(eww-history-limit): New variable.
[emacs.git] / src / w32.c
blobf014cd73a767b9e6a997b9a7d89e421c0692d8da
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2014 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <float.h> /* for DBL_EPSILON */
29 #include <io.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <sys/file.h>
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
36 #include <sys/time.h>
37 #include <sys/utime.h>
38 #include <math.h>
40 /* must include CRT headers *before* config.h */
42 #include <config.h>
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
45 #undef access
46 #undef chdir
47 #undef chmod
48 #undef creat
49 #undef ctime
50 #undef fopen
51 #undef link
52 #undef mkdir
53 #undef open
54 #undef rename
55 #undef rmdir
56 #undef unlink
58 #undef close
59 #undef dup
60 #undef dup2
61 #undef pipe
62 #undef read
63 #undef write
65 #undef strerror
67 #undef localtime
69 #include "lisp.h"
70 #include "epaths.h" /* for SHELL */
72 #include <pwd.h>
73 #include <grp.h>
75 /* MinGW64 (_W64) defines these in its _mingw.h. */
76 #ifndef _ANONYMOUS_UNION
77 # define _ANONYMOUS_UNION
78 #endif
79 #ifndef _ANONYMOUS_STRUCT
80 # define _ANONYMOUS_STRUCT
81 #endif
82 #include <windows.h>
83 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
84 use a different name to avoid compilation problems. */
85 typedef struct _MEMORY_STATUS_EX {
86 DWORD dwLength;
87 DWORD dwMemoryLoad;
88 DWORDLONG ullTotalPhys;
89 DWORDLONG ullAvailPhys;
90 DWORDLONG ullTotalPageFile;
91 DWORDLONG ullAvailPageFile;
92 DWORDLONG ullTotalVirtual;
93 DWORDLONG ullAvailVirtual;
94 DWORDLONG ullAvailExtendedVirtual;
95 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
97 /* These are here so that GDB would know about these data types. This
98 allows to attach GDB to Emacs when a fatal exception is triggered
99 and Windows pops up the "application needs to be closed" dialog.
100 At that point, _gnu_exception_handler, the top-level exception
101 handler installed by the MinGW startup code, is somewhere on the
102 call-stack of the main thread, so going to that call frame and
103 looking at the argument to _gnu_exception_handler, which is a
104 PEXCEPTION_POINTERS pointer, can reveal the exception code
105 (excptr->ExceptionRecord->ExceptionCode) and the address where the
106 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
107 well as some additional information specific to the exception. */
108 PEXCEPTION_POINTERS excptr;
109 PEXCEPTION_RECORD excprec;
110 PCONTEXT ctxrec;
112 #include <lmcons.h>
113 #include <shlobj.h>
115 #include <tlhelp32.h>
116 #include <psapi.h>
117 #ifndef _MSC_VER
118 #include <w32api.h>
119 #endif
120 #if _WIN32_WINNT < 0x0500
121 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
122 /* This either is not in psapi.h or guarded by higher value of
123 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
124 defines it in psapi.h */
125 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
126 DWORD cb;
127 DWORD PageFaultCount;
128 SIZE_T PeakWorkingSetSize;
129 SIZE_T WorkingSetSize;
130 SIZE_T QuotaPeakPagedPoolUsage;
131 SIZE_T QuotaPagedPoolUsage;
132 SIZE_T QuotaPeakNonPagedPoolUsage;
133 SIZE_T QuotaNonPagedPoolUsage;
134 SIZE_T PagefileUsage;
135 SIZE_T PeakPagefileUsage;
136 SIZE_T PrivateUsage;
137 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
138 #endif
139 #endif
141 #include <winioctl.h>
142 #include <aclapi.h>
143 #include <sddl.h>
145 #include <sys/acl.h>
146 #include <acl.h>
148 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
149 define them by hand if not already defined. */
150 #ifndef SDDL_REVISION_1
151 #define SDDL_REVISION_1 1
152 #endif /* SDDL_REVISION_1 */
154 #if defined(_MSC_VER) || defined(_W64)
155 /* MSVC and MinGW64 don't provide the definition of
156 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
157 which cannot be included because it triggers conflicts with other
158 Windows API headers. So we define it here by hand. */
160 typedef struct _REPARSE_DATA_BUFFER {
161 ULONG ReparseTag;
162 USHORT ReparseDataLength;
163 USHORT Reserved;
164 union {
165 struct {
166 USHORT SubstituteNameOffset;
167 USHORT SubstituteNameLength;
168 USHORT PrintNameOffset;
169 USHORT PrintNameLength;
170 ULONG Flags;
171 WCHAR PathBuffer[1];
172 } SymbolicLinkReparseBuffer;
173 struct {
174 USHORT SubstituteNameOffset;
175 USHORT SubstituteNameLength;
176 USHORT PrintNameOffset;
177 USHORT PrintNameLength;
178 WCHAR PathBuffer[1];
179 } MountPointReparseBuffer;
180 struct {
181 UCHAR DataBuffer[1];
182 } GenericReparseBuffer;
183 } DUMMYUNIONNAME;
184 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
186 #ifndef FILE_DEVICE_FILE_SYSTEM
187 #define FILE_DEVICE_FILE_SYSTEM 9
188 #endif
189 #ifndef METHOD_BUFFERED
190 #define METHOD_BUFFERED 0
191 #endif
192 #ifndef FILE_ANY_ACCESS
193 #define FILE_ANY_ACCESS 0x00000000
194 #endif
195 #ifndef CTL_CODE
196 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
197 #endif
198 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
199 #ifndef FSCTL_GET_REPARSE_POINT
200 #define FSCTL_GET_REPARSE_POINT \
201 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
202 #endif
203 #endif
205 /* TCP connection support. */
206 #include <sys/socket.h>
207 #undef socket
208 #undef bind
209 #undef connect
210 #undef htons
211 #undef ntohs
212 #undef inet_addr
213 #undef gethostname
214 #undef gethostbyname
215 #undef getservbyname
216 #undef getpeername
217 #undef shutdown
218 #undef setsockopt
219 #undef listen
220 #undef getsockname
221 #undef accept
222 #undef recvfrom
223 #undef sendto
225 #include <iphlpapi.h> /* should be after winsock2.h */
227 #include "w32.h"
228 #include <dirent.h>
229 #include "w32common.h"
230 #include "w32heap.h"
231 #include "w32select.h"
232 #include "systime.h"
233 #include "dispextern.h" /* for xstrcasecmp */
234 #include "coding.h" /* for Vlocale_coding_system */
236 #include "careadlinkat.h"
237 #include "allocator.h"
239 /* For serial_configure and serial_open. */
240 #include "process.h"
242 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
243 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
245 Lisp_Object QCloaded_from;
247 void globals_of_w32 (void);
248 static DWORD get_rid (PSID);
249 static int is_symlink (const char *);
250 static char * chase_symlinks (const char *);
251 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
252 static int restore_privilege (TOKEN_PRIVILEGES *);
253 static BOOL WINAPI revert_to_self (void);
255 static int sys_access (const char *, int);
256 extern void *e_malloc (size_t);
257 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
258 struct timespec *, void *);
259 extern int sys_dup (int);
264 /* Initialization states.
266 WARNING: If you add any more such variables for additional APIs,
267 you MUST add initialization for them to globals_of_w32
268 below. This is because these variables might get set
269 to non-NULL values during dumping, but the dumped Emacs
270 cannot reuse those values, because it could be run on a
271 different version of the OS, where API addresses are
272 different. */
273 static BOOL g_b_init_is_windows_9x;
274 static BOOL g_b_init_open_process_token;
275 static BOOL g_b_init_get_token_information;
276 static BOOL g_b_init_lookup_account_sid;
277 static BOOL g_b_init_get_sid_sub_authority;
278 static BOOL g_b_init_get_sid_sub_authority_count;
279 static BOOL g_b_init_get_security_info;
280 static BOOL g_b_init_get_file_security_w;
281 static BOOL g_b_init_get_file_security_a;
282 static BOOL g_b_init_get_security_descriptor_owner;
283 static BOOL g_b_init_get_security_descriptor_group;
284 static BOOL g_b_init_is_valid_sid;
285 static BOOL g_b_init_create_toolhelp32_snapshot;
286 static BOOL g_b_init_process32_first;
287 static BOOL g_b_init_process32_next;
288 static BOOL g_b_init_open_thread_token;
289 static BOOL g_b_init_impersonate_self;
290 static BOOL g_b_init_revert_to_self;
291 static BOOL g_b_init_get_process_memory_info;
292 static BOOL g_b_init_get_process_working_set_size;
293 static BOOL g_b_init_global_memory_status;
294 static BOOL g_b_init_global_memory_status_ex;
295 static BOOL g_b_init_get_length_sid;
296 static BOOL g_b_init_equal_sid;
297 static BOOL g_b_init_copy_sid;
298 static BOOL g_b_init_get_native_system_info;
299 static BOOL g_b_init_get_system_times;
300 static BOOL g_b_init_create_symbolic_link_w;
301 static BOOL g_b_init_create_symbolic_link_a;
302 static BOOL g_b_init_get_security_descriptor_dacl;
303 static BOOL g_b_init_convert_sd_to_sddl;
304 static BOOL g_b_init_convert_sddl_to_sd;
305 static BOOL g_b_init_is_valid_security_descriptor;
306 static BOOL g_b_init_set_file_security_w;
307 static BOOL g_b_init_set_file_security_a;
308 static BOOL g_b_init_set_named_security_info_w;
309 static BOOL g_b_init_set_named_security_info_a;
310 static BOOL g_b_init_get_adapters_info;
312 BOOL g_b_init_compare_string_w;
315 BEGIN: Wrapper functions around OpenProcessToken
316 and other functions in advapi32.dll that are only
317 supported in Windows NT / 2k / XP
319 /* ** Function pointer typedefs ** */
320 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
321 HANDLE ProcessHandle,
322 DWORD DesiredAccess,
323 PHANDLE TokenHandle);
324 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
325 HANDLE TokenHandle,
326 TOKEN_INFORMATION_CLASS TokenInformationClass,
327 LPVOID TokenInformation,
328 DWORD TokenInformationLength,
329 PDWORD ReturnLength);
330 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
331 HANDLE process_handle,
332 LPFILETIME creation_time,
333 LPFILETIME exit_time,
334 LPFILETIME kernel_time,
335 LPFILETIME user_time);
337 GetProcessTimes_Proc get_process_times_fn = NULL;
339 #ifdef _UNICODE
340 const char * const LookupAccountSid_Name = "LookupAccountSidW";
341 #else
342 const char * const LookupAccountSid_Name = "LookupAccountSidA";
343 #endif
344 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
345 LPCTSTR lpSystemName,
346 PSID Sid,
347 LPTSTR Name,
348 LPDWORD cbName,
349 LPTSTR DomainName,
350 LPDWORD cbDomainName,
351 PSID_NAME_USE peUse);
352 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
353 PSID pSid,
354 DWORD n);
355 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
356 PSID pSid);
357 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
358 HANDLE handle,
359 SE_OBJECT_TYPE ObjectType,
360 SECURITY_INFORMATION SecurityInfo,
361 PSID *ppsidOwner,
362 PSID *ppsidGroup,
363 PACL *ppDacl,
364 PACL *ppSacl,
365 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
366 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
367 LPCWSTR lpFileName,
368 SECURITY_INFORMATION RequestedInformation,
369 PSECURITY_DESCRIPTOR pSecurityDescriptor,
370 DWORD nLength,
371 LPDWORD lpnLengthNeeded);
372 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
373 LPCSTR lpFileName,
374 SECURITY_INFORMATION RequestedInformation,
375 PSECURITY_DESCRIPTOR pSecurityDescriptor,
376 DWORD nLength,
377 LPDWORD lpnLengthNeeded);
378 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
379 LPCWSTR lpFileName,
380 SECURITY_INFORMATION SecurityInformation,
381 PSECURITY_DESCRIPTOR pSecurityDescriptor);
382 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
383 LPCSTR lpFileName,
384 SECURITY_INFORMATION SecurityInformation,
385 PSECURITY_DESCRIPTOR pSecurityDescriptor);
386 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
387 LPCWSTR lpObjectName,
388 SE_OBJECT_TYPE ObjectType,
389 SECURITY_INFORMATION SecurityInformation,
390 PSID psidOwner,
391 PSID psidGroup,
392 PACL pDacl,
393 PACL pSacl);
394 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
395 LPCSTR lpObjectName,
396 SE_OBJECT_TYPE ObjectType,
397 SECURITY_INFORMATION SecurityInformation,
398 PSID psidOwner,
399 PSID psidGroup,
400 PACL pDacl,
401 PACL pSacl);
402 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
403 PSECURITY_DESCRIPTOR pSecurityDescriptor,
404 PSID *pOwner,
405 LPBOOL lpbOwnerDefaulted);
406 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
407 PSECURITY_DESCRIPTOR pSecurityDescriptor,
408 PSID *pGroup,
409 LPBOOL lpbGroupDefaulted);
410 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
411 PSECURITY_DESCRIPTOR pSecurityDescriptor,
412 LPBOOL lpbDaclPresent,
413 PACL *pDacl,
414 LPBOOL lpbDaclDefaulted);
415 typedef BOOL (WINAPI * IsValidSid_Proc) (
416 PSID sid);
417 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
418 DWORD dwFlags,
419 DWORD th32ProcessID);
420 typedef BOOL (WINAPI * Process32First_Proc) (
421 HANDLE hSnapshot,
422 LPPROCESSENTRY32 lppe);
423 typedef BOOL (WINAPI * Process32Next_Proc) (
424 HANDLE hSnapshot,
425 LPPROCESSENTRY32 lppe);
426 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
427 HANDLE ThreadHandle,
428 DWORD DesiredAccess,
429 BOOL OpenAsSelf,
430 PHANDLE TokenHandle);
431 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
432 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
433 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
434 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
435 HANDLE Process,
436 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
437 DWORD cb);
438 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
439 HANDLE hProcess,
440 PSIZE_T lpMinimumWorkingSetSize,
441 PSIZE_T lpMaximumWorkingSetSize);
442 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
443 LPMEMORYSTATUS lpBuffer);
444 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
445 LPMEMORY_STATUS_EX lpBuffer);
446 typedef BOOL (WINAPI * CopySid_Proc) (
447 DWORD nDestinationSidLength,
448 PSID pDestinationSid,
449 PSID pSourceSid);
450 typedef BOOL (WINAPI * EqualSid_Proc) (
451 PSID pSid1,
452 PSID pSid2);
453 typedef DWORD (WINAPI * GetLengthSid_Proc) (
454 PSID pSid);
455 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
456 LPSYSTEM_INFO lpSystemInfo);
457 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
458 LPFILETIME lpIdleTime,
459 LPFILETIME lpKernelTime,
460 LPFILETIME lpUserTime);
461 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
462 LPCWSTR lpSymlinkFileName,
463 LPCWSTR lpTargetFileName,
464 DWORD dwFlags);
465 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
466 LPCSTR lpSymlinkFileName,
467 LPCSTR lpTargetFileName,
468 DWORD dwFlags);
469 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
470 LPCTSTR StringSecurityDescriptor,
471 DWORD StringSDRevision,
472 PSECURITY_DESCRIPTOR *SecurityDescriptor,
473 PULONG SecurityDescriptorSize);
474 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
475 PSECURITY_DESCRIPTOR SecurityDescriptor,
476 DWORD RequestedStringSDRevision,
477 SECURITY_INFORMATION SecurityInformation,
478 LPTSTR *StringSecurityDescriptor,
479 PULONG StringSecurityDescriptorLen);
480 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
481 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
482 PIP_ADAPTER_INFO pAdapterInfo,
483 PULONG pOutBufLen);
485 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
486 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
488 /* ** A utility function ** */
489 static BOOL
490 is_windows_9x (void)
492 static BOOL s_b_ret = 0;
493 OSVERSIONINFO os_ver;
494 if (g_b_init_is_windows_9x == 0)
496 g_b_init_is_windows_9x = 1;
497 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
498 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
499 if (GetVersionEx (&os_ver))
501 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
504 return s_b_ret;
507 static Lisp_Object ltime (ULONGLONG);
509 /* Get total user and system times for get-internal-run-time.
510 Returns a list of integers if the times are provided by the OS
511 (NT derivatives), otherwise it returns the result of current-time. */
512 Lisp_Object
513 w32_get_internal_run_time (void)
515 if (get_process_times_fn)
517 FILETIME create, exit, kernel, user;
518 HANDLE proc = GetCurrentProcess ();
519 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
521 LARGE_INTEGER user_int, kernel_int, total;
522 user_int.LowPart = user.dwLowDateTime;
523 user_int.HighPart = user.dwHighDateTime;
524 kernel_int.LowPart = kernel.dwLowDateTime;
525 kernel_int.HighPart = kernel.dwHighDateTime;
526 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
527 return ltime (total.QuadPart);
531 return Fcurrent_time ();
534 /* ** The wrapper functions ** */
536 static BOOL WINAPI
537 open_process_token (HANDLE ProcessHandle,
538 DWORD DesiredAccess,
539 PHANDLE TokenHandle)
541 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
542 HMODULE hm_advapi32 = NULL;
543 if (is_windows_9x () == TRUE)
545 return FALSE;
547 if (g_b_init_open_process_token == 0)
549 g_b_init_open_process_token = 1;
550 hm_advapi32 = LoadLibrary ("Advapi32.dll");
551 s_pfn_Open_Process_Token =
552 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
554 if (s_pfn_Open_Process_Token == NULL)
556 return FALSE;
558 return (
559 s_pfn_Open_Process_Token (
560 ProcessHandle,
561 DesiredAccess,
562 TokenHandle)
566 static BOOL WINAPI
567 get_token_information (HANDLE TokenHandle,
568 TOKEN_INFORMATION_CLASS TokenInformationClass,
569 LPVOID TokenInformation,
570 DWORD TokenInformationLength,
571 PDWORD ReturnLength)
573 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
574 HMODULE hm_advapi32 = NULL;
575 if (is_windows_9x () == TRUE)
577 return FALSE;
579 if (g_b_init_get_token_information == 0)
581 g_b_init_get_token_information = 1;
582 hm_advapi32 = LoadLibrary ("Advapi32.dll");
583 s_pfn_Get_Token_Information =
584 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
586 if (s_pfn_Get_Token_Information == NULL)
588 return FALSE;
590 return (
591 s_pfn_Get_Token_Information (
592 TokenHandle,
593 TokenInformationClass,
594 TokenInformation,
595 TokenInformationLength,
596 ReturnLength)
600 static BOOL WINAPI
601 lookup_account_sid (LPCTSTR lpSystemName,
602 PSID Sid,
603 LPTSTR Name,
604 LPDWORD cbName,
605 LPTSTR DomainName,
606 LPDWORD cbDomainName,
607 PSID_NAME_USE peUse)
609 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
610 HMODULE hm_advapi32 = NULL;
611 if (is_windows_9x () == TRUE)
613 return FALSE;
615 if (g_b_init_lookup_account_sid == 0)
617 g_b_init_lookup_account_sid = 1;
618 hm_advapi32 = LoadLibrary ("Advapi32.dll");
619 s_pfn_Lookup_Account_Sid =
620 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
622 if (s_pfn_Lookup_Account_Sid == NULL)
624 return FALSE;
626 return (
627 s_pfn_Lookup_Account_Sid (
628 lpSystemName,
629 Sid,
630 Name,
631 cbName,
632 DomainName,
633 cbDomainName,
634 peUse)
638 static PDWORD WINAPI
639 get_sid_sub_authority (PSID pSid, DWORD n)
641 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
642 static DWORD zero = 0U;
643 HMODULE hm_advapi32 = NULL;
644 if (is_windows_9x () == TRUE)
646 return &zero;
648 if (g_b_init_get_sid_sub_authority == 0)
650 g_b_init_get_sid_sub_authority = 1;
651 hm_advapi32 = LoadLibrary ("Advapi32.dll");
652 s_pfn_Get_Sid_Sub_Authority =
653 (GetSidSubAuthority_Proc) GetProcAddress (
654 hm_advapi32, "GetSidSubAuthority");
656 if (s_pfn_Get_Sid_Sub_Authority == NULL)
658 return &zero;
660 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
663 static PUCHAR WINAPI
664 get_sid_sub_authority_count (PSID pSid)
666 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
667 static UCHAR zero = 0U;
668 HMODULE hm_advapi32 = NULL;
669 if (is_windows_9x () == TRUE)
671 return &zero;
673 if (g_b_init_get_sid_sub_authority_count == 0)
675 g_b_init_get_sid_sub_authority_count = 1;
676 hm_advapi32 = LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_Sid_Sub_Authority_Count =
678 (GetSidSubAuthorityCount_Proc) GetProcAddress (
679 hm_advapi32, "GetSidSubAuthorityCount");
681 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
683 return &zero;
685 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
688 static DWORD WINAPI
689 get_security_info (HANDLE handle,
690 SE_OBJECT_TYPE ObjectType,
691 SECURITY_INFORMATION SecurityInfo,
692 PSID *ppsidOwner,
693 PSID *ppsidGroup,
694 PACL *ppDacl,
695 PACL *ppSacl,
696 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
698 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
699 HMODULE hm_advapi32 = NULL;
700 if (is_windows_9x () == TRUE)
702 return FALSE;
704 if (g_b_init_get_security_info == 0)
706 g_b_init_get_security_info = 1;
707 hm_advapi32 = LoadLibrary ("Advapi32.dll");
708 s_pfn_Get_Security_Info =
709 (GetSecurityInfo_Proc) GetProcAddress (
710 hm_advapi32, "GetSecurityInfo");
712 if (s_pfn_Get_Security_Info == NULL)
714 return FALSE;
716 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
717 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
718 ppSecurityDescriptor));
721 static BOOL WINAPI
722 get_file_security (const char *lpFileName,
723 SECURITY_INFORMATION RequestedInformation,
724 PSECURITY_DESCRIPTOR pSecurityDescriptor,
725 DWORD nLength,
726 LPDWORD lpnLengthNeeded)
728 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
729 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
730 HMODULE hm_advapi32 = NULL;
731 if (is_windows_9x () == TRUE)
733 errno = ENOTSUP;
734 return FALSE;
736 if (w32_unicode_filenames)
738 wchar_t filename_w[MAX_PATH];
740 if (g_b_init_get_file_security_w == 0)
742 g_b_init_get_file_security_w = 1;
743 hm_advapi32 = LoadLibrary ("Advapi32.dll");
744 s_pfn_Get_File_SecurityW =
745 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
746 "GetFileSecurityW");
748 if (s_pfn_Get_File_SecurityW == NULL)
750 errno = ENOTSUP;
751 return FALSE;
753 filename_to_utf16 (lpFileName, filename_w);
754 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
755 pSecurityDescriptor, nLength,
756 lpnLengthNeeded));
758 else
760 char filename_a[MAX_PATH];
762 if (g_b_init_get_file_security_a == 0)
764 g_b_init_get_file_security_a = 1;
765 hm_advapi32 = LoadLibrary ("Advapi32.dll");
766 s_pfn_Get_File_SecurityA =
767 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
768 "GetFileSecurityA");
770 if (s_pfn_Get_File_SecurityA == NULL)
772 errno = ENOTSUP;
773 return FALSE;
775 filename_to_ansi (lpFileName, filename_a);
776 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
777 pSecurityDescriptor, nLength,
778 lpnLengthNeeded));
782 static BOOL WINAPI
783 set_file_security (const char *lpFileName,
784 SECURITY_INFORMATION SecurityInformation,
785 PSECURITY_DESCRIPTOR pSecurityDescriptor)
787 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
788 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
789 HMODULE hm_advapi32 = NULL;
790 if (is_windows_9x () == TRUE)
792 errno = ENOTSUP;
793 return FALSE;
795 if (w32_unicode_filenames)
797 wchar_t filename_w[MAX_PATH];
799 if (g_b_init_set_file_security_w == 0)
801 g_b_init_set_file_security_w = 1;
802 hm_advapi32 = LoadLibrary ("Advapi32.dll");
803 s_pfn_Set_File_SecurityW =
804 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
805 "SetFileSecurityW");
807 if (s_pfn_Set_File_SecurityW == NULL)
809 errno = ENOTSUP;
810 return FALSE;
812 filename_to_utf16 (lpFileName, filename_w);
813 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
814 pSecurityDescriptor));
816 else
818 char filename_a[MAX_PATH];
820 if (g_b_init_set_file_security_a == 0)
822 g_b_init_set_file_security_a = 1;
823 hm_advapi32 = LoadLibrary ("Advapi32.dll");
824 s_pfn_Set_File_SecurityA =
825 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
826 "SetFileSecurityA");
828 if (s_pfn_Set_File_SecurityA == NULL)
830 errno = ENOTSUP;
831 return FALSE;
833 filename_to_ansi (lpFileName, filename_a);
834 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
835 pSecurityDescriptor));
839 static DWORD WINAPI
840 set_named_security_info (LPCTSTR lpObjectName,
841 SE_OBJECT_TYPE ObjectType,
842 SECURITY_INFORMATION SecurityInformation,
843 PSID psidOwner,
844 PSID psidGroup,
845 PACL pDacl,
846 PACL pSacl)
848 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
849 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
850 HMODULE hm_advapi32 = NULL;
851 if (is_windows_9x () == TRUE)
853 errno = ENOTSUP;
854 return ENOTSUP;
856 if (w32_unicode_filenames)
858 wchar_t filename_w[MAX_PATH];
860 if (g_b_init_set_named_security_info_w == 0)
862 g_b_init_set_named_security_info_w = 1;
863 hm_advapi32 = LoadLibrary ("Advapi32.dll");
864 s_pfn_Set_Named_Security_InfoW =
865 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
866 "SetNamedSecurityInfoW");
868 if (s_pfn_Set_Named_Security_InfoW == NULL)
870 errno = ENOTSUP;
871 return ENOTSUP;
873 filename_to_utf16 (lpObjectName, filename_w);
874 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
875 SecurityInformation, psidOwner,
876 psidGroup, pDacl, pSacl));
878 else
880 char filename_a[MAX_PATH];
882 if (g_b_init_set_named_security_info_a == 0)
884 g_b_init_set_named_security_info_a = 1;
885 hm_advapi32 = LoadLibrary ("Advapi32.dll");
886 s_pfn_Set_Named_Security_InfoA =
887 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
888 "SetNamedSecurityInfoA");
890 if (s_pfn_Set_Named_Security_InfoA == NULL)
892 errno = ENOTSUP;
893 return ENOTSUP;
895 filename_to_ansi (lpObjectName, filename_a);
896 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
897 SecurityInformation, psidOwner,
898 psidGroup, pDacl, pSacl));
902 static BOOL WINAPI
903 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
904 PSID *pOwner,
905 LPBOOL lpbOwnerDefaulted)
907 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
908 HMODULE hm_advapi32 = NULL;
909 if (is_windows_9x () == TRUE)
911 errno = ENOTSUP;
912 return FALSE;
914 if (g_b_init_get_security_descriptor_owner == 0)
916 g_b_init_get_security_descriptor_owner = 1;
917 hm_advapi32 = LoadLibrary ("Advapi32.dll");
918 s_pfn_Get_Security_Descriptor_Owner =
919 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
920 hm_advapi32, "GetSecurityDescriptorOwner");
922 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
924 errno = ENOTSUP;
925 return FALSE;
927 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
928 lpbOwnerDefaulted));
931 static BOOL WINAPI
932 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
933 PSID *pGroup,
934 LPBOOL lpbGroupDefaulted)
936 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
937 HMODULE hm_advapi32 = NULL;
938 if (is_windows_9x () == TRUE)
940 errno = ENOTSUP;
941 return FALSE;
943 if (g_b_init_get_security_descriptor_group == 0)
945 g_b_init_get_security_descriptor_group = 1;
946 hm_advapi32 = LoadLibrary ("Advapi32.dll");
947 s_pfn_Get_Security_Descriptor_Group =
948 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
949 hm_advapi32, "GetSecurityDescriptorGroup");
951 if (s_pfn_Get_Security_Descriptor_Group == NULL)
953 errno = ENOTSUP;
954 return FALSE;
956 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
957 lpbGroupDefaulted));
960 static BOOL WINAPI
961 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
962 LPBOOL lpbDaclPresent,
963 PACL *pDacl,
964 LPBOOL lpbDaclDefaulted)
966 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
967 HMODULE hm_advapi32 = NULL;
968 if (is_windows_9x () == TRUE)
970 errno = ENOTSUP;
971 return FALSE;
973 if (g_b_init_get_security_descriptor_dacl == 0)
975 g_b_init_get_security_descriptor_dacl = 1;
976 hm_advapi32 = LoadLibrary ("Advapi32.dll");
977 s_pfn_Get_Security_Descriptor_Dacl =
978 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
979 hm_advapi32, "GetSecurityDescriptorDacl");
981 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
983 errno = ENOTSUP;
984 return FALSE;
986 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
987 lpbDaclPresent, pDacl,
988 lpbDaclDefaulted));
991 static BOOL WINAPI
992 is_valid_sid (PSID sid)
994 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
995 HMODULE hm_advapi32 = NULL;
996 if (is_windows_9x () == TRUE)
998 return FALSE;
1000 if (g_b_init_is_valid_sid == 0)
1002 g_b_init_is_valid_sid = 1;
1003 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1004 s_pfn_Is_Valid_Sid =
1005 (IsValidSid_Proc) GetProcAddress (
1006 hm_advapi32, "IsValidSid");
1008 if (s_pfn_Is_Valid_Sid == NULL)
1010 return FALSE;
1012 return (s_pfn_Is_Valid_Sid (sid));
1015 static BOOL WINAPI
1016 equal_sid (PSID sid1, PSID sid2)
1018 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1019 HMODULE hm_advapi32 = NULL;
1020 if (is_windows_9x () == TRUE)
1022 return FALSE;
1024 if (g_b_init_equal_sid == 0)
1026 g_b_init_equal_sid = 1;
1027 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1028 s_pfn_Equal_Sid =
1029 (EqualSid_Proc) GetProcAddress (
1030 hm_advapi32, "EqualSid");
1032 if (s_pfn_Equal_Sid == NULL)
1034 return FALSE;
1036 return (s_pfn_Equal_Sid (sid1, sid2));
1039 static DWORD WINAPI
1040 get_length_sid (PSID sid)
1042 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1043 HMODULE hm_advapi32 = NULL;
1044 if (is_windows_9x () == TRUE)
1046 return 0;
1048 if (g_b_init_get_length_sid == 0)
1050 g_b_init_get_length_sid = 1;
1051 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1052 s_pfn_Get_Length_Sid =
1053 (GetLengthSid_Proc) GetProcAddress (
1054 hm_advapi32, "GetLengthSid");
1056 if (s_pfn_Get_Length_Sid == NULL)
1058 return 0;
1060 return (s_pfn_Get_Length_Sid (sid));
1063 static BOOL WINAPI
1064 copy_sid (DWORD destlen, PSID dest, PSID src)
1066 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1067 HMODULE hm_advapi32 = NULL;
1068 if (is_windows_9x () == TRUE)
1070 return FALSE;
1072 if (g_b_init_copy_sid == 0)
1074 g_b_init_copy_sid = 1;
1075 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1076 s_pfn_Copy_Sid =
1077 (CopySid_Proc) GetProcAddress (
1078 hm_advapi32, "CopySid");
1080 if (s_pfn_Copy_Sid == NULL)
1082 return FALSE;
1084 return (s_pfn_Copy_Sid (destlen, dest, src));
1088 END: Wrapper functions around OpenProcessToken
1089 and other functions in advapi32.dll that are only
1090 supported in Windows NT / 2k / XP
1093 static void WINAPI
1094 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1096 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1097 if (is_windows_9x () != TRUE)
1099 if (g_b_init_get_native_system_info == 0)
1101 g_b_init_get_native_system_info = 1;
1102 s_pfn_Get_Native_System_Info =
1103 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1104 "GetNativeSystemInfo");
1106 if (s_pfn_Get_Native_System_Info != NULL)
1107 s_pfn_Get_Native_System_Info (lpSystemInfo);
1109 else
1110 lpSystemInfo->dwNumberOfProcessors = -1;
1113 static BOOL WINAPI
1114 get_system_times (LPFILETIME lpIdleTime,
1115 LPFILETIME lpKernelTime,
1116 LPFILETIME lpUserTime)
1118 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1119 if (is_windows_9x () == TRUE)
1121 return FALSE;
1123 if (g_b_init_get_system_times == 0)
1125 g_b_init_get_system_times = 1;
1126 s_pfn_Get_System_times =
1127 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1128 "GetSystemTimes");
1130 if (s_pfn_Get_System_times == NULL)
1131 return FALSE;
1132 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1135 static BOOLEAN WINAPI
1136 create_symbolic_link (LPCSTR lpSymlinkFilename,
1137 LPCSTR lpTargetFileName,
1138 DWORD dwFlags)
1140 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1141 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1142 BOOLEAN retval;
1144 if (is_windows_9x () == TRUE)
1146 errno = ENOSYS;
1147 return 0;
1149 if (w32_unicode_filenames)
1151 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1153 if (g_b_init_create_symbolic_link_w == 0)
1155 g_b_init_create_symbolic_link_w = 1;
1156 s_pfn_Create_Symbolic_LinkW =
1157 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1158 "CreateSymbolicLinkW");
1160 if (s_pfn_Create_Symbolic_LinkW == NULL)
1162 errno = ENOSYS;
1163 return 0;
1166 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1167 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1168 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1169 /* If we were denied creation of the symlink, try again after
1170 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1171 if (!retval)
1173 TOKEN_PRIVILEGES priv_current;
1175 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1176 &priv_current))
1178 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1179 restore_privilege (&priv_current);
1180 revert_to_self ();
1184 else
1186 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1188 if (g_b_init_create_symbolic_link_a == 0)
1190 g_b_init_create_symbolic_link_a = 1;
1191 s_pfn_Create_Symbolic_LinkA =
1192 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1193 "CreateSymbolicLinkA");
1195 if (s_pfn_Create_Symbolic_LinkA == NULL)
1197 errno = ENOSYS;
1198 return 0;
1201 filename_to_ansi (lpSymlinkFilename, symfn_a);
1202 filename_to_ansi (lpTargetFileName, tgtfn_a);
1203 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1204 /* If we were denied creation of the symlink, try again after
1205 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1206 if (!retval)
1208 TOKEN_PRIVILEGES priv_current;
1210 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1211 &priv_current))
1213 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1214 restore_privilege (&priv_current);
1215 revert_to_self ();
1219 return retval;
1222 static BOOL WINAPI
1223 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1225 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1227 if (is_windows_9x () == TRUE)
1229 errno = ENOTSUP;
1230 return FALSE;
1233 if (g_b_init_is_valid_security_descriptor == 0)
1235 g_b_init_is_valid_security_descriptor = 1;
1236 s_pfn_Is_Valid_Security_Descriptor_Proc =
1237 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1238 "IsValidSecurityDescriptor");
1240 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1242 errno = ENOTSUP;
1243 return FALSE;
1246 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1249 static BOOL WINAPI
1250 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1251 DWORD RequestedStringSDRevision,
1252 SECURITY_INFORMATION SecurityInformation,
1253 LPTSTR *StringSecurityDescriptor,
1254 PULONG StringSecurityDescriptorLen)
1256 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1257 BOOL retval;
1259 if (is_windows_9x () == TRUE)
1261 errno = ENOTSUP;
1262 return FALSE;
1265 if (g_b_init_convert_sd_to_sddl == 0)
1267 g_b_init_convert_sd_to_sddl = 1;
1268 #ifdef _UNICODE
1269 s_pfn_Convert_SD_To_SDDL =
1270 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1271 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1272 #else
1273 s_pfn_Convert_SD_To_SDDL =
1274 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1275 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1276 #endif
1278 if (s_pfn_Convert_SD_To_SDDL == NULL)
1280 errno = ENOTSUP;
1281 return FALSE;
1284 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1285 RequestedStringSDRevision,
1286 SecurityInformation,
1287 StringSecurityDescriptor,
1288 StringSecurityDescriptorLen);
1290 return retval;
1293 static BOOL WINAPI
1294 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1295 DWORD StringSDRevision,
1296 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1297 PULONG SecurityDescriptorSize)
1299 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1300 BOOL retval;
1302 if (is_windows_9x () == TRUE)
1304 errno = ENOTSUP;
1305 return FALSE;
1308 if (g_b_init_convert_sddl_to_sd == 0)
1310 g_b_init_convert_sddl_to_sd = 1;
1311 #ifdef _UNICODE
1312 s_pfn_Convert_SDDL_To_SD =
1313 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1314 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1315 #else
1316 s_pfn_Convert_SDDL_To_SD =
1317 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1318 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1319 #endif
1321 if (s_pfn_Convert_SDDL_To_SD == NULL)
1323 errno = ENOTSUP;
1324 return FALSE;
1327 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1328 StringSDRevision,
1329 SecurityDescriptor,
1330 SecurityDescriptorSize);
1332 return retval;
1335 static DWORD WINAPI
1336 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1338 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1339 HMODULE hm_iphlpapi = NULL;
1341 if (is_windows_9x () == TRUE)
1342 return ERROR_NOT_SUPPORTED;
1344 if (g_b_init_get_adapters_info == 0)
1346 g_b_init_get_adapters_info = 1;
1347 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1348 if (hm_iphlpapi)
1349 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1350 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1352 if (s_pfn_Get_Adapters_Info == NULL)
1353 return ERROR_NOT_SUPPORTED;
1354 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1359 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1360 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1362 This is called from alloc.c:valid_pointer_p. */
1364 w32_valid_pointer_p (void *p, int size)
1366 SIZE_T done;
1367 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1369 if (h)
1371 unsigned char *buf = alloca (size);
1372 int retval = ReadProcessMemory (h, p, buf, size, &done);
1374 CloseHandle (h);
1375 return retval;
1377 else
1378 return -1;
1383 /* Here's an overview of how the Windows build supports file names
1384 that cannot be encoded by the current system codepage.
1386 From the POV of Lisp and layers of C code above the functions here,
1387 Emacs on Windows pretends that its file names are encoded in UTF-8;
1388 see encode_file and decode_file on coding.c. Any file name that is
1389 passed as a unibyte string to C functions defined here is assumed
1390 to be in UTF-8 encoding. Any file name returned by functions
1391 defined here must be in UTF-8 encoding, with only a few exceptions
1392 reserved for a couple of special cases. (Be sure to use
1393 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1394 as they can be much longer than MAX_PATH!)
1396 The UTF-8 encoded file names cannot be passed to system APIs, as
1397 Windows does not support that. Therefore, they are converted
1398 either to UTF-16 or to the ANSI codepage, depending on the value of
1399 w32-unicode-filenames, before calling any system APIs or CRT library
1400 functions. The default value of that variable is determined by the
1401 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1402 user can change that default (although I don't see why would she
1403 want to).
1405 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1406 filename_from_utf16, and filename_from_ansi, are the workhorses of
1407 these conversions. They rely on Windows native APIs
1408 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1409 functions from coding.c here, because they allocate memory, which
1410 is a bad idea on the level of libc, which is what the functions
1411 here emulate. (If you worry about performance due to constant
1412 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1413 it was measured to take only a few microseconds on a not-so-fast
1414 machine, and second, that's exactly what the ANSI APIs we used
1415 before did anyway, because they are just thin wrappers around the
1416 Unicode APIs.)
1418 The variables file-name-coding-system and default-file-name-coding-system
1419 still exist, but are actually used only when a file name needs to
1420 be converted to the ANSI codepage. This happens all the time when
1421 w32-unicode-filenames is nil, but can also happen from time to time
1422 when it is t. Otherwise, these variables have no effect on file-name
1423 encoding when w32-unicode-filenames is t; this is similar to
1424 selection-coding-system.
1426 This arrangement works very well, but it has a few gotchas and
1427 limitations:
1429 . Lisp code that encodes or decodes file names manually should
1430 normally use 'utf-8' as the coding-system on Windows,
1431 disregarding file-name-coding-system. This is a somewhat
1432 unpleasant consequence, but it cannot be avoided. Fortunately,
1433 very few Lisp packages need to do that.
1435 More generally, passing to library functions (e.g., fopen or
1436 opendir) file names already encoded in the ANSI codepage is
1437 explicitly *verboten*, as all those functions, as shadowed and
1438 emulated here, assume they will receive UTF-8 encoded file names.
1440 For the same reasons, no CRT function or Win32 API can be called
1441 directly in Emacs sources, without either converting the file
1442 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1443 some shadowing function defined here.
1445 . Environment variables stored in Vprocess_environment are encoded
1446 in the ANSI codepage, so if getenv/egetenv is used for a variable
1447 whose value is a file name or a list of directories, it needs to
1448 be converted to UTF-8, before it is used as argument to functions
1449 or decoded into a Lisp string.
1451 . File names passed to external libraries, like the image libraries
1452 and GnuTLS, need special handling. These libraries generally
1453 don't support UTF-16 or UTF-8 file names, so they must get file
1454 names encoded in the ANSI codepage. To facilitate using these
1455 libraries with file names that are not encodable in the ANSI
1456 codepage, use the function ansi_encode_filename, which will try
1457 to use the short 8+3 alias of a file name if that file name is
1458 not encodable in the ANSI codepage. See image.c and gnutls.c for
1459 examples of how this should be done.
1461 . Running subprocesses in non-ASCII directories and with non-ASCII
1462 file arguments is limited to the current codepage (even though
1463 Emacs is perfectly capable of finding an executable program file
1464 in a directory whose name cannot be encoded in the current
1465 codepage). This is because the command-line arguments are
1466 encoded _before_ they get to the w32-specific level, and the
1467 encoding is not known in advance (it doesn't have to be the
1468 current ANSI codepage), so w32proc.c functions cannot re-encode
1469 them in UTF-16. This should be fixed, but will also require
1470 changes in cmdproxy. The current limitation is not terribly bad
1471 anyway, since very few, if any, Windows console programs that are
1472 likely to be invoked by Emacs support UTF-16 encoded command
1473 lines.
1475 . For similar reasons, server.el and emacsclient are also limited
1476 to the current ANSI codepage for now.
1478 . Emacs itself can only handle command-line arguments encoded in
1479 the current codepage.
1481 . Turning on w32-unicode-filename on Windows 9X (if it at all
1482 works) requires UNICOWS.DLL, which is thus a requirement even in
1483 non-GUI sessions, something the we previously avoided. */
1487 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1488 codepage defined by file-name-coding-system. */
1490 /* Current codepage for encoding file names. */
1491 static int file_name_codepage;
1493 /* Produce a Windows ANSI codepage suitable for encoding file names.
1494 Return the information about that codepage in CP_INFO. */
1495 static int
1496 codepage_for_filenames (CPINFO *cp_info)
1498 /* A simple cache to avoid calling GetCPInfo every time we need to
1499 encode/decode a file name. The file-name encoding is not
1500 supposed to be changed too frequently, if ever. */
1501 static Lisp_Object last_file_name_encoding;
1502 static CPINFO cp;
1503 Lisp_Object current_encoding;
1505 current_encoding = Vfile_name_coding_system;
1506 if (NILP (current_encoding))
1507 current_encoding = Vdefault_file_name_coding_system;
1509 if (!EQ (last_file_name_encoding, current_encoding))
1511 /* Default to the current ANSI codepage. */
1512 file_name_codepage = w32_ansi_code_page;
1514 if (NILP (current_encoding))
1516 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1517 char *cp = NULL, *end;
1518 int cpnum;
1520 if (strncmp (cpname, "cp", 2) == 0)
1521 cp = cpname + 2;
1522 else if (strncmp (cpname, "windows-", 8) == 0)
1523 cp = cpname + 8;
1525 if (cp)
1527 end = cp;
1528 cpnum = strtol (cp, &end, 10);
1529 if (cpnum && *end == '\0' && end - cp >= 2)
1530 file_name_codepage = cpnum;
1534 if (!file_name_codepage)
1535 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1537 if (!GetCPInfo (file_name_codepage, &cp))
1539 file_name_codepage = CP_ACP;
1540 if (!GetCPInfo (file_name_codepage, &cp))
1541 emacs_abort ();
1544 if (cp_info)
1545 *cp_info = cp;
1547 return file_name_codepage;
1551 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1553 int result = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, fn_in, -1,
1554 fn_out, MAX_PATH);
1556 if (!result)
1558 DWORD err = GetLastError ();
1560 switch (err)
1562 case ERROR_INVALID_FLAGS:
1563 case ERROR_INVALID_PARAMETER:
1564 errno = EINVAL;
1565 break;
1566 case ERROR_INSUFFICIENT_BUFFER:
1567 case ERROR_NO_UNICODE_TRANSLATION:
1568 default:
1569 errno = ENOENT;
1570 break;
1572 return -1;
1574 return 0;
1578 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1580 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1581 fn_out, MAX_UTF8_PATH, NULL, NULL);
1583 if (!result)
1585 DWORD err = GetLastError ();
1587 switch (err)
1589 case ERROR_INVALID_FLAGS:
1590 case ERROR_INVALID_PARAMETER:
1591 errno = EINVAL;
1592 break;
1593 case ERROR_INSUFFICIENT_BUFFER:
1594 case ERROR_NO_UNICODE_TRANSLATION:
1595 default:
1596 errno = ENOENT;
1597 break;
1599 return -1;
1601 return 0;
1605 filename_to_ansi (const char *fn_in, char *fn_out)
1607 wchar_t fn_utf16[MAX_PATH];
1609 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1611 int result;
1612 int codepage = codepage_for_filenames (NULL);
1614 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1615 fn_out, MAX_PATH, NULL, NULL);
1616 if (!result)
1618 DWORD err = GetLastError ();
1620 switch (err)
1622 case ERROR_INVALID_FLAGS:
1623 case ERROR_INVALID_PARAMETER:
1624 errno = EINVAL;
1625 break;
1626 case ERROR_INSUFFICIENT_BUFFER:
1627 case ERROR_NO_UNICODE_TRANSLATION:
1628 default:
1629 errno = ENOENT;
1630 break;
1632 return -1;
1634 return 0;
1636 return -1;
1640 filename_from_ansi (const char *fn_in, char *fn_out)
1642 wchar_t fn_utf16[MAX_PATH];
1643 int codepage = codepage_for_filenames (NULL);
1644 int result = pMultiByteToWideChar (codepage, MB_ERR_INVALID_CHARS, fn_in, -1,
1645 fn_utf16, MAX_PATH);
1647 if (!result)
1649 DWORD err = GetLastError ();
1651 switch (err)
1653 case ERROR_INVALID_FLAGS:
1654 case ERROR_INVALID_PARAMETER:
1655 errno = EINVAL;
1656 break;
1657 case ERROR_INSUFFICIENT_BUFFER:
1658 case ERROR_NO_UNICODE_TRANSLATION:
1659 default:
1660 errno = ENOENT;
1661 break;
1663 return -1;
1665 return filename_from_utf16 (fn_utf16, fn_out);
1670 /* The directory where we started, in UTF-8. */
1671 static char startup_dir[MAX_UTF8_PATH];
1673 /* Get the current working directory. */
1674 char *
1675 getcwd (char *dir, int dirsize)
1677 if (!dirsize)
1679 errno = EINVAL;
1680 return NULL;
1682 if (dirsize <= strlen (startup_dir))
1684 errno = ERANGE;
1685 return NULL;
1687 #if 0
1688 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1689 return dir;
1690 return NULL;
1691 #else
1692 /* Emacs doesn't actually change directory itself, it stays in the
1693 same directory where it was started. */
1694 strcpy (dir, startup_dir);
1695 return dir;
1696 #endif
1699 /* Emulate getloadavg. */
1701 struct load_sample {
1702 time_t sample_time;
1703 ULONGLONG idle;
1704 ULONGLONG kernel;
1705 ULONGLONG user;
1708 /* Number of processors on this machine. */
1709 static unsigned num_of_processors;
1711 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1712 static struct load_sample samples[16*60];
1713 static int first_idx = -1, last_idx = -1;
1714 static int max_idx = ARRAYELTS (samples);
1716 static int
1717 buf_next (int from)
1719 int next_idx = from + 1;
1721 if (next_idx >= max_idx)
1722 next_idx = 0;
1724 return next_idx;
1727 static int
1728 buf_prev (int from)
1730 int prev_idx = from - 1;
1732 if (prev_idx < 0)
1733 prev_idx = max_idx - 1;
1735 return prev_idx;
1738 static void
1739 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1741 SYSTEM_INFO sysinfo;
1742 FILETIME ft_idle, ft_user, ft_kernel;
1744 /* Initialize the number of processors on this machine. */
1745 if (num_of_processors <= 0)
1747 get_native_system_info (&sysinfo);
1748 num_of_processors = sysinfo.dwNumberOfProcessors;
1749 if (num_of_processors <= 0)
1751 GetSystemInfo (&sysinfo);
1752 num_of_processors = sysinfo.dwNumberOfProcessors;
1754 if (num_of_processors <= 0)
1755 num_of_processors = 1;
1758 /* TODO: Take into account threads that are ready to run, by
1759 sampling the "\System\Processor Queue Length" performance
1760 counter. The code below accounts only for threads that are
1761 actually running. */
1763 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1765 ULARGE_INTEGER uidle, ukernel, uuser;
1767 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1768 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1769 memcpy (&uuser, &ft_user, sizeof (ft_user));
1770 *idle = uidle.QuadPart;
1771 *kernel = ukernel.QuadPart;
1772 *user = uuser.QuadPart;
1774 else
1776 *idle = 0;
1777 *kernel = 0;
1778 *user = 0;
1782 /* Produce the load average for a given time interval, using the
1783 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1784 1-minute, 5-minute, or 15-minute average, respectively. */
1785 static double
1786 getavg (int which)
1788 double retval = -1.0;
1789 double tdiff;
1790 int idx;
1791 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1792 time_t now = samples[last_idx].sample_time;
1794 if (first_idx != last_idx)
1796 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1798 tdiff = difftime (now, samples[idx].sample_time);
1799 if (tdiff >= span - 2*DBL_EPSILON*now)
1801 long double sys =
1802 samples[last_idx].kernel + samples[last_idx].user
1803 - (samples[idx].kernel + samples[idx].user);
1804 long double idl = samples[last_idx].idle - samples[idx].idle;
1806 retval = (1.0 - idl / sys) * num_of_processors;
1807 break;
1809 if (idx == first_idx)
1810 break;
1814 return retval;
1818 getloadavg (double loadavg[], int nelem)
1820 int elem;
1821 ULONGLONG idle, kernel, user;
1822 time_t now = time (NULL);
1824 /* If system time jumped back for some reason, delete all samples
1825 whose time is later than the current wall-clock time. This
1826 prevents load average figures from becoming frozen for prolonged
1827 periods of time, when system time is reset backwards. */
1828 if (last_idx >= 0)
1830 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1832 if (last_idx == first_idx)
1834 first_idx = last_idx = -1;
1835 break;
1837 last_idx = buf_prev (last_idx);
1841 /* Store another sample. We ignore samples that are less than 1 sec
1842 apart. */
1843 if (last_idx < 0
1844 || (difftime (now, samples[last_idx].sample_time)
1845 >= 1.0 - 2*DBL_EPSILON*now))
1847 sample_system_load (&idle, &kernel, &user);
1848 last_idx = buf_next (last_idx);
1849 samples[last_idx].sample_time = now;
1850 samples[last_idx].idle = idle;
1851 samples[last_idx].kernel = kernel;
1852 samples[last_idx].user = user;
1853 /* If the buffer has more that 15 min worth of samples, discard
1854 the old ones. */
1855 if (first_idx == -1)
1856 first_idx = last_idx;
1857 while (first_idx != last_idx
1858 && (difftime (now, samples[first_idx].sample_time)
1859 >= 15.0*60 + 2*DBL_EPSILON*now))
1860 first_idx = buf_next (first_idx);
1863 for (elem = 0; elem < nelem; elem++)
1865 double avg = getavg (elem);
1867 if (avg < 0)
1868 break;
1869 loadavg[elem] = avg;
1872 return elem;
1875 /* Emulate getpwuid, getpwnam and others. */
1877 #define PASSWD_FIELD_SIZE 256
1879 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1880 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1881 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1882 static char dflt_passwd_dir[MAX_UTF8_PATH];
1883 static char dflt_passwd_shell[MAX_UTF8_PATH];
1885 static struct passwd dflt_passwd =
1887 dflt_passwd_name,
1888 dflt_passwd_passwd,
1892 dflt_passwd_gecos,
1893 dflt_passwd_dir,
1894 dflt_passwd_shell,
1897 static char dflt_group_name[GNLEN+1];
1899 static struct group dflt_group =
1901 /* When group information is not available, we return this as the
1902 group for all files. */
1903 dflt_group_name,
1907 unsigned
1908 getuid (void)
1910 return dflt_passwd.pw_uid;
1913 unsigned
1914 geteuid (void)
1916 /* I could imagine arguing for checking to see whether the user is
1917 in the Administrators group and returning a UID of 0 for that
1918 case, but I don't know how wise that would be in the long run. */
1919 return getuid ();
1922 unsigned
1923 getgid (void)
1925 return dflt_passwd.pw_gid;
1928 unsigned
1929 getegid (void)
1931 return getgid ();
1934 struct passwd *
1935 getpwuid (unsigned uid)
1937 if (uid == dflt_passwd.pw_uid)
1938 return &dflt_passwd;
1939 return NULL;
1942 struct group *
1943 getgrgid (gid_t gid)
1945 return &dflt_group;
1948 struct passwd *
1949 getpwnam (char *name)
1951 struct passwd *pw;
1953 pw = getpwuid (getuid ());
1954 if (!pw)
1955 return pw;
1957 if (xstrcasecmp (name, pw->pw_name))
1958 return NULL;
1960 return pw;
1963 static void
1964 init_user_info (void)
1966 /* Find the user's real name by opening the process token and
1967 looking up the name associated with the user-sid in that token.
1969 Use the relative portion of the identifier authority value from
1970 the user-sid as the user id value (same for group id using the
1971 primary group sid from the process token). */
1973 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1974 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1975 DWORD glength = sizeof (gname);
1976 HANDLE token = NULL;
1977 SID_NAME_USE user_type;
1978 unsigned char *buf = NULL;
1979 DWORD blen = 0;
1980 TOKEN_USER user_token;
1981 TOKEN_PRIMARY_GROUP group_token;
1982 BOOL result;
1984 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1985 if (result)
1987 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1988 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1990 buf = xmalloc (blen);
1991 result = get_token_information (token, TokenUser,
1992 (LPVOID)buf, blen, &needed);
1993 if (result)
1995 memcpy (&user_token, buf, sizeof (user_token));
1996 result = lookup_account_sid (NULL, user_token.User.Sid,
1997 uname, &ulength,
1998 domain, &dlength, &user_type);
2001 else
2002 result = FALSE;
2004 if (result)
2006 strcpy (dflt_passwd.pw_name, uname);
2007 /* Determine a reasonable uid value. */
2008 if (xstrcasecmp ("administrator", uname) == 0)
2010 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2011 dflt_passwd.pw_gid = 513; /* well-known None gid */
2013 else
2015 /* Use the last sub-authority value of the RID, the relative
2016 portion of the SID, as user/group ID. */
2017 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2019 /* Get group id and name. */
2020 result = get_token_information (token, TokenPrimaryGroup,
2021 (LPVOID)buf, blen, &needed);
2022 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2024 buf = xrealloc (buf, blen = needed);
2025 result = get_token_information (token, TokenPrimaryGroup,
2026 (LPVOID)buf, blen, &needed);
2028 if (result)
2030 memcpy (&group_token, buf, sizeof (group_token));
2031 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2032 dlength = sizeof (domain);
2033 /* If we can get at the real Primary Group name, use that.
2034 Otherwise, the default group name was already set to
2035 "None" in globals_of_w32. */
2036 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2037 gname, &glength, NULL, &dlength,
2038 &user_type))
2039 strcpy (dflt_group_name, gname);
2041 else
2042 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2045 /* If security calls are not supported (presumably because we
2046 are running under Windows 9X), fallback to this: */
2047 else if (GetUserName (uname, &ulength))
2049 strcpy (dflt_passwd.pw_name, uname);
2050 if (xstrcasecmp ("administrator", uname) == 0)
2051 dflt_passwd.pw_uid = 0;
2052 else
2053 dflt_passwd.pw_uid = 123;
2054 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2056 else
2058 strcpy (dflt_passwd.pw_name, "unknown");
2059 dflt_passwd.pw_uid = 123;
2060 dflt_passwd.pw_gid = 123;
2062 dflt_group.gr_gid = dflt_passwd.pw_gid;
2064 /* Set dir and shell from environment variables. */
2065 if (w32_unicode_filenames)
2067 wchar_t *home = _wgetenv (L"HOME");
2068 wchar_t *shell = _wgetenv (L"SHELL");
2070 /* Ensure HOME and SHELL are defined. */
2071 if (home == NULL)
2072 emacs_abort ();
2073 if (shell == NULL)
2074 emacs_abort ();
2075 filename_from_utf16 (home, dflt_passwd.pw_dir);
2076 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2078 else
2080 char *home = getenv ("HOME");
2081 char *shell = getenv ("SHELL");
2083 if (home == NULL)
2084 emacs_abort ();
2085 if (shell == NULL)
2086 emacs_abort ();
2087 filename_from_ansi (home, dflt_passwd.pw_dir);
2088 filename_from_ansi (shell, dflt_passwd.pw_shell);
2091 xfree (buf);
2092 if (token)
2093 CloseHandle (token);
2097 random (void)
2099 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2100 return ((rand () << 15) | rand ());
2103 void
2104 srandom (int seed)
2106 srand (seed);
2109 /* Return the maximum length in bytes of a multibyte character
2110 sequence encoded in the current ANSI codepage. This is required to
2111 correctly walk the encoded file names one character at a time. */
2112 static int
2113 max_filename_mbslen (void)
2115 CPINFO cp_info;
2117 codepage_for_filenames (&cp_info);
2118 return cp_info.MaxCharSize;
2121 /* Normalize filename by converting in-place all of its path
2122 separators to the separator specified by PATH_SEP. */
2124 static void
2125 normalize_filename (register char *fp, char path_sep)
2127 char *p2;
2129 /* Always lower-case drive letters a-z, even if the filesystem
2130 preserves case in filenames.
2131 This is so filenames can be compared by string comparison
2132 functions that are case-sensitive. Even case-preserving filesystems
2133 do not distinguish case in drive letters. */
2134 p2 = fp + 1;
2136 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2138 *fp += 'a' - 'A';
2139 fp += 2;
2142 while (*fp)
2144 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2145 *fp = path_sep;
2146 fp++;
2150 /* Destructively turn backslashes into slashes. */
2151 void
2152 dostounix_filename (register char *p)
2154 normalize_filename (p, '/');
2157 /* Destructively turn slashes into backslashes. */
2158 void
2159 unixtodos_filename (register char *p)
2161 normalize_filename (p, '\\');
2164 /* Remove all CR's that are followed by a LF.
2165 (From msdos.c...probably should figure out a way to share it,
2166 although this code isn't going to ever change.) */
2167 static int
2168 crlf_to_lf (register int n, register unsigned char *buf)
2170 unsigned char *np = buf;
2171 unsigned char *startp = buf;
2172 unsigned char *endp = buf + n;
2174 if (n == 0)
2175 return n;
2176 while (buf < endp - 1)
2178 if (*buf == 0x0d)
2180 if (*(++buf) != 0x0a)
2181 *np++ = 0x0d;
2183 else
2184 *np++ = *buf++;
2186 if (buf < endp)
2187 *np++ = *buf++;
2188 return np - startp;
2191 /* Parse the root part of file name, if present. Return length and
2192 optionally store pointer to char after root. */
2193 static int
2194 parse_root (const char * name, const char ** pPath)
2196 const char * start = name;
2198 if (name == NULL)
2199 return 0;
2201 /* find the root name of the volume if given */
2202 if (isalpha (name[0]) && name[1] == ':')
2204 /* skip past drive specifier */
2205 name += 2;
2206 if (IS_DIRECTORY_SEP (name[0]))
2207 name++;
2209 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2211 int slashes = 2;
2213 name += 2;
2216 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2217 break;
2218 name++;
2220 while ( *name );
2221 if (IS_DIRECTORY_SEP (name[0]))
2222 name++;
2225 if (pPath)
2226 *pPath = name;
2228 return name - start;
2231 /* Get long base name for name; name is assumed to be absolute. */
2232 static int
2233 get_long_basename (char * name, char * buf, int size)
2235 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2236 char fname_utf8[MAX_UTF8_PATH];
2237 int len = 0;
2238 int cstatus = -1;
2240 /* Must be valid filename, no wild cards or other invalid characters. */
2241 if (strpbrk (name, "*?|<>\""))
2242 return 0;
2244 if (w32_unicode_filenames)
2246 wchar_t fname_utf16[MAX_PATH];
2247 WIN32_FIND_DATAW find_data_wide;
2249 filename_to_utf16 (name, fname_utf16);
2250 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2251 if (dir_handle != INVALID_HANDLE_VALUE)
2252 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2254 else
2256 char fname_ansi[MAX_PATH];
2257 WIN32_FIND_DATAA find_data_ansi;
2259 filename_to_ansi (name, fname_ansi);
2260 /* If the ANSI name includes ? characters, it is not encodable
2261 in the ANSI codepage. In that case, we deliver the question
2262 marks to the caller; calling FindFirstFileA in this case
2263 could return some unrelated file name in the same
2264 directory. */
2265 if (_mbspbrk (fname_ansi, "?"))
2267 /* Find the basename of fname_ansi. */
2268 char *p = strrchr (fname_ansi, '\\');
2270 if (!p)
2271 p = fname_ansi;
2272 else
2273 p++;
2274 cstatus = filename_from_ansi (p, fname_utf8);
2276 else
2278 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2279 if (dir_handle != INVALID_HANDLE_VALUE)
2280 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2284 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2285 memcpy (buf, fname_utf8, len + 1);
2286 else
2287 len = 0;
2289 if (dir_handle != INVALID_HANDLE_VALUE)
2290 FindClose (dir_handle);
2292 return len;
2295 /* Get long name for file, if possible (assumed to be absolute). */
2296 BOOL
2297 w32_get_long_filename (const char * name, char * buf, int size)
2299 char * o = buf;
2300 char * p;
2301 const char * q;
2302 char full[ MAX_UTF8_PATH ];
2303 int len;
2305 len = strlen (name);
2306 if (len >= MAX_UTF8_PATH)
2307 return FALSE;
2309 /* Use local copy for destructive modification. */
2310 memcpy (full, name, len+1);
2311 unixtodos_filename (full);
2313 /* Copy root part verbatim. */
2314 len = parse_root (full, (const char **)&p);
2315 memcpy (o, full, len);
2316 o += len;
2317 *o = '\0';
2318 size -= len;
2320 while (p != NULL && *p)
2322 q = p;
2323 p = strchr (q, '\\');
2324 if (p) *p = '\0';
2325 len = get_long_basename (full, o, size);
2326 if (len > 0)
2328 o += len;
2329 size -= len;
2330 if (p != NULL)
2332 *p++ = '\\';
2333 if (size < 2)
2334 return FALSE;
2335 *o++ = '\\';
2336 size--;
2337 *o = '\0';
2340 else
2341 return FALSE;
2344 return TRUE;
2347 unsigned int
2348 w32_get_short_filename (const char * name, char * buf, int size)
2350 if (w32_unicode_filenames)
2352 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2353 unsigned int retval;
2355 filename_to_utf16 (name, name_utf16);
2356 retval = GetShortPathNameW (name_utf16, short_name, size);
2357 if (retval && retval < size)
2358 filename_from_utf16 (short_name, buf);
2359 return retval;
2361 else
2363 char name_ansi[MAX_PATH];
2365 filename_to_ansi (name, name_ansi);
2366 return GetShortPathNameA (name_ansi, buf, size);
2370 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2371 MS-Windows ANSI codepage. If FILENAME includes characters not
2372 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2373 if it exists. This is needed because the w32 build wants to
2374 support file names outside of the system locale, but image
2375 libraries typically don't support wide (a.k.a. "Unicode") APIs
2376 required for that. */
2378 Lisp_Object
2379 ansi_encode_filename (Lisp_Object filename)
2381 Lisp_Object encoded_filename;
2382 char fname[MAX_PATH];
2384 filename_to_ansi (SSDATA (filename), fname);
2385 if (_mbspbrk (fname, "?"))
2387 char shortname[MAX_PATH];
2389 if (w32_get_short_filename (SDATA (filename), shortname, MAX_PATH))
2391 dostounix_filename (shortname);
2392 encoded_filename = build_string (shortname);
2394 else
2395 encoded_filename = build_unibyte_string (fname);
2397 else
2398 encoded_filename = build_unibyte_string (fname);
2399 return encoded_filename;
2402 static int
2403 is_unc_volume (const char *filename)
2405 const char *ptr = filename;
2407 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2408 return 0;
2410 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2411 return 0;
2413 return 1;
2416 /* Emulate the Posix unsetenv. */
2418 unsetenv (const char *name)
2420 char *var;
2421 size_t name_len;
2423 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2425 errno = EINVAL;
2426 return -1;
2428 name_len = strlen (name);
2429 /* MS docs says an environment variable cannot be longer than 32K. */
2430 if (name_len > 32767)
2432 errno = ENOMEM;
2433 return 0;
2435 /* It is safe to use 'alloca' with 32K size, since the stack is at
2436 least 2MB, and we set it to 8MB in the link command line. */
2437 var = alloca (name_len + 2);
2438 strncpy (var, name, name_len);
2439 var[name_len++] = '=';
2440 var[name_len] = '\0';
2441 return _putenv (var);
2444 /* MS _putenv doesn't support removing a variable when the argument
2445 does not include the '=' character, so we fix that here. */
2447 sys_putenv (char *str)
2449 const char *const name_end = strchr (str, '=');
2451 if (name_end == NULL)
2453 /* Remove the variable from the environment. */
2454 return unsetenv (str);
2457 return _putenv (str);
2460 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2462 LPBYTE
2463 w32_get_resource (char *key, LPDWORD lpdwtype)
2465 LPBYTE lpvalue;
2466 HKEY hrootkey = NULL;
2467 DWORD cbData;
2469 /* Check both the current user and the local machine to see if
2470 we have any resources. */
2472 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2474 lpvalue = NULL;
2476 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2477 && (lpvalue = xmalloc (cbData)) != NULL
2478 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2480 RegCloseKey (hrootkey);
2481 return (lpvalue);
2484 xfree (lpvalue);
2486 RegCloseKey (hrootkey);
2489 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2491 lpvalue = NULL;
2493 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2494 && (lpvalue = xmalloc (cbData)) != NULL
2495 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2497 RegCloseKey (hrootkey);
2498 return (lpvalue);
2501 xfree (lpvalue);
2503 RegCloseKey (hrootkey);
2506 return (NULL);
2509 /* The argv[] array holds ANSI-encoded strings, and so this function
2510 works with ANS_encoded strings. */
2511 void
2512 init_environment (char ** argv)
2514 static const char * const tempdirs[] = {
2515 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2518 int i;
2520 const int imax = ARRAYELTS (tempdirs);
2522 /* Implementation note: This function explicitly works with ANSI
2523 file names, not with UTF-8 encoded file names. This is because
2524 this function pushes variables into the Emacs's environment, and
2525 the environment variables are always assumed to be in the
2526 locale-specific encoding. Do NOT call any functions that accept
2527 UTF-8 file names from this function! */
2529 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2530 temporary files and assume "/tmp" if $TMPDIR is unset, which
2531 will break on DOS/Windows. Refuse to work if we cannot find
2532 a directory, not even "c:/", usable for that purpose. */
2533 for (i = 0; i < imax ; i++)
2535 const char *tmp = tempdirs[i];
2537 if (*tmp == '$')
2538 tmp = getenv (tmp + 1);
2539 /* Note that `access' can lie to us if the directory resides on a
2540 read-only filesystem, like CD-ROM or a write-protected floppy.
2541 The only way to be really sure is to actually create a file and
2542 see if it succeeds. But I think that's too much to ask. */
2544 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2545 if (tmp && sys_access (tmp, D_OK) == 0)
2547 char * var = alloca (strlen (tmp) + 8);
2548 sprintf (var, "TMPDIR=%s", tmp);
2549 _putenv (strdup (var));
2550 break;
2553 if (i >= imax)
2554 cmd_error_internal
2555 (Fcons (Qerror,
2556 Fcons (build_string ("no usable temporary directories found!!"),
2557 Qnil)),
2558 "While setting TMPDIR: ");
2560 /* Check for environment variables and use registry settings if they
2561 don't exist. Fallback on default values where applicable. */
2563 int i;
2564 LPBYTE lpval;
2565 DWORD dwType;
2566 char locale_name[32];
2567 char default_home[MAX_PATH];
2568 int appdata = 0;
2570 static const struct env_entry
2572 char * name;
2573 char * def_value;
2574 } dflt_envvars[] =
2576 /* If the default value is NULL, we will use the value from the
2577 outside environment or the Registry, but will not push the
2578 variable into the Emacs environment if it is defined neither
2579 in the Registry nor in the outside environment. */
2580 {"HOME", "C:/"},
2581 {"PRELOAD_WINSOCK", NULL},
2582 {"emacs_dir", "C:/emacs"},
2583 {"EMACSLOADPATH", NULL},
2584 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2585 {"EMACSDATA", NULL},
2586 {"EMACSPATH", NULL},
2587 {"INFOPATH", NULL},
2588 {"EMACSDOC", NULL},
2589 {"TERM", "cmd"},
2590 {"LANG", NULL},
2593 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2595 /* We need to copy dflt_envvars[] and work on the copy because we
2596 don't want the dumped Emacs to inherit the values of
2597 environment variables we saw during dumping (which could be on
2598 a different system). The defaults above must be left intact. */
2599 struct env_entry env_vars[N_ENV_VARS];
2601 for (i = 0; i < N_ENV_VARS; i++)
2602 env_vars[i] = dflt_envvars[i];
2604 /* For backwards compatibility, check if a .emacs file exists in C:/
2605 If not, then we can try to default to the appdata directory under the
2606 user's profile, which is more likely to be writable. */
2607 if (sys_access ("C:/.emacs", F_OK) != 0)
2609 HRESULT profile_result;
2610 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2611 of Windows 95 and NT4 that have not been updated to include
2612 MSIE 5. */
2613 ShGetFolderPath_fn get_folder_path;
2614 get_folder_path = (ShGetFolderPath_fn)
2615 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2617 if (get_folder_path != NULL)
2619 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2620 0, default_home);
2622 /* If we can't get the appdata dir, revert to old behavior. */
2623 if (profile_result == S_OK)
2625 env_vars[0].def_value = default_home;
2626 appdata = 1;
2631 /* Get default locale info and use it for LANG. */
2632 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2633 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2634 locale_name, sizeof (locale_name)))
2636 for (i = 0; i < N_ENV_VARS; i++)
2638 if (strcmp (env_vars[i].name, "LANG") == 0)
2640 env_vars[i].def_value = locale_name;
2641 break;
2646 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2648 /* Treat emacs_dir specially: set it unconditionally based on our
2649 location. */
2651 char *p;
2652 char modname[MAX_PATH];
2654 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2655 emacs_abort ();
2656 if ((p = _mbsrchr (modname, '\\')) == NULL)
2657 emacs_abort ();
2658 *p = 0;
2660 if ((p = _mbsrchr (modname, '\\'))
2661 /* From bin means installed Emacs, from src means uninstalled. */
2662 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2664 char buf[SET_ENV_BUF_SIZE];
2665 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2667 *p = 0;
2668 for (p = modname; *p; p = CharNext (p))
2669 if (*p == '\\') *p = '/';
2671 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2672 _putenv (strdup (buf));
2673 /* If we are running from the Posix-like build tree, define
2674 SHELL to point to our own cmdproxy. The loop below will
2675 then disregard PATH_EXEC and the default value. */
2676 if (within_build_tree)
2678 _snprintf (buf, sizeof (buf) - 1,
2679 "SHELL=%s/nt/cmdproxy.exe", modname);
2680 _putenv (strdup (buf));
2685 for (i = 0; i < N_ENV_VARS; i++)
2687 if (!getenv (env_vars[i].name))
2689 int dont_free = 0;
2690 char bufc[SET_ENV_BUF_SIZE];
2692 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2693 /* Also ignore empty environment variables. */
2694 || *lpval == 0)
2696 xfree (lpval);
2697 dont_free = 1;
2698 if (strcmp (env_vars[i].name, "SHELL") == 0)
2700 /* Look for cmdproxy.exe in every directory in
2701 PATH_EXEC. FIXME: This does not find cmdproxy
2702 in nt/ when we run uninstalled. */
2703 char fname[MAX_PATH];
2704 const char *pstart = PATH_EXEC, *pend;
2706 do {
2707 pend = _mbschr (pstart, ';');
2708 if (!pend)
2709 pend = pstart + strlen (pstart);
2710 /* Be defensive against series of ;;; characters. */
2711 if (pend > pstart)
2713 strncpy (fname, pstart, pend - pstart);
2714 fname[pend - pstart] = '/';
2715 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2716 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2717 sizeof (bufc));
2718 if (sys_access (bufc, F_OK) == 0)
2720 lpval = bufc;
2721 dwType = REG_SZ;
2722 break;
2725 if (*pend)
2726 pstart = pend + 1;
2727 else
2728 pstart = pend;
2729 if (!*pstart)
2731 /* If not found in any directory, use the
2732 default as the last resort. */
2733 lpval = env_vars[i].def_value;
2734 dwType = REG_EXPAND_SZ;
2736 } while (*pstart);
2738 else
2740 lpval = env_vars[i].def_value;
2741 dwType = REG_EXPAND_SZ;
2743 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2744 Vdelayed_warnings_list
2745 = Fcons (listn (CONSTYPE_HEAP, 2,
2746 intern ("initialization"),
2747 build_string ("Setting HOME to C:\\ by default is deprecated")),
2748 Vdelayed_warnings_list);
2751 if (lpval)
2753 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2755 if (dwType == REG_EXPAND_SZ)
2756 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2757 else if (dwType == REG_SZ)
2758 strcpy (buf1, lpval);
2759 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2761 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2762 buf1);
2763 _putenv (strdup (buf2));
2766 if (!dont_free)
2767 xfree (lpval);
2773 /* Rebuild system configuration to reflect invoking system. */
2774 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2776 /* Another special case: on NT, the PATH variable is actually named
2777 "Path" although cmd.exe (perhaps NT itself) arranges for
2778 environment variable lookup and setting to be case insensitive.
2779 However, Emacs assumes a fully case sensitive environment, so we
2780 need to change "Path" to "PATH" to match the expectations of
2781 various elisp packages. We do this by the sneaky method of
2782 modifying the string in the C runtime environ entry.
2784 The same applies to COMSPEC. */
2786 char ** envp;
2788 for (envp = environ; *envp; envp++)
2789 if (_strnicmp (*envp, "PATH=", 5) == 0)
2790 memcpy (*envp, "PATH=", 5);
2791 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2792 memcpy (*envp, "COMSPEC=", 8);
2795 /* Remember the initial working directory for getcwd. */
2796 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2797 Does it matter anywhere in Emacs? */
2798 if (w32_unicode_filenames)
2800 wchar_t wstartup_dir[MAX_PATH];
2802 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2803 emacs_abort ();
2804 filename_from_utf16 (wstartup_dir, startup_dir);
2806 else
2808 char astartup_dir[MAX_PATH];
2810 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2811 emacs_abort ();
2812 filename_from_ansi (astartup_dir, startup_dir);
2816 static char modname[MAX_PATH];
2818 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2819 emacs_abort ();
2820 argv[0] = modname;
2823 /* Determine if there is a middle mouse button, to allow parse_button
2824 to decide whether right mouse events should be mouse-2 or
2825 mouse-3. */
2826 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2828 init_user_info ();
2831 /* Called from expand-file-name when default-directory is not a string. */
2833 char *
2834 emacs_root_dir (void)
2836 static char root_dir[MAX_UTF8_PATH];
2837 const char *p;
2839 p = getenv ("emacs_dir");
2840 if (p == NULL)
2841 emacs_abort ();
2842 filename_from_ansi (p, root_dir);
2843 root_dir[parse_root (root_dir, NULL)] = '\0';
2844 dostounix_filename (root_dir);
2845 return root_dir;
2848 #include <sys/timeb.h>
2850 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2852 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2854 struct _timeb tb;
2855 _ftime (&tb);
2857 tv->tv_sec = tb.time;
2858 tv->tv_usec = tb.millitm * 1000L;
2859 /* Implementation note: _ftime sometimes doesn't update the dstflag
2860 according to the new timezone when the system timezone is
2861 changed. We could fix that by using GetSystemTime and
2862 GetTimeZoneInformation, but that doesn't seem necessary, since
2863 Emacs always calls gettimeofday with the 2nd argument NULL (see
2864 current_emacs_time). */
2865 if (tz)
2867 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2868 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2870 return 0;
2873 /* Emulate fdutimens. */
2875 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2876 TIMESPEC[0] and TIMESPEC[1], respectively.
2877 FD must be either negative -- in which case it is ignored --
2878 or a file descriptor that is open on FILE.
2879 If FD is nonnegative, then FILE can be NULL, which means
2880 use just futimes instead of utimes.
2881 If TIMESPEC is null, FAIL.
2882 Return 0 on success, -1 (setting errno) on failure. */
2885 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2887 if (!timespec)
2889 errno = ENOSYS;
2890 return -1;
2892 if (fd < 0 && !file)
2894 errno = EBADF;
2895 return -1;
2897 /* _futime's prototype defines 2nd arg as having the type 'struct
2898 _utimbuf', while utime needs to accept 'struct utimbuf' for
2899 compatibility with Posix. So we need to use 2 different (but
2900 equivalent) types to avoid compiler warnings, sigh. */
2901 if (fd >= 0)
2903 struct _utimbuf _ut;
2905 _ut.actime = timespec[0].tv_sec;
2906 _ut.modtime = timespec[1].tv_sec;
2907 return _futime (fd, &_ut);
2909 else
2911 struct utimbuf ut;
2913 ut.actime = timespec[0].tv_sec;
2914 ut.modtime = timespec[1].tv_sec;
2915 /* Call 'utime', which is implemented below, not the MS library
2916 function, which fails on directories. */
2917 return utime (file, &ut);
2922 /* ------------------------------------------------------------------------- */
2923 /* IO support and wrapper functions for the Windows API. */
2924 /* ------------------------------------------------------------------------- */
2926 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2927 on network directories, so we handle that case here.
2928 (Ulrich Leodolter, 1/11/95). */
2929 char *
2930 sys_ctime (const time_t *t)
2932 char *str = (char *) ctime (t);
2933 return (str ? str : "Sun Jan 01 00:00:00 1970");
2936 /* Emulate sleep...we could have done this with a define, but that
2937 would necessitate including windows.h in the files that used it.
2938 This is much easier. */
2939 void
2940 sys_sleep (int seconds)
2942 Sleep (seconds * 1000);
2945 /* Internal MSVC functions for low-level descriptor munging */
2946 extern int __cdecl _set_osfhnd (int fd, long h);
2947 extern int __cdecl _free_osfhnd (int fd);
2949 /* parallel array of private info on file handles */
2950 filedesc fd_info [ MAXDESC ];
2952 typedef struct volume_info_data {
2953 struct volume_info_data * next;
2955 /* time when info was obtained */
2956 DWORD timestamp;
2958 /* actual volume info */
2959 char * root_dir;
2960 DWORD serialnum;
2961 DWORD maxcomp;
2962 DWORD flags;
2963 char * name;
2964 char * type;
2965 } volume_info_data;
2967 /* Global referenced by various functions. */
2968 static volume_info_data volume_info;
2970 /* Vector to indicate which drives are local and fixed (for which cached
2971 data never expires). */
2972 static BOOL fixed_drives[26];
2974 /* Consider cached volume information to be stale if older than 10s,
2975 at least for non-local drives. Info for fixed drives is never stale. */
2976 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2977 #define VOLINFO_STILL_VALID( root_dir, info ) \
2978 ( ( isalpha (root_dir[0]) && \
2979 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2980 || GetTickCount () - info->timestamp < 10000 )
2982 /* Cache support functions. */
2984 /* Simple linked list with linear search is sufficient. */
2985 static volume_info_data *volume_cache = NULL;
2987 static volume_info_data *
2988 lookup_volume_info (char * root_dir)
2990 volume_info_data * info;
2992 for (info = volume_cache; info; info = info->next)
2993 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2994 break;
2995 return info;
2998 static void
2999 add_volume_info (char * root_dir, volume_info_data * info)
3001 info->root_dir = xstrdup (root_dir);
3002 unixtodos_filename (info->root_dir);
3003 info->next = volume_cache;
3004 volume_cache = info;
3008 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3009 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3010 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3011 static volume_info_data *
3012 GetCachedVolumeInformation (char * root_dir)
3014 volume_info_data * info;
3015 char default_root[ MAX_UTF8_PATH ];
3016 char name[MAX_PATH+1];
3017 char type[MAX_PATH+1];
3019 /* NULL for root_dir means use root from current directory. */
3020 if (root_dir == NULL)
3022 if (w32_unicode_filenames)
3024 wchar_t curdirw[MAX_PATH];
3026 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3027 return NULL;
3028 filename_from_utf16 (curdirw, default_root);
3030 else
3032 char curdira[MAX_PATH];
3034 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3035 return NULL;
3036 filename_from_ansi (curdira, default_root);
3038 parse_root (default_root, (const char **)&root_dir);
3039 *root_dir = 0;
3040 root_dir = default_root;
3043 /* Local fixed drives can be cached permanently. Removable drives
3044 cannot be cached permanently, since the volume name and serial
3045 number (if nothing else) can change. Remote drives should be
3046 treated as if they are removable, since there is no sure way to
3047 tell whether they are or not. Also, the UNC association of drive
3048 letters mapped to remote volumes can be changed at any time (even
3049 by other processes) without notice.
3051 As a compromise, so we can benefit from caching info for remote
3052 volumes, we use a simple expiry mechanism to invalidate cache
3053 entries that are more than ten seconds old. */
3055 #if 0
3056 /* No point doing this, because WNetGetConnection is even slower than
3057 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3058 GetDriveType is about the only call of this type which does not
3059 involve network access, and so is extremely quick). */
3061 /* Map drive letter to UNC if remote. */
3062 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3064 char remote_name[ 256 ];
3065 char drive[3] = { root_dir[0], ':' };
3067 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3068 == NO_ERROR)
3069 /* do something */ ;
3071 #endif
3073 info = lookup_volume_info (root_dir);
3075 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3077 DWORD serialnum;
3078 DWORD maxcomp;
3079 DWORD flags;
3081 /* Info is not cached, or is stale. */
3082 if (w32_unicode_filenames)
3084 wchar_t root_w[MAX_PATH];
3085 wchar_t name_w[MAX_PATH+1];
3086 wchar_t type_w[MAX_PATH+1];
3088 filename_to_utf16 (root_dir, root_w);
3089 if (!GetVolumeInformationW (root_w,
3090 name_w, sizeof (name_w),
3091 &serialnum,
3092 &maxcomp,
3093 &flags,
3094 type_w, sizeof (type_w)))
3095 return NULL;
3096 /* Hmm... not really 100% correct, as these 2 are not file
3097 names... */
3098 filename_from_utf16 (name_w, name);
3099 filename_from_utf16 (type_w, type);
3101 else
3103 char root_a[MAX_PATH];
3104 char name_a[MAX_PATH+1];
3105 char type_a[MAX_PATH+1];
3107 filename_to_ansi (root_dir, root_a);
3108 if (!GetVolumeInformationA (root_a,
3109 name_a, sizeof (name_a),
3110 &serialnum,
3111 &maxcomp,
3112 &flags,
3113 type_a, sizeof (type_a)))
3114 return NULL;
3115 filename_from_ansi (name_a, name);
3116 filename_from_ansi (type_a, type);
3119 /* Cache the volume information for future use, overwriting existing
3120 entry if present. */
3121 if (info == NULL)
3123 info = xmalloc (sizeof (volume_info_data));
3124 add_volume_info (root_dir, info);
3126 else
3128 xfree (info->name);
3129 xfree (info->type);
3132 info->name = xstrdup (name);
3133 unixtodos_filename (info->name);
3134 info->serialnum = serialnum;
3135 info->maxcomp = maxcomp;
3136 info->flags = flags;
3137 info->type = xstrdup (type);
3138 info->timestamp = GetTickCount ();
3141 return info;
3144 /* Get information on the volume where NAME is held; set path pointer to
3145 start of pathname in NAME (past UNC header\volume header if present),
3146 if pPath is non-NULL.
3148 Note: if NAME includes symlinks, the information is for the volume
3149 of the symlink, not of its target. That's because, even though
3150 GetVolumeInformation returns information about the symlink target
3151 of its argument, we only pass the root directory to
3152 GetVolumeInformation, not the full NAME. */
3153 static int
3154 get_volume_info (const char * name, const char ** pPath)
3156 char temp[MAX_UTF8_PATH];
3157 char *rootname = NULL; /* default to current volume */
3158 volume_info_data * info;
3159 int root_len = parse_root (name, pPath);
3161 if (name == NULL)
3162 return FALSE;
3164 /* Copy the root name of the volume, if given. */
3165 if (root_len)
3167 strncpy (temp, name, root_len);
3168 temp[root_len] = '\0';
3169 unixtodos_filename (temp);
3170 rootname = temp;
3173 info = GetCachedVolumeInformation (rootname);
3174 if (info != NULL)
3176 /* Set global referenced by other functions. */
3177 volume_info = *info;
3178 return TRUE;
3180 return FALSE;
3183 /* Determine if volume is FAT format (ie. only supports short 8.3
3184 names); also set path pointer to start of pathname in name, if
3185 pPath is non-NULL. */
3186 static int
3187 is_fat_volume (const char * name, const char ** pPath)
3189 if (get_volume_info (name, pPath))
3190 return (volume_info.maxcomp == 12);
3191 return FALSE;
3194 /* Convert all slashes in a filename to backslashes, and map filename
3195 to a valid 8.3 name if necessary. The result is a pointer to a
3196 static buffer, so CAVEAT EMPTOR! */
3197 const char *
3198 map_w32_filename (const char * name, const char ** pPath)
3200 static char shortname[MAX_UTF8_PATH];
3201 char * str = shortname;
3202 char c;
3203 char * path;
3204 const char * save_name = name;
3206 if (strlen (name) >= sizeof (shortname))
3208 /* Return a filename which will cause callers to fail. */
3209 strcpy (shortname, "?");
3210 return shortname;
3213 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3215 register int left = 8; /* maximum number of chars in part */
3216 register int extn = 0; /* extension added? */
3217 register int dots = 2; /* maximum number of dots allowed */
3219 while (name < path)
3220 *str++ = *name++; /* skip past UNC header */
3222 while ((c = *name++))
3224 switch ( c )
3226 case ':':
3227 case '\\':
3228 case '/':
3229 *str++ = (c == ':' ? ':' : '\\');
3230 extn = 0; /* reset extension flags */
3231 dots = 2; /* max 2 dots */
3232 left = 8; /* max length 8 for main part */
3233 break;
3234 case '.':
3235 if ( dots )
3237 /* Convert path components of the form .xxx to _xxx,
3238 but leave . and .. as they are. This allows .emacs
3239 to be read as _emacs, for example. */
3241 if (! *name ||
3242 *name == '.' ||
3243 IS_DIRECTORY_SEP (*name))
3245 *str++ = '.';
3246 dots--;
3248 else
3250 *str++ = '_';
3251 left--;
3252 dots = 0;
3255 else if ( !extn )
3257 *str++ = '.';
3258 extn = 1; /* we've got an extension */
3259 left = 3; /* 3 chars in extension */
3261 else
3263 /* any embedded dots after the first are converted to _ */
3264 *str++ = '_';
3266 break;
3267 case '~':
3268 case '#': /* don't lose these, they're important */
3269 if ( ! left )
3270 str[-1] = c; /* replace last character of part */
3271 /* FALLTHRU */
3272 default:
3273 if ( left && 'A' <= c && c <= 'Z' )
3275 *str++ = tolower (c); /* map to lower case (looks nicer) */
3276 left--;
3277 dots = 0; /* started a path component */
3279 break;
3282 *str = '\0';
3284 else
3286 strcpy (shortname, name);
3287 unixtodos_filename (shortname);
3290 if (pPath)
3291 *pPath = shortname + (path - save_name);
3293 return shortname;
3296 static int
3297 is_exec (const char * name)
3299 char * p = strrchr (name, '.');
3300 return
3301 (p != NULL
3302 && (xstrcasecmp (p, ".exe") == 0 ||
3303 xstrcasecmp (p, ".com") == 0 ||
3304 xstrcasecmp (p, ".bat") == 0 ||
3305 xstrcasecmp (p, ".cmd") == 0));
3308 /* Emulate the Unix directory procedures opendir, closedir, and
3309 readdir. We rename them to sys_* names because some versions of
3310 MinGW startup code call opendir and readdir to glob wildcards, and
3311 the code that calls them doesn't grok UTF-8 encoded file names we
3312 produce in dirent->d_name[]. */
3314 struct dirent dir_static; /* simulated directory contents */
3315 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3316 static int dir_is_fat;
3317 static char dir_pathname[MAX_UTF8_PATH];
3318 static WIN32_FIND_DATAW dir_find_data_w;
3319 static WIN32_FIND_DATAA dir_find_data_a;
3320 #define DIR_FIND_DATA_W 1
3321 #define DIR_FIND_DATA_A 2
3322 static int last_dir_find_data = -1;
3324 /* Support shares on a network resource as subdirectories of a read-only
3325 root directory. */
3326 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3327 static HANDLE open_unc_volume (const char *);
3328 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3329 static void close_unc_volume (HANDLE);
3331 DIR *
3332 sys_opendir (const char *filename)
3334 DIR *dirp;
3336 /* Opening is done by FindFirstFile. However, a read is inherent to
3337 this operation, so we defer the open until read time. */
3339 if (dir_find_handle != INVALID_HANDLE_VALUE)
3340 return NULL;
3341 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3342 return NULL;
3344 /* Note: We don't support traversal of UNC volumes via symlinks.
3345 Doing so would mean punishing 99.99% of use cases by resolving
3346 all the possible symlinks in FILENAME, recursively. */
3347 if (is_unc_volume (filename))
3349 wnet_enum_handle = open_unc_volume (filename);
3350 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3351 return NULL;
3354 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3355 return NULL;
3357 dirp->dd_fd = 0;
3358 dirp->dd_loc = 0;
3359 dirp->dd_size = 0;
3361 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3362 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3363 /* Note: We don't support symlinks to file names on FAT volumes.
3364 Doing so would mean punishing 99.99% of use cases by resolving
3365 all the possible symlinks in FILENAME, recursively. */
3366 dir_is_fat = is_fat_volume (filename, NULL);
3368 return dirp;
3371 void
3372 sys_closedir (DIR *dirp)
3374 /* If we have a find-handle open, close it. */
3375 if (dir_find_handle != INVALID_HANDLE_VALUE)
3377 FindClose (dir_find_handle);
3378 dir_find_handle = INVALID_HANDLE_VALUE;
3380 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3382 close_unc_volume (wnet_enum_handle);
3383 wnet_enum_handle = INVALID_HANDLE_VALUE;
3385 xfree ((char *) dirp);
3388 struct dirent *
3389 sys_readdir (DIR *dirp)
3391 int downcase = !NILP (Vw32_downcase_file_names);
3393 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3395 if (!read_unc_volume (wnet_enum_handle,
3396 dir_find_data_w.cFileName,
3397 dir_find_data_a.cFileName,
3398 MAX_PATH))
3399 return NULL;
3401 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3402 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3404 char filename[MAX_UTF8_PATH + 2];
3405 int ln;
3407 strcpy (filename, dir_pathname);
3408 ln = strlen (filename) - 1;
3409 if (!IS_DIRECTORY_SEP (filename[ln]))
3410 strcat (filename, "\\");
3411 strcat (filename, "*");
3413 /* Note: No need to resolve symlinks in FILENAME, because
3414 FindFirst opens the directory that is the target of a
3415 symlink. */
3416 if (w32_unicode_filenames)
3418 wchar_t fnw[MAX_PATH];
3420 filename_to_utf16 (filename, fnw);
3421 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3423 else
3425 char fna[MAX_PATH];
3427 filename_to_ansi (filename, fna);
3428 /* If FILENAME is not representable by the current ANSI
3429 codepage, we don't want FindFirstFileA to interpret the
3430 '?' characters as a wildcard. */
3431 if (_mbspbrk (fna, "?"))
3432 dir_find_handle = INVALID_HANDLE_VALUE;
3433 else
3434 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3437 if (dir_find_handle == INVALID_HANDLE_VALUE)
3438 return NULL;
3440 else if (w32_unicode_filenames)
3442 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3443 return NULL;
3445 else
3447 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3448 return NULL;
3451 /* Emacs never uses this value, so don't bother making it match
3452 value returned by stat(). */
3453 dir_static.d_ino = 1;
3455 if (w32_unicode_filenames)
3457 if (downcase || dir_is_fat)
3459 wchar_t tem[MAX_PATH];
3461 wcscpy (tem, dir_find_data_w.cFileName);
3462 CharLowerW (tem);
3463 filename_from_utf16 (tem, dir_static.d_name);
3465 else
3466 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3467 last_dir_find_data = DIR_FIND_DATA_W;
3469 else
3471 char tem[MAX_PATH];
3473 /* If the file name in cFileName[] includes `?' characters, it
3474 means the original file name used characters that cannot be
3475 represented by the current ANSI codepage. To avoid total
3476 lossage, retrieve the short 8+3 alias of the long file
3477 name. */
3478 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3480 strcpy (tem, dir_find_data_a.cAlternateFileName);
3481 /* 8+3 aliases are returned in all caps, which could break
3482 various alists that look at filenames' extensions. */
3483 downcase = 1;
3485 else if (downcase || dir_is_fat)
3486 strcpy (tem, dir_find_data_a.cFileName);
3487 else
3488 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3489 if (downcase || dir_is_fat)
3491 _mbslwr (tem);
3492 filename_from_ansi (tem, dir_static.d_name);
3494 last_dir_find_data = DIR_FIND_DATA_A;
3497 dir_static.d_namlen = strlen (dir_static.d_name);
3498 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3499 dir_static.d_namlen - dir_static.d_namlen % 4;
3501 return &dir_static;
3504 static HANDLE
3505 open_unc_volume (const char *path)
3507 const char *fn = map_w32_filename (path, NULL);
3508 DWORD result;
3509 HANDLE henum;
3511 if (w32_unicode_filenames)
3513 NETRESOURCEW nrw;
3514 wchar_t fnw[MAX_PATH];
3516 nrw.dwScope = RESOURCE_GLOBALNET;
3517 nrw.dwType = RESOURCETYPE_DISK;
3518 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3519 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3520 nrw.lpLocalName = NULL;
3521 filename_to_utf16 (fn, fnw);
3522 nrw.lpRemoteName = fnw;
3523 nrw.lpComment = NULL;
3524 nrw.lpProvider = NULL;
3526 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3527 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3529 else
3531 NETRESOURCEA nra;
3532 char fna[MAX_PATH];
3534 nra.dwScope = RESOURCE_GLOBALNET;
3535 nra.dwType = RESOURCETYPE_DISK;
3536 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3537 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3538 nra.lpLocalName = NULL;
3539 filename_to_ansi (fn, fna);
3540 nra.lpRemoteName = fna;
3541 nra.lpComment = NULL;
3542 nra.lpProvider = NULL;
3544 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3545 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3547 if (result == NO_ERROR)
3548 return henum;
3549 else
3550 return INVALID_HANDLE_VALUE;
3553 static void *
3554 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3556 DWORD count;
3557 int result;
3558 char *buffer;
3559 DWORD bufsize = 512;
3560 void *retval;
3562 count = 1;
3563 if (w32_unicode_filenames)
3565 wchar_t *ptrw;
3567 bufsize *= 2;
3568 buffer = alloca (bufsize);
3569 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3570 if (result != NO_ERROR)
3571 return NULL;
3572 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3573 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3574 ptrw += 2;
3575 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3576 ptrw++;
3577 wcsncpy (fname_w, ptrw, size);
3578 retval = fname_w;
3580 else
3582 int dbcs_p = max_filename_mbslen () > 1;
3583 char *ptra;
3585 buffer = alloca (bufsize);
3586 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3587 if (result != NO_ERROR)
3588 return NULL;
3589 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3590 ptra += 2;
3591 if (!dbcs_p)
3592 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3593 else
3595 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3596 ptra = CharNextExA (file_name_codepage, ptra, 0);
3598 ptra++;
3599 strncpy (fname_a, ptra, size);
3600 retval = fname_a;
3603 return retval;
3606 static void
3607 close_unc_volume (HANDLE henum)
3609 if (henum != INVALID_HANDLE_VALUE)
3610 WNetCloseEnum (henum);
3613 static DWORD
3614 unc_volume_file_attributes (const char *path)
3616 HANDLE henum;
3617 DWORD attrs;
3619 henum = open_unc_volume (path);
3620 if (henum == INVALID_HANDLE_VALUE)
3621 return -1;
3623 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3625 close_unc_volume (henum);
3627 return attrs;
3630 /* Ensure a network connection is authenticated. */
3631 static void
3632 logon_network_drive (const char *path)
3634 char share[MAX_UTF8_PATH];
3635 int n_slashes;
3636 char drive[4];
3637 UINT drvtype;
3638 char *p;
3639 DWORD val;
3641 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3642 drvtype = DRIVE_REMOTE;
3643 else if (path[0] == '\0' || path[1] != ':')
3644 drvtype = GetDriveType (NULL);
3645 else
3647 drive[0] = path[0];
3648 drive[1] = ':';
3649 drive[2] = '\\';
3650 drive[3] = '\0';
3651 drvtype = GetDriveType (drive);
3654 /* Only logon to networked drives. */
3655 if (drvtype != DRIVE_REMOTE)
3656 return;
3658 n_slashes = 2;
3659 strncpy (share, path, MAX_UTF8_PATH);
3660 /* Truncate to just server and share name. */
3661 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3663 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3665 *p = '\0';
3666 break;
3670 if (w32_unicode_filenames)
3672 NETRESOURCEW resourcew;
3673 wchar_t share_w[MAX_PATH];
3675 resourcew.dwScope = RESOURCE_GLOBALNET;
3676 resourcew.dwType = RESOURCETYPE_DISK;
3677 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3678 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3679 resourcew.lpLocalName = NULL;
3680 filename_to_utf16 (share, share_w);
3681 resourcew.lpRemoteName = share_w;
3682 resourcew.lpProvider = NULL;
3684 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3686 else
3688 NETRESOURCEA resourcea;
3689 char share_a[MAX_PATH];
3691 resourcea.dwScope = RESOURCE_GLOBALNET;
3692 resourcea.dwType = RESOURCETYPE_DISK;
3693 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3694 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3695 resourcea.lpLocalName = NULL;
3696 filename_to_ansi (share, share_a);
3697 resourcea.lpRemoteName = share_a;
3698 resourcea.lpProvider = NULL;
3700 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3703 switch (val)
3705 case NO_ERROR:
3706 case ERROR_ALREADY_ASSIGNED:
3707 break;
3708 case ERROR_ACCESS_DENIED:
3709 case ERROR_LOGON_FAILURE:
3710 errno = EACCES;
3711 break;
3712 case ERROR_BUSY:
3713 errno = EAGAIN;
3714 break;
3715 case ERROR_BAD_NET_NAME:
3716 case ERROR_NO_NET_OR_BAD_PATH:
3717 case ERROR_NO_NETWORK:
3718 case ERROR_CANCELLED:
3719 default:
3720 errno = ENOENT;
3721 break;
3725 /* Emulate faccessat(2). */
3727 faccessat (int dirfd, const char * path, int mode, int flags)
3729 DWORD attributes;
3731 if (dirfd != AT_FDCWD
3732 && !(IS_DIRECTORY_SEP (path[0])
3733 || IS_DEVICE_SEP (path[1])))
3735 errno = EBADF;
3736 return -1;
3739 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3740 newer versions blow up when passed D_OK. */
3741 path = map_w32_filename (path, NULL);
3742 /* If the last element of PATH is a symlink, we need to resolve it
3743 to get the attributes of its target file. Note: any symlinks in
3744 PATH elements other than the last one are transparently resolved
3745 by GetFileAttributes below. */
3746 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3747 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3748 path = chase_symlinks (path);
3750 if (w32_unicode_filenames)
3752 wchar_t path_w[MAX_PATH];
3754 filename_to_utf16 (path, path_w);
3755 attributes = GetFileAttributesW (path_w);
3757 else
3759 char path_a[MAX_PATH];
3761 filename_to_ansi (path, path_a);
3762 attributes = GetFileAttributesA (path_a);
3765 if (attributes == -1)
3767 DWORD w32err = GetLastError ();
3769 switch (w32err)
3771 case ERROR_INVALID_NAME:
3772 case ERROR_BAD_PATHNAME:
3773 if (is_unc_volume (path))
3775 attributes = unc_volume_file_attributes (path);
3776 if (attributes == -1)
3778 errno = EACCES;
3779 return -1;
3781 break;
3783 /* FALLTHROUGH */
3784 case ERROR_FILE_NOT_FOUND:
3785 case ERROR_BAD_NETPATH:
3786 errno = ENOENT;
3787 break;
3788 default:
3789 errno = EACCES;
3790 break;
3792 return -1;
3794 if ((mode & X_OK) != 0
3795 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3797 errno = EACCES;
3798 return -1;
3800 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3802 errno = EACCES;
3803 return -1;
3805 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3807 errno = EACCES;
3808 return -1;
3810 return 0;
3813 /* A version of 'access' to be used locally with file names in
3814 locale-specific encoding. Does not resolve symlinks and does not
3815 support file names on FAT12 and FAT16 volumes, but that's OK, since
3816 we only invoke this function for files inside the Emacs source or
3817 installation tree, on directories (so any symlinks should have the
3818 directory bit set), and on short file names such as "C:/.emacs". */
3819 static int
3820 sys_access (const char *fname, int mode)
3822 char fname_copy[MAX_PATH], *p;
3823 DWORD attributes;
3825 strcpy (fname_copy, fname);
3826 /* Do the equivalent of unixtodos_filename. */
3827 for (p = fname_copy; *p; p = CharNext (p))
3828 if (*p == '/')
3829 *p = '\\';
3831 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
3833 DWORD w32err = GetLastError ();
3835 switch (w32err)
3837 case ERROR_INVALID_NAME:
3838 case ERROR_BAD_PATHNAME:
3839 case ERROR_FILE_NOT_FOUND:
3840 case ERROR_BAD_NETPATH:
3841 errno = ENOENT;
3842 break;
3843 default:
3844 errno = EACCES;
3845 break;
3847 return -1;
3849 if ((mode & X_OK) != 0
3850 && !(is_exec (fname_copy)
3851 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3853 errno = EACCES;
3854 return -1;
3856 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3858 errno = EACCES;
3859 return -1;
3861 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3863 errno = EACCES;
3864 return -1;
3866 return 0;
3869 /* Shadow some MSVC runtime functions to map requests for long filenames
3870 to reasonable short names if necessary. This was originally added to
3871 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3872 long file names. */
3875 sys_chdir (const char * path)
3877 path = map_w32_filename (path, NULL);
3878 if (w32_unicode_filenames)
3880 wchar_t newdir_w[MAX_PATH];
3882 if (filename_to_utf16 (path, newdir_w) == 0)
3883 return _wchdir (newdir_w);
3884 return -1;
3886 else
3888 char newdir_a[MAX_PATH];
3890 if (filename_to_ansi (path, newdir_a) == 0)
3891 return _chdir (newdir_a);
3892 return -1;
3897 sys_chmod (const char * path, int mode)
3899 path = chase_symlinks (map_w32_filename (path, NULL));
3900 if (w32_unicode_filenames)
3902 wchar_t path_w[MAX_PATH];
3904 filename_to_utf16 (path, path_w);
3905 return _wchmod (path_w, mode);
3907 else
3909 char path_a[MAX_PATH];
3911 filename_to_ansi (path, path_a);
3912 return _chmod (path_a, mode);
3917 sys_creat (const char * path, int mode)
3919 path = map_w32_filename (path, NULL);
3920 if (w32_unicode_filenames)
3922 wchar_t path_w[MAX_PATH];
3924 filename_to_utf16 (path, path_w);
3925 return _wcreat (path_w, mode);
3927 else
3929 char path_a[MAX_PATH];
3931 filename_to_ansi (path, path_a);
3932 return _creat (path_a, mode);
3936 FILE *
3937 sys_fopen (const char * path, const char * mode)
3939 int fd;
3940 int oflag;
3941 const char * mode_save = mode;
3943 /* Force all file handles to be non-inheritable. This is necessary to
3944 ensure child processes don't unwittingly inherit handles that might
3945 prevent future file access. */
3947 if (mode[0] == 'r')
3948 oflag = O_RDONLY;
3949 else if (mode[0] == 'w' || mode[0] == 'a')
3950 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3951 else
3952 return NULL;
3954 /* Only do simplistic option parsing. */
3955 while (*++mode)
3956 if (mode[0] == '+')
3958 oflag &= ~(O_RDONLY | O_WRONLY);
3959 oflag |= O_RDWR;
3961 else if (mode[0] == 'b')
3963 oflag &= ~O_TEXT;
3964 oflag |= O_BINARY;
3966 else if (mode[0] == 't')
3968 oflag &= ~O_BINARY;
3969 oflag |= O_TEXT;
3971 else break;
3973 path = map_w32_filename (path, NULL);
3974 if (w32_unicode_filenames)
3976 wchar_t path_w[MAX_PATH];
3978 filename_to_utf16 (path, path_w);
3979 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
3981 else
3983 char path_a[MAX_PATH];
3985 filename_to_ansi (path, path_a);
3986 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
3988 if (fd < 0)
3989 return NULL;
3991 return _fdopen (fd, mode_save);
3994 /* This only works on NTFS volumes, but is useful to have. */
3996 sys_link (const char * old, const char * new)
3998 HANDLE fileh;
3999 int result = -1;
4000 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4001 wchar_t oldname_w[MAX_PATH];
4002 char oldname_a[MAX_PATH];
4004 if (old == NULL || new == NULL)
4006 errno = ENOENT;
4007 return -1;
4010 strcpy (oldname, map_w32_filename (old, NULL));
4011 strcpy (newname, map_w32_filename (new, NULL));
4013 if (w32_unicode_filenames)
4015 filename_to_utf16 (oldname, oldname_w);
4016 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4017 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4019 else
4021 filename_to_ansi (oldname, oldname_a);
4022 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4023 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4025 if (fileh != INVALID_HANDLE_VALUE)
4027 int wlen;
4029 /* Confusingly, the "alternate" stream name field does not apply
4030 when restoring a hard link, and instead contains the actual
4031 stream data for the link (ie. the name of the link to create).
4032 The WIN32_STREAM_ID structure before the cStreamName field is
4033 the stream header, which is then immediately followed by the
4034 stream data. */
4036 struct {
4037 WIN32_STREAM_ID wid;
4038 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4039 } data;
4041 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4042 indicates that flag is unsupported for CP_UTF8, and OTOH says
4043 it is the default anyway. */
4044 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4045 data.wid.cStreamName, MAX_PATH);
4046 if (wlen > 0)
4048 LPVOID context = NULL;
4049 DWORD wbytes = 0;
4051 data.wid.dwStreamId = BACKUP_LINK;
4052 data.wid.dwStreamAttributes = 0;
4053 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4054 data.wid.Size.HighPart = 0;
4055 data.wid.dwStreamNameSize = 0;
4057 if (BackupWrite (fileh, (LPBYTE)&data,
4058 offsetof (WIN32_STREAM_ID, cStreamName)
4059 + data.wid.Size.LowPart,
4060 &wbytes, FALSE, FALSE, &context)
4061 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4063 /* succeeded */
4064 result = 0;
4066 else
4068 DWORD err = GetLastError ();
4069 DWORD attributes;
4071 switch (err)
4073 case ERROR_ACCESS_DENIED:
4074 /* This is what happens when OLDNAME is a directory,
4075 since Windows doesn't support hard links to
4076 directories. Posix says to set errno to EPERM in
4077 that case. */
4078 if (w32_unicode_filenames)
4079 attributes = GetFileAttributesW (oldname_w);
4080 else
4081 attributes = GetFileAttributesA (oldname_a);
4082 if (attributes != -1
4083 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4084 errno = EPERM;
4085 else if (attributes == -1
4086 && is_unc_volume (oldname)
4087 && unc_volume_file_attributes (oldname) != -1)
4088 errno = EPERM;
4089 else
4090 errno = EACCES;
4091 break;
4092 case ERROR_TOO_MANY_LINKS:
4093 errno = EMLINK;
4094 break;
4095 case ERROR_NOT_SAME_DEVICE:
4096 errno = EXDEV;
4097 break;
4098 default:
4099 errno = EINVAL;
4100 break;
4105 CloseHandle (fileh);
4107 else
4108 errno = ENOENT;
4110 return result;
4114 sys_mkdir (const char * path)
4116 path = map_w32_filename (path, NULL);
4118 if (w32_unicode_filenames)
4120 wchar_t path_w[MAX_PATH];
4122 filename_to_utf16 (path, path_w);
4123 return _wmkdir (path_w);
4125 else
4127 char path_a[MAX_PATH];
4129 filename_to_ansi (path, path_a);
4130 return _mkdir (path_a);
4135 sys_open (const char * path, int oflag, int mode)
4137 const char* mpath = map_w32_filename (path, NULL);
4138 int res = -1;
4140 if (w32_unicode_filenames)
4142 wchar_t mpath_w[MAX_PATH];
4144 filename_to_utf16 (mpath, mpath_w);
4145 /* If possible, try to open file without _O_CREAT, to be able to
4146 write to existing hidden and system files. Force all file
4147 handles to be non-inheritable. */
4148 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4149 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4150 if (res < 0)
4151 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4153 else
4155 char mpath_a[MAX_PATH];
4157 filename_to_ansi (mpath, mpath_a);
4158 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4159 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4160 if (res < 0)
4161 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4164 return res;
4167 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4168 when using mktemp.
4170 Standard algorithm for generating a temporary file name seems to be
4171 use pid or tid with a letter on the front (in place of the 6 X's)
4172 and cycle through the letters to find a unique name. We extend
4173 that to allow any reasonable character as the first of the 6 X's,
4174 so that the number of simultaneously used temporary files will be
4175 greater. */
4178 mkostemp (char * template, int flags)
4180 char * p;
4181 int i, fd = -1;
4182 unsigned uid = GetCurrentThreadId ();
4183 int save_errno = errno;
4184 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4186 errno = EINVAL;
4187 if (template == NULL)
4188 return -1;
4190 p = template + strlen (template);
4191 i = 5;
4192 /* replace up to the last 5 X's with uid in decimal */
4193 while (--p >= template && p[0] == 'X' && --i >= 0)
4195 p[0] = '0' + uid % 10;
4196 uid /= 10;
4199 if (i < 0 && p[0] == 'X')
4201 i = 0;
4204 p[0] = first_char[i];
4205 if ((fd = sys_open (template,
4206 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4207 S_IRUSR | S_IWUSR)) >= 0
4208 || errno != EEXIST)
4210 if (fd >= 0)
4211 errno = save_errno;
4212 return fd;
4215 while (++i < sizeof (first_char));
4218 /* Template is badly formed or else we can't generate a unique name. */
4219 return -1;
4223 fchmod (int fd, mode_t mode)
4225 return 0;
4229 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4231 BOOL result;
4232 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4233 int newname_dev;
4234 int oldname_dev;
4235 bool have_temp_a = false;
4237 /* MoveFile on Windows 95 doesn't correctly change the short file name
4238 alias in a number of circumstances (it is not easy to predict when
4239 just by looking at oldname and newname, unfortunately). In these
4240 cases, renaming through a temporary name avoids the problem.
4242 A second problem on Windows 95 is that renaming through a temp name when
4243 newname is uppercase fails (the final long name ends up in
4244 lowercase, although the short alias might be uppercase) UNLESS the
4245 long temp name is not 8.3.
4247 So, on Windows 95 we always rename through a temp name, and we make sure
4248 the temp name has a long extension to ensure correct renaming. */
4250 strcpy (temp, map_w32_filename (oldname, NULL));
4252 /* volume_info is set indirectly by map_w32_filename. */
4253 oldname_dev = volume_info.serialnum;
4255 if (os_subtype == OS_9X)
4257 char * o;
4258 char * p;
4259 int i = 0;
4260 char oldname_a[MAX_PATH];
4262 oldname = map_w32_filename (oldname, NULL);
4263 filename_to_ansi (oldname, oldname_a);
4264 filename_to_ansi (temp, temp_a);
4265 if ((o = strrchr (oldname_a, '\\')))
4266 o++;
4267 else
4268 o = (char *) oldname_a;
4270 if ((p = strrchr (temp_a, '\\')))
4271 p++;
4272 else
4273 p = temp_a;
4277 /* Force temp name to require a manufactured 8.3 alias - this
4278 seems to make the second rename work properly. */
4279 sprintf (p, "_.%s.%u", o, i);
4280 i++;
4281 result = rename (oldname_a, temp_a);
4283 /* This loop must surely terminate! */
4284 while (result < 0 && errno == EEXIST);
4285 if (result < 0)
4286 return -1;
4287 have_temp_a = true;
4290 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4291 (at least if it is a file; don't do this for directories).
4293 Since we mustn't do this if we are just changing the case of the
4294 file name (we would end up deleting the file we are trying to
4295 rename!), we let rename detect if the destination file already
4296 exists - that way we avoid the possible pitfalls of trying to
4297 determine ourselves whether two names really refer to the same
4298 file, which is not always possible in the general case. (Consider
4299 all the permutations of shared or subst'd drives, etc.) */
4301 newname = map_w32_filename (newname, NULL);
4303 /* volume_info is set indirectly by map_w32_filename. */
4304 newname_dev = volume_info.serialnum;
4306 if (w32_unicode_filenames)
4308 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4310 filename_to_utf16 (temp, temp_w);
4311 filename_to_utf16 (newname, newname_w);
4312 result = _wrename (temp_w, newname_w);
4313 if (result < 0 && force)
4315 DWORD w32err = GetLastError ();
4317 if (errno == EACCES
4318 && newname_dev != oldname_dev)
4320 /* The implementation of `rename' on Windows does not return
4321 errno = EXDEV when you are moving a directory to a
4322 different storage device (ex. logical disk). It returns
4323 EACCES instead. So here we handle such situations and
4324 return EXDEV. */
4325 DWORD attributes;
4327 if ((attributes = GetFileAttributesW (temp_w)) != -1
4328 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4329 errno = EXDEV;
4331 else if (errno == EEXIST)
4333 if (_wchmod (newname_w, 0666) != 0)
4334 return result;
4335 if (_wunlink (newname_w) != 0)
4336 return result;
4337 result = _wrename (temp_w, newname_w);
4339 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4340 && is_symlink (temp))
4342 /* This is Windows prohibiting the user from creating a
4343 symlink in another place, since that requires
4344 privileges. */
4345 errno = EPERM;
4349 else
4351 char newname_a[MAX_PATH];
4353 if (!have_temp_a)
4354 filename_to_ansi (temp, temp_a);
4355 filename_to_ansi (newname, newname_a);
4356 result = rename (temp_a, newname_a);
4357 if (result < 0 && force)
4359 DWORD w32err = GetLastError ();
4361 if (errno == EACCES
4362 && newname_dev != oldname_dev)
4364 DWORD attributes;
4366 if ((attributes = GetFileAttributesA (temp_a)) != -1
4367 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4368 errno = EXDEV;
4370 else if (errno == EEXIST)
4372 if (_chmod (newname_a, 0666) != 0)
4373 return result;
4374 if (_unlink (newname_a) != 0)
4375 return result;
4376 result = rename (temp_a, newname_a);
4378 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4379 && is_symlink (temp))
4380 errno = EPERM;
4384 return result;
4388 sys_rename (char const *old, char const *new)
4390 return sys_rename_replace (old, new, TRUE);
4394 sys_rmdir (const char * path)
4396 path = map_w32_filename (path, NULL);
4398 if (w32_unicode_filenames)
4400 wchar_t path_w[MAX_PATH];
4402 filename_to_utf16 (path, path_w);
4403 return _wrmdir (path_w);
4405 else
4407 char path_a[MAX_PATH];
4409 filename_to_ansi (path, path_a);
4410 return _rmdir (path_a);
4415 sys_unlink (const char * path)
4417 path = map_w32_filename (path, NULL);
4419 if (w32_unicode_filenames)
4421 wchar_t path_w[MAX_PATH];
4423 filename_to_utf16 (path, path_w);
4424 /* On Unix, unlink works without write permission. */
4425 _wchmod (path_w, 0666);
4426 return _wunlink (path_w);
4428 else
4430 char path_a[MAX_PATH];
4432 filename_to_ansi (path, path_a);
4433 _chmod (path_a, 0666);
4434 return _unlink (path_a);
4438 static FILETIME utc_base_ft;
4439 static ULONGLONG utc_base; /* In 100ns units */
4440 static int init = 0;
4442 #define FILETIME_TO_U64(result, ft) \
4443 do { \
4444 ULARGE_INTEGER uiTemp; \
4445 uiTemp.LowPart = (ft).dwLowDateTime; \
4446 uiTemp.HighPart = (ft).dwHighDateTime; \
4447 result = uiTemp.QuadPart; \
4448 } while (0)
4450 static void
4451 initialize_utc_base (void)
4453 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4454 SYSTEMTIME st;
4456 st.wYear = 1970;
4457 st.wMonth = 1;
4458 st.wDay = 1;
4459 st.wHour = 0;
4460 st.wMinute = 0;
4461 st.wSecond = 0;
4462 st.wMilliseconds = 0;
4464 SystemTimeToFileTime (&st, &utc_base_ft);
4465 FILETIME_TO_U64 (utc_base, utc_base_ft);
4468 static time_t
4469 convert_time (FILETIME ft)
4471 ULONGLONG tmp;
4473 if (!init)
4475 initialize_utc_base ();
4476 init = 1;
4479 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4480 return 0;
4482 FILETIME_TO_U64 (tmp, ft);
4483 return (time_t) ((tmp - utc_base) / 10000000L);
4486 static void
4487 convert_from_time_t (time_t time, FILETIME * pft)
4489 ULARGE_INTEGER tmp;
4491 if (!init)
4493 initialize_utc_base ();
4494 init = 1;
4497 /* time in 100ns units since 1-Jan-1601 */
4498 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4499 pft->dwHighDateTime = tmp.HighPart;
4500 pft->dwLowDateTime = tmp.LowPart;
4503 static PSECURITY_DESCRIPTOR
4504 get_file_security_desc_by_handle (HANDLE h)
4506 PSECURITY_DESCRIPTOR psd = NULL;
4507 DWORD err;
4508 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4509 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4511 err = get_security_info (h, SE_FILE_OBJECT, si,
4512 NULL, NULL, NULL, NULL, &psd);
4513 if (err != ERROR_SUCCESS)
4514 return NULL;
4516 return psd;
4519 static PSECURITY_DESCRIPTOR
4520 get_file_security_desc_by_name (const char *fname)
4522 PSECURITY_DESCRIPTOR psd = NULL;
4523 DWORD sd_len, err;
4524 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4525 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4527 if (!get_file_security (fname, si, psd, 0, &sd_len))
4529 err = GetLastError ();
4530 if (err != ERROR_INSUFFICIENT_BUFFER)
4531 return NULL;
4534 psd = xmalloc (sd_len);
4535 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4537 xfree (psd);
4538 return NULL;
4541 return psd;
4544 static DWORD
4545 get_rid (PSID sid)
4547 unsigned n_subauthorities;
4549 /* Use the last sub-authority value of the RID, the relative
4550 portion of the SID, as user/group ID. */
4551 n_subauthorities = *get_sid_sub_authority_count (sid);
4552 if (n_subauthorities < 1)
4553 return 0; /* the "World" RID */
4554 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4557 /* Caching SID and account values for faster lokup. */
4559 struct w32_id {
4560 unsigned rid;
4561 struct w32_id *next;
4562 char name[GNLEN+1];
4563 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4566 static struct w32_id *w32_idlist;
4568 static int
4569 w32_cached_id (PSID sid, unsigned *id, char *name)
4571 struct w32_id *tail, *found;
4573 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4575 if (equal_sid ((PSID)tail->sid, sid))
4577 found = tail;
4578 break;
4581 if (found)
4583 *id = found->rid;
4584 strcpy (name, found->name);
4585 return 1;
4587 else
4588 return 0;
4591 static void
4592 w32_add_to_cache (PSID sid, unsigned id, char *name)
4594 DWORD sid_len;
4595 struct w32_id *new_entry;
4597 /* We don't want to leave behind stale cache from when Emacs was
4598 dumped. */
4599 if (initialized)
4601 sid_len = get_length_sid (sid);
4602 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4603 if (new_entry)
4605 new_entry->rid = id;
4606 strcpy (new_entry->name, name);
4607 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4608 new_entry->next = w32_idlist;
4609 w32_idlist = new_entry;
4614 #define UID 1
4615 #define GID 2
4617 static int
4618 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4620 PSID sid = NULL;
4621 BOOL dflt;
4622 SID_NAME_USE ignore;
4623 char name[UNLEN+1];
4624 DWORD name_len = sizeof (name);
4625 char domain[1024];
4626 DWORD domain_len = sizeof (domain);
4627 int use_dflt = 0;
4628 int result;
4630 if (what == UID)
4631 result = get_security_descriptor_owner (psd, &sid, &dflt);
4632 else if (what == GID)
4633 result = get_security_descriptor_group (psd, &sid, &dflt);
4634 else
4635 result = 0;
4637 if (!result || !is_valid_sid (sid))
4638 use_dflt = 1;
4639 else if (!w32_cached_id (sid, id, nm))
4641 if (!lookup_account_sid (NULL, sid, name, &name_len,
4642 domain, &domain_len, &ignore)
4643 || name_len > UNLEN+1)
4644 use_dflt = 1;
4645 else
4647 *id = get_rid (sid);
4648 strcpy (nm, name);
4649 w32_add_to_cache (sid, *id, name);
4652 return use_dflt;
4655 static void
4656 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4658 int dflt_usr = 0, dflt_grp = 0;
4660 if (!psd)
4662 dflt_usr = 1;
4663 dflt_grp = 1;
4665 else
4667 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4668 dflt_usr = 1;
4669 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4670 dflt_grp = 1;
4672 /* Consider files to belong to current user/group, if we cannot get
4673 more accurate information. */
4674 if (dflt_usr)
4676 st->st_uid = dflt_passwd.pw_uid;
4677 strcpy (st->st_uname, dflt_passwd.pw_name);
4679 if (dflt_grp)
4681 st->st_gid = dflt_passwd.pw_gid;
4682 strcpy (st->st_gname, dflt_group.gr_name);
4686 /* Return non-zero if NAME is a potentially slow filesystem. */
4688 is_slow_fs (const char *name)
4690 char drive_root[4];
4691 UINT devtype;
4693 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4694 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4695 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4696 devtype = GetDriveType (NULL); /* use root of current drive */
4697 else
4699 /* GetDriveType needs the root directory of the drive. */
4700 strncpy (drive_root, name, 2);
4701 drive_root[2] = '\\';
4702 drive_root[3] = '\0';
4703 devtype = GetDriveType (drive_root);
4705 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4708 /* If this is non-zero, the caller wants accurate information about
4709 file's owner and group, which could be expensive to get. dired.c
4710 uses this flag when needed for the job at hand. */
4711 int w32_stat_get_owner_group;
4713 /* MSVC stat function can't cope with UNC names and has other bugs, so
4714 replace it with our own. This also allows us to calculate consistent
4715 inode values and owner/group without hacks in the main Emacs code,
4716 and support file names encoded in UTF-8. */
4718 static int
4719 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4721 char *name, *save_name, *r;
4722 WIN32_FIND_DATAW wfd_w;
4723 WIN32_FIND_DATAA wfd_a;
4724 HANDLE fh;
4725 unsigned __int64 fake_inode = 0;
4726 int permission;
4727 int len;
4728 int rootdir = FALSE;
4729 PSECURITY_DESCRIPTOR psd = NULL;
4730 int is_a_symlink = 0;
4731 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4732 DWORD access_rights = 0;
4733 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4734 FILETIME ctime, atime, wtime;
4735 wchar_t name_w[MAX_PATH];
4736 char name_a[MAX_PATH];
4738 if (path == NULL || buf == NULL)
4740 errno = EFAULT;
4741 return -1;
4744 save_name = name = (char *) map_w32_filename (path, &path);
4745 /* Must be valid filename, no wild cards or other invalid
4746 characters. */
4747 if (strpbrk (name, "*?|<>\""))
4749 errno = ENOENT;
4750 return -1;
4753 len = strlen (name);
4754 /* Allocate 1 extra byte so that we could append a slash to a root
4755 directory, down below. */
4756 name = strcpy (alloca (len + 2), name);
4758 /* Avoid a somewhat costly call to is_symlink if the filesystem
4759 doesn't support symlinks. */
4760 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4761 is_a_symlink = is_symlink (name);
4763 /* Plan A: Open the file and get all the necessary information via
4764 the resulting handle. This solves several issues in one blow:
4766 . retrieves attributes for the target of a symlink, if needed
4767 . gets attributes of root directories and symlinks pointing to
4768 root directories, thus avoiding the need for special-casing
4769 these and detecting them by examining the file-name format
4770 . retrieves more accurate attributes (e.g., non-zero size for
4771 some directories, esp. directories that are junction points)
4772 . correctly resolves "c:/..", "/.." and similar file names
4773 . avoids run-time penalties for 99% of use cases
4775 Plan A is always tried first, unless the user asked not to (but
4776 if the file is a symlink and we need to follow links, we try Plan
4777 A even if the user asked not to).
4779 If Plan A fails, we go to Plan B (below), where various
4780 potentially expensive techniques must be used to handle "special"
4781 files such as UNC volumes etc. */
4782 if (!(NILP (Vw32_get_true_file_attributes)
4783 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4784 /* Following symlinks requires getting the info by handle. */
4785 || (is_a_symlink && follow_symlinks))
4787 BY_HANDLE_FILE_INFORMATION info;
4789 if (is_a_symlink && !follow_symlinks)
4790 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4791 /* READ_CONTROL access rights are required to get security info
4792 by handle. But if the OS doesn't support security in the
4793 first place, we don't need to try. */
4794 if (is_windows_9x () != TRUE)
4795 access_rights |= READ_CONTROL;
4797 if (w32_unicode_filenames)
4799 filename_to_utf16 (name, name_w);
4800 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4801 file_flags, NULL);
4802 /* If CreateFile fails with READ_CONTROL, try again with
4803 zero as access rights. */
4804 if (fh == INVALID_HANDLE_VALUE && access_rights)
4805 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
4806 file_flags, NULL);
4808 else
4810 filename_to_ansi (name, name_a);
4811 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
4812 file_flags, NULL);
4813 if (fh == INVALID_HANDLE_VALUE && access_rights)
4814 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
4815 file_flags, NULL);
4817 if (fh == INVALID_HANDLE_VALUE)
4818 goto no_true_file_attributes;
4820 /* This is more accurate in terms of getting the correct number
4821 of links, but is quite slow (it is noticeable when Emacs is
4822 making a list of file name completions). */
4823 if (GetFileInformationByHandle (fh, &info))
4825 nlinks = info.nNumberOfLinks;
4826 /* Might as well use file index to fake inode values, but this
4827 is not guaranteed to be unique unless we keep a handle open
4828 all the time (even then there are situations where it is
4829 not unique). Reputedly, there are at most 48 bits of info
4830 (on NTFS, presumably less on FAT). */
4831 fake_inode = info.nFileIndexHigh;
4832 fake_inode <<= 32;
4833 fake_inode += info.nFileIndexLow;
4834 serialnum = info.dwVolumeSerialNumber;
4835 fs_high = info.nFileSizeHigh;
4836 fs_low = info.nFileSizeLow;
4837 ctime = info.ftCreationTime;
4838 atime = info.ftLastAccessTime;
4839 wtime = info.ftLastWriteTime;
4840 fattrs = info.dwFileAttributes;
4842 else
4844 /* We don't go to Plan B here, because it's not clear that
4845 it's a good idea. The only known use case where
4846 CreateFile succeeds, but GetFileInformationByHandle fails
4847 (with ERROR_INVALID_FUNCTION) is for character devices
4848 such as NUL, PRN, etc. For these, switching to Plan B is
4849 a net loss, because we lose the character device
4850 attribute returned by GetFileType below (FindFirstFile
4851 doesn't set that bit in the attributes), and the other
4852 fields don't make sense for character devices anyway.
4853 Emacs doesn't really care for non-file entities in the
4854 context of l?stat, so neither do we. */
4856 /* w32err is assigned so one could put a breakpoint here and
4857 examine its value, when GetFileInformationByHandle
4858 fails. */
4859 DWORD w32err = GetLastError ();
4861 switch (w32err)
4863 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4864 errno = ENOENT;
4865 return -1;
4869 /* Test for a symlink before testing for a directory, since
4870 symlinks to directories have the directory bit set, but we
4871 don't want them to appear as directories. */
4872 if (is_a_symlink && !follow_symlinks)
4873 buf->st_mode = S_IFLNK;
4874 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4875 buf->st_mode = S_IFDIR;
4876 else
4878 DWORD ftype = GetFileType (fh);
4880 switch (ftype)
4882 case FILE_TYPE_DISK:
4883 buf->st_mode = S_IFREG;
4884 break;
4885 case FILE_TYPE_PIPE:
4886 buf->st_mode = S_IFIFO;
4887 break;
4888 case FILE_TYPE_CHAR:
4889 case FILE_TYPE_UNKNOWN:
4890 default:
4891 buf->st_mode = S_IFCHR;
4894 /* We produce the fallback owner and group data, based on the
4895 current user that runs Emacs, in the following cases:
4897 . caller didn't request owner and group info
4898 . this is Windows 9X
4899 . getting security by handle failed, and we need to produce
4900 information for the target of a symlink (this is better
4901 than producing a potentially misleading info about the
4902 symlink itself)
4904 If getting security by handle fails, and we don't need to
4905 resolve symlinks, we try getting security by name. */
4906 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4907 get_file_owner_and_group (NULL, buf);
4908 else
4910 psd = get_file_security_desc_by_handle (fh);
4911 if (psd)
4913 get_file_owner_and_group (psd, buf);
4914 LocalFree (psd);
4916 else if (!(is_a_symlink && follow_symlinks))
4918 psd = get_file_security_desc_by_name (name);
4919 get_file_owner_and_group (psd, buf);
4920 xfree (psd);
4922 else
4923 get_file_owner_and_group (NULL, buf);
4925 CloseHandle (fh);
4927 else
4929 no_true_file_attributes:
4930 /* Plan B: Either getting a handle on the file failed, or the
4931 caller explicitly asked us to not bother making this
4932 information more accurate.
4934 Implementation note: In Plan B, we never bother to resolve
4935 symlinks, even if we got here because we tried Plan A and
4936 failed. That's because, even if the caller asked for extra
4937 precision by setting Vw32_get_true_file_attributes to t,
4938 resolving symlinks requires acquiring a file handle to the
4939 symlink, which we already know will fail. And if the user
4940 did not ask for extra precision, resolving symlinks will fly
4941 in the face of that request, since the user then wants the
4942 lightweight version of the code. */
4943 rootdir = (path >= save_name + len - 1
4944 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4946 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4947 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4948 if (IS_DIRECTORY_SEP (r[0])
4949 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4950 r[1] = r[2] = '\0';
4952 /* Note: If NAME is a symlink to the root of a UNC volume
4953 (i.e. "\\SERVER"), we will not detect that here, and we will
4954 return data about the symlink as result of FindFirst below.
4955 This is unfortunate, but that marginal use case does not
4956 justify a call to chase_symlinks which would impose a penalty
4957 on all the other use cases. (We get here for symlinks to
4958 roots of UNC volumes because CreateFile above fails for them,
4959 unlike with symlinks to root directories X:\ of drives.) */
4960 if (is_unc_volume (name))
4962 fattrs = unc_volume_file_attributes (name);
4963 if (fattrs == -1)
4964 return -1;
4966 ctime = atime = wtime = utc_base_ft;
4968 else if (rootdir)
4970 /* Make sure root directories end in a slash. */
4971 if (!IS_DIRECTORY_SEP (name[len-1]))
4972 strcat (name, "\\");
4973 if (GetDriveType (name) < 2)
4975 errno = ENOENT;
4976 return -1;
4979 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4980 ctime = atime = wtime = utc_base_ft;
4982 else
4984 int have_wfd = -1;
4986 /* Make sure non-root directories do NOT end in a slash,
4987 otherwise FindFirstFile might fail. */
4988 if (IS_DIRECTORY_SEP (name[len-1]))
4989 name[len - 1] = 0;
4991 /* (This is hacky, but helps when doing file completions on
4992 network drives.) Optimize by using information available from
4993 active readdir if possible. */
4994 len = strlen (dir_pathname);
4995 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4996 len--;
4997 if (dir_find_handle != INVALID_HANDLE_VALUE
4998 && last_dir_find_data != -1
4999 && !(is_a_symlink && follow_symlinks)
5000 /* The 2 file-name comparisons below support only ASCII
5001 characters, and will lose (compare not equal) when
5002 the file names include non-ASCII characters that are
5003 the same but for the case. However, doing this
5004 properly involves: (a) converting both file names to
5005 UTF-16, (b) lower-casing both names using CharLowerW,
5006 and (c) comparing the results; this would be quite a
5007 bit slower, whereas Plan B is for users who want
5008 lightweight albeit inaccurate version of 'stat'. */
5009 && c_strncasecmp (save_name, dir_pathname, len) == 0
5010 && IS_DIRECTORY_SEP (name[len])
5011 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5013 have_wfd = last_dir_find_data;
5014 /* This was the last entry returned by readdir. */
5015 if (last_dir_find_data == DIR_FIND_DATA_W)
5016 wfd_w = dir_find_data_w;
5017 else
5018 wfd_a = dir_find_data_a;
5020 else
5022 logon_network_drive (name);
5024 if (w32_unicode_filenames)
5026 filename_to_utf16 (name, name_w);
5027 fh = FindFirstFileW (name_w, &wfd_w);
5028 have_wfd = DIR_FIND_DATA_W;
5030 else
5032 filename_to_ansi (name, name_a);
5033 /* If NAME includes characters not representable by
5034 the current ANSI codepage, filename_to_ansi
5035 usually replaces them with a '?'. We don't want
5036 to let FindFirstFileA interpret those as wildcards,
5037 and "succeed", returning us data from some random
5038 file in the same directory. */
5039 if (_mbspbrk (name_a, "?"))
5040 fh = INVALID_HANDLE_VALUE;
5041 else
5042 fh = FindFirstFileA (name_a, &wfd_a);
5043 have_wfd = DIR_FIND_DATA_A;
5045 if (fh == INVALID_HANDLE_VALUE)
5047 errno = ENOENT;
5048 return -1;
5050 FindClose (fh);
5052 /* Note: if NAME is a symlink, the information we get from
5053 FindFirstFile is for the symlink, not its target. */
5054 if (have_wfd == DIR_FIND_DATA_W)
5056 fattrs = wfd_w.dwFileAttributes;
5057 ctime = wfd_w.ftCreationTime;
5058 atime = wfd_w.ftLastAccessTime;
5059 wtime = wfd_w.ftLastWriteTime;
5060 fs_high = wfd_w.nFileSizeHigh;
5061 fs_low = wfd_w.nFileSizeLow;
5063 else
5065 fattrs = wfd_a.dwFileAttributes;
5066 ctime = wfd_a.ftCreationTime;
5067 atime = wfd_a.ftLastAccessTime;
5068 wtime = wfd_a.ftLastWriteTime;
5069 fs_high = wfd_a.nFileSizeHigh;
5070 fs_low = wfd_a.nFileSizeLow;
5072 fake_inode = 0;
5073 nlinks = 1;
5074 serialnum = volume_info.serialnum;
5076 if (is_a_symlink && !follow_symlinks)
5077 buf->st_mode = S_IFLNK;
5078 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5079 buf->st_mode = S_IFDIR;
5080 else
5081 buf->st_mode = S_IFREG;
5083 get_file_owner_and_group (NULL, buf);
5086 buf->st_ino = fake_inode;
5088 buf->st_dev = serialnum;
5089 buf->st_rdev = serialnum;
5091 buf->st_size = fs_high;
5092 buf->st_size <<= 32;
5093 buf->st_size += fs_low;
5094 buf->st_nlink = nlinks;
5096 /* Convert timestamps to Unix format. */
5097 buf->st_mtime = convert_time (wtime);
5098 buf->st_atime = convert_time (atime);
5099 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5100 buf->st_ctime = convert_time (ctime);
5101 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5103 /* determine rwx permissions */
5104 if (is_a_symlink && !follow_symlinks)
5105 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5106 else
5108 if (fattrs & FILE_ATTRIBUTE_READONLY)
5109 permission = S_IREAD;
5110 else
5111 permission = S_IREAD | S_IWRITE;
5113 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5114 permission |= S_IEXEC;
5115 else if (is_exec (name))
5116 permission |= S_IEXEC;
5119 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5121 return 0;
5125 stat (const char * path, struct stat * buf)
5127 return stat_worker (path, buf, 1);
5131 lstat (const char * path, struct stat * buf)
5133 return stat_worker (path, buf, 0);
5137 fstatat (int fd, char const *name, struct stat *st, int flags)
5139 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5140 This is good enough for the current usage in Emacs, but is fragile.
5142 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5143 Gnulib does this and can serve as a model. */
5144 char fullname[MAX_UTF8_PATH];
5146 if (fd != AT_FDCWD)
5148 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5150 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5151 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5152 < 0)
5154 errno = ENAMETOOLONG;
5155 return -1;
5157 name = fullname;
5160 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5163 /* Provide fstat and utime as well as stat for consistent handling of
5164 file timestamps. */
5166 fstat (int desc, struct stat * buf)
5168 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5169 BY_HANDLE_FILE_INFORMATION info;
5170 unsigned __int64 fake_inode;
5171 int permission;
5173 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5175 case FILE_TYPE_DISK:
5176 buf->st_mode = S_IFREG;
5177 if (!GetFileInformationByHandle (fh, &info))
5179 errno = EACCES;
5180 return -1;
5182 break;
5183 case FILE_TYPE_PIPE:
5184 buf->st_mode = S_IFIFO;
5185 goto non_disk;
5186 case FILE_TYPE_CHAR:
5187 case FILE_TYPE_UNKNOWN:
5188 default:
5189 buf->st_mode = S_IFCHR;
5190 non_disk:
5191 memset (&info, 0, sizeof (info));
5192 info.dwFileAttributes = 0;
5193 info.ftCreationTime = utc_base_ft;
5194 info.ftLastAccessTime = utc_base_ft;
5195 info.ftLastWriteTime = utc_base_ft;
5198 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5199 buf->st_mode = S_IFDIR;
5201 buf->st_nlink = info.nNumberOfLinks;
5202 /* Might as well use file index to fake inode values, but this
5203 is not guaranteed to be unique unless we keep a handle open
5204 all the time (even then there are situations where it is
5205 not unique). Reputedly, there are at most 48 bits of info
5206 (on NTFS, presumably less on FAT). */
5207 fake_inode = info.nFileIndexHigh;
5208 fake_inode <<= 32;
5209 fake_inode += info.nFileIndexLow;
5211 /* MSVC defines _ino_t to be short; other libc's might not. */
5212 if (sizeof (buf->st_ino) == 2)
5213 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5214 else
5215 buf->st_ino = fake_inode;
5217 /* If the caller so requested, get the true file owner and group.
5218 Otherwise, consider the file to belong to the current user. */
5219 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5220 get_file_owner_and_group (NULL, buf);
5221 else
5223 PSECURITY_DESCRIPTOR psd = NULL;
5225 psd = get_file_security_desc_by_handle (fh);
5226 if (psd)
5228 get_file_owner_and_group (psd, buf);
5229 LocalFree (psd);
5231 else
5232 get_file_owner_and_group (NULL, buf);
5235 buf->st_dev = info.dwVolumeSerialNumber;
5236 buf->st_rdev = info.dwVolumeSerialNumber;
5238 buf->st_size = info.nFileSizeHigh;
5239 buf->st_size <<= 32;
5240 buf->st_size += info.nFileSizeLow;
5242 /* Convert timestamps to Unix format. */
5243 buf->st_mtime = convert_time (info.ftLastWriteTime);
5244 buf->st_atime = convert_time (info.ftLastAccessTime);
5245 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5246 buf->st_ctime = convert_time (info.ftCreationTime);
5247 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5249 /* determine rwx permissions */
5250 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5251 permission = S_IREAD;
5252 else
5253 permission = S_IREAD | S_IWRITE;
5255 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5256 permission |= S_IEXEC;
5257 else
5259 #if 0 /* no way of knowing the filename */
5260 char * p = strrchr (name, '.');
5261 if (p != NULL &&
5262 (xstrcasecmp (p, ".exe") == 0 ||
5263 xstrcasecmp (p, ".com") == 0 ||
5264 xstrcasecmp (p, ".bat") == 0 ||
5265 xstrcasecmp (p, ".cmd") == 0))
5266 permission |= S_IEXEC;
5267 #endif
5270 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5272 return 0;
5275 /* A version of 'utime' which handles directories as well as
5276 files. */
5279 utime (const char *name, struct utimbuf *times)
5281 struct utimbuf deftime;
5282 HANDLE fh;
5283 FILETIME mtime;
5284 FILETIME atime;
5286 if (times == NULL)
5288 deftime.modtime = deftime.actime = time (NULL);
5289 times = &deftime;
5292 if (w32_unicode_filenames)
5294 wchar_t name_utf16[MAX_PATH];
5296 if (filename_to_utf16 (name, name_utf16) != 0)
5297 return -1; /* errno set by filename_to_utf16 */
5299 /* Need write access to set times. */
5300 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5301 /* If NAME specifies a directory, FILE_SHARE_DELETE
5302 allows other processes to delete files inside it,
5303 while we have the directory open. */
5304 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5305 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5307 else
5309 char name_ansi[MAX_PATH];
5311 if (filename_to_ansi (name, name_ansi) != 0)
5312 return -1; /* errno set by filename_to_ansi */
5314 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5315 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5316 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5318 if (fh != INVALID_HANDLE_VALUE)
5320 convert_from_time_t (times->actime, &atime);
5321 convert_from_time_t (times->modtime, &mtime);
5322 if (!SetFileTime (fh, NULL, &atime, &mtime))
5324 CloseHandle (fh);
5325 errno = EACCES;
5326 return -1;
5328 CloseHandle (fh);
5330 else
5332 DWORD err = GetLastError ();
5334 switch (err)
5336 case ERROR_FILE_NOT_FOUND:
5337 case ERROR_PATH_NOT_FOUND:
5338 case ERROR_INVALID_DRIVE:
5339 case ERROR_BAD_NETPATH:
5340 case ERROR_DEV_NOT_EXIST:
5341 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5342 file name includes ?s, i.e. translation to ANSI failed. */
5343 case ERROR_INVALID_NAME:
5344 errno = ENOENT;
5345 break;
5346 case ERROR_TOO_MANY_OPEN_FILES:
5347 errno = ENFILE;
5348 break;
5349 case ERROR_ACCESS_DENIED:
5350 case ERROR_SHARING_VIOLATION:
5351 errno = EACCES;
5352 break;
5353 default:
5354 errno = EINVAL;
5355 break;
5357 return -1;
5359 return 0;
5363 sys_umask (int mode)
5365 static int current_mask;
5366 int retval, arg = 0;
5368 /* The only bit we really support is the write bit. Files are
5369 always readable on MS-Windows, and the execute bit does not exist
5370 at all. */
5371 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5372 to prevent access by other users on NTFS. */
5373 if ((mode & S_IWRITE) != 0)
5374 arg |= S_IWRITE;
5376 retval = _umask (arg);
5377 /* Merge into the return value the bits they've set the last time,
5378 which msvcrt.dll ignores and never returns. Emacs insists on its
5379 notion of mask being identical to what we return. */
5380 retval |= (current_mask & ~S_IWRITE);
5381 current_mask = mode;
5383 return retval;
5387 /* Symlink-related functions. */
5388 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5389 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5390 #endif
5393 symlink (char const *filename, char const *linkname)
5395 char linkfn[MAX_UTF8_PATH], *tgtfn;
5396 DWORD flags = 0;
5397 int dir_access, filename_ends_in_slash;
5399 /* Diagnostics follows Posix as much as possible. */
5400 if (filename == NULL || linkname == NULL)
5402 errno = EFAULT;
5403 return -1;
5405 if (!*filename)
5407 errno = ENOENT;
5408 return -1;
5410 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5412 errno = ENAMETOOLONG;
5413 return -1;
5416 strcpy (linkfn, map_w32_filename (linkname, NULL));
5417 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5419 errno = EPERM;
5420 return -1;
5423 /* Note: since empty FILENAME was already rejected, we can safely
5424 refer to FILENAME[1]. */
5425 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5427 /* Non-absolute FILENAME is understood as being relative to
5428 LINKNAME's directory. We need to prepend that directory to
5429 FILENAME to get correct results from faccessat below, since
5430 otherwise it will interpret FILENAME relative to the
5431 directory where the Emacs process runs. Note that
5432 make-symbolic-link always makes sure LINKNAME is a fully
5433 expanded file name. */
5434 char tem[MAX_UTF8_PATH];
5435 char *p = linkfn + strlen (linkfn);
5437 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5438 p--;
5439 if (p > linkfn)
5440 strncpy (tem, linkfn, p - linkfn);
5441 tem[p - linkfn] = '\0';
5442 strcat (tem, filename);
5443 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5445 else
5446 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5448 /* Since Windows distinguishes between symlinks to directories and
5449 to files, we provide a kludgy feature: if FILENAME doesn't
5450 exist, but ends in a slash, we create a symlink to directory. If
5451 FILENAME exists and is a directory, we always create a symlink to
5452 directory. */
5453 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5454 if (dir_access == 0 || filename_ends_in_slash)
5455 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5457 tgtfn = (char *)map_w32_filename (filename, NULL);
5458 if (filename_ends_in_slash)
5459 tgtfn[strlen (tgtfn) - 1] = '\0';
5461 errno = 0;
5462 if (!create_symbolic_link (linkfn, tgtfn, flags))
5464 /* ENOSYS is set by create_symbolic_link, when it detects that
5465 the OS doesn't support the CreateSymbolicLink API. */
5466 if (errno != ENOSYS)
5468 DWORD w32err = GetLastError ();
5470 switch (w32err)
5472 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5473 TGTFN point to the same file name, go figure. */
5474 case ERROR_SUCCESS:
5475 case ERROR_FILE_EXISTS:
5476 errno = EEXIST;
5477 break;
5478 case ERROR_ACCESS_DENIED:
5479 errno = EACCES;
5480 break;
5481 case ERROR_FILE_NOT_FOUND:
5482 case ERROR_PATH_NOT_FOUND:
5483 case ERROR_BAD_NETPATH:
5484 case ERROR_INVALID_REPARSE_DATA:
5485 errno = ENOENT;
5486 break;
5487 case ERROR_DIRECTORY:
5488 errno = EISDIR;
5489 break;
5490 case ERROR_PRIVILEGE_NOT_HELD:
5491 case ERROR_NOT_ALL_ASSIGNED:
5492 errno = EPERM;
5493 break;
5494 case ERROR_DISK_FULL:
5495 errno = ENOSPC;
5496 break;
5497 default:
5498 errno = EINVAL;
5499 break;
5502 return -1;
5504 return 0;
5507 /* A quick inexpensive test of whether FILENAME identifies a file that
5508 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5509 must already be in the normalized form returned by
5510 map_w32_filename.
5512 Note: for repeated operations on many files, it is best to test
5513 whether the underlying volume actually supports symlinks, by
5514 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5515 avoid the call to this function if it doesn't. That's because the
5516 call to GetFileAttributes takes a non-negligible time, especially
5517 on non-local or removable filesystems. See stat_worker for an
5518 example of how to do that. */
5519 static int
5520 is_symlink (const char *filename)
5522 DWORD attrs;
5523 wchar_t filename_w[MAX_PATH];
5524 char filename_a[MAX_PATH];
5525 WIN32_FIND_DATAW wfdw;
5526 WIN32_FIND_DATAA wfda;
5527 HANDLE fh;
5528 int attrs_mean_symlink;
5530 if (w32_unicode_filenames)
5532 filename_to_utf16 (filename, filename_w);
5533 attrs = GetFileAttributesW (filename_w);
5535 else
5537 filename_to_ansi (filename, filename_a);
5538 attrs = GetFileAttributesA (filename_a);
5540 if (attrs == -1)
5542 DWORD w32err = GetLastError ();
5544 switch (w32err)
5546 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5547 break;
5548 case ERROR_ACCESS_DENIED:
5549 errno = EACCES;
5550 break;
5551 case ERROR_FILE_NOT_FOUND:
5552 case ERROR_PATH_NOT_FOUND:
5553 default:
5554 errno = ENOENT;
5555 break;
5557 return 0;
5559 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5560 return 0;
5561 logon_network_drive (filename);
5562 if (w32_unicode_filenames)
5564 fh = FindFirstFileW (filename_w, &wfdw);
5565 attrs_mean_symlink =
5566 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5567 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5569 else if (_mbspbrk (filename_a, "?"))
5571 /* filename_to_ansi failed to convert the file name. */
5572 errno = ENOENT;
5573 return 0;
5575 else
5577 fh = FindFirstFileA (filename_a, &wfda);
5578 attrs_mean_symlink =
5579 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5580 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5582 if (fh == INVALID_HANDLE_VALUE)
5583 return 0;
5584 FindClose (fh);
5585 return attrs_mean_symlink;
5588 /* If NAME identifies a symbolic link, copy into BUF the file name of
5589 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5590 null-terminate the target name, even if it fits. Return the number
5591 of bytes copied, or -1 if NAME is not a symlink or any error was
5592 encountered while resolving it. The file name copied into BUF is
5593 encoded in the current ANSI codepage. */
5594 ssize_t
5595 readlink (const char *name, char *buf, size_t buf_size)
5597 const char *path;
5598 TOKEN_PRIVILEGES privs;
5599 int restore_privs = 0;
5600 HANDLE sh;
5601 ssize_t retval;
5602 char resolved[MAX_UTF8_PATH];
5604 if (name == NULL)
5606 errno = EFAULT;
5607 return -1;
5609 if (!*name)
5611 errno = ENOENT;
5612 return -1;
5615 path = map_w32_filename (name, NULL);
5617 if (strlen (path) > MAX_UTF8_PATH)
5619 errno = ENAMETOOLONG;
5620 return -1;
5623 errno = 0;
5624 if (is_windows_9x () == TRUE
5625 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5626 || !is_symlink (path))
5628 if (!errno)
5629 errno = EINVAL; /* not a symlink */
5630 return -1;
5633 /* Done with simple tests, now we're in for some _real_ work. */
5634 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5635 restore_privs = 1;
5636 /* Implementation note: From here and onward, don't return early,
5637 since that will fail to restore the original set of privileges of
5638 the calling thread. */
5640 retval = -1; /* not too optimistic, are we? */
5642 /* Note: In the next call to CreateFile, we use zero as the 2nd
5643 argument because, when the symlink is a hidden/system file,
5644 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5645 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5646 and directory symlinks. */
5647 if (w32_unicode_filenames)
5649 wchar_t path_w[MAX_PATH];
5651 filename_to_utf16 (path, path_w);
5652 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5653 FILE_FLAG_OPEN_REPARSE_POINT
5654 | FILE_FLAG_BACKUP_SEMANTICS,
5655 NULL);
5657 else
5659 char path_a[MAX_PATH];
5661 filename_to_ansi (path, path_a);
5662 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5663 FILE_FLAG_OPEN_REPARSE_POINT
5664 | FILE_FLAG_BACKUP_SEMANTICS,
5665 NULL);
5667 if (sh != INVALID_HANDLE_VALUE)
5669 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5670 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5671 DWORD retbytes;
5673 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5674 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5675 &retbytes, NULL))
5676 errno = EIO;
5677 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5678 errno = EINVAL;
5679 else
5681 /* Copy the link target name, in wide characters, from
5682 reparse_data, then convert it to multibyte encoding in
5683 the current locale's codepage. */
5684 WCHAR *lwname;
5685 size_t lname_size;
5686 USHORT lwname_len =
5687 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5688 WCHAR *lwname_src =
5689 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5690 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5691 size_t size_to_copy = buf_size;
5693 /* According to MSDN, PrintNameLength does not include the
5694 terminating null character. */
5695 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5696 memcpy (lwname, lwname_src, lwname_len);
5697 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5698 filename_from_utf16 (lwname, resolved);
5699 dostounix_filename (resolved);
5700 lname_size = strlen (resolved) + 1;
5701 if (lname_size <= buf_size)
5702 size_to_copy = lname_size;
5703 strncpy (buf, resolved, size_to_copy);
5704 /* Success! */
5705 retval = size_to_copy;
5707 CloseHandle (sh);
5709 else
5711 /* CreateFile failed. */
5712 DWORD w32err2 = GetLastError ();
5714 switch (w32err2)
5716 case ERROR_FILE_NOT_FOUND:
5717 case ERROR_PATH_NOT_FOUND:
5718 errno = ENOENT;
5719 break;
5720 case ERROR_ACCESS_DENIED:
5721 case ERROR_TOO_MANY_OPEN_FILES:
5722 errno = EACCES;
5723 break;
5724 default:
5725 errno = EPERM;
5726 break;
5729 if (restore_privs)
5731 restore_privilege (&privs);
5732 revert_to_self ();
5735 return retval;
5738 ssize_t
5739 readlinkat (int fd, char const *name, char *buffer,
5740 size_t buffer_size)
5742 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5743 as in fstatat. FIXME: Add proper support for readlinkat. */
5744 char fullname[MAX_UTF8_PATH];
5746 if (fd != AT_FDCWD)
5748 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5749 < 0)
5751 errno = ENAMETOOLONG;
5752 return -1;
5754 name = fullname;
5757 return readlink (name, buffer, buffer_size);
5760 /* If FILE is a symlink, return its target (stored in a static
5761 buffer); otherwise return FILE.
5763 This function repeatedly resolves symlinks in the last component of
5764 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5765 until it arrives at a file whose last component is not a symlink,
5766 or some error occurs. It returns the target of the last
5767 successfully resolved symlink in the chain. If it succeeds to
5768 resolve even a single symlink, the value returned is an absolute
5769 file name with backslashes (result of GetFullPathName). By
5770 contrast, if the original FILE is returned, it is unaltered.
5772 Note: This function can set errno even if it succeeds.
5774 Implementation note: we only resolve the last portion ("basename")
5775 of the argument FILE and of each following file in the chain,
5776 disregarding any possible symlinks in its leading directories.
5777 This is because Windows system calls and library functions
5778 transparently resolve symlinks in leading directories and return
5779 correct information, as long as the basename is not a symlink. */
5780 static char *
5781 chase_symlinks (const char *file)
5783 static char target[MAX_UTF8_PATH];
5784 char link[MAX_UTF8_PATH];
5785 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5786 char target_a[MAX_PATH], link_a[MAX_PATH];
5787 ssize_t res, link_len;
5788 int loop_count = 0;
5790 if (is_windows_9x () == TRUE || !is_symlink (file))
5791 return (char *)file;
5793 if (w32_unicode_filenames)
5795 wchar_t file_w[MAX_PATH];
5797 filename_to_utf16 (file, file_w);
5798 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5799 return (char *)file;
5800 filename_from_utf16 (link_w, link);
5802 else
5804 char file_a[MAX_PATH];
5806 filename_to_ansi (file, file_a);
5807 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
5808 return (char *)file;
5809 filename_from_ansi (link_a, link);
5811 link_len = strlen (link);
5813 target[0] = '\0';
5814 do {
5816 /* Remove trailing slashes, as we want to resolve the last
5817 non-trivial part of the link name. */
5818 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5819 link[link_len--] = '\0';
5821 res = readlink (link, target, MAX_UTF8_PATH);
5822 if (res > 0)
5824 target[res] = '\0';
5825 if (!(IS_DEVICE_SEP (target[1])
5826 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5828 /* Target is relative. Append it to the directory part of
5829 the symlink, then copy the result back to target. */
5830 char *p = link + link_len;
5832 while (p > link && !IS_ANY_SEP (p[-1]))
5833 p--;
5834 strcpy (p, target);
5835 strcpy (target, link);
5837 /* Resolve any "." and ".." to get a fully-qualified file name
5838 in link[] again. */
5839 if (w32_unicode_filenames)
5841 filename_to_utf16 (target, target_w);
5842 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
5843 if (link_len > 0)
5844 filename_from_utf16 (link_w, link);
5846 else
5848 filename_to_ansi (target, target_a);
5849 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
5850 if (link_len > 0)
5851 filename_from_ansi (link_a, link);
5853 link_len = strlen (link);
5855 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5857 if (loop_count > 100)
5858 errno = ELOOP;
5860 if (target[0] == '\0') /* not a single call to readlink succeeded */
5861 return (char *)file;
5862 return target;
5866 /* Posix ACL emulation. */
5869 acl_valid (acl_t acl)
5871 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5874 char *
5875 acl_to_text (acl_t acl, ssize_t *size)
5877 LPTSTR str_acl;
5878 SECURITY_INFORMATION flags =
5879 OWNER_SECURITY_INFORMATION |
5880 GROUP_SECURITY_INFORMATION |
5881 DACL_SECURITY_INFORMATION;
5882 char *retval = NULL;
5883 ULONG local_size;
5884 int e = errno;
5886 errno = 0;
5888 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5890 errno = e;
5891 /* We don't want to mix heaps, so we duplicate the string in our
5892 heap and free the one allocated by the API. */
5893 retval = xstrdup (str_acl);
5894 if (size)
5895 *size = local_size;
5896 LocalFree (str_acl);
5898 else if (errno != ENOTSUP)
5899 errno = EINVAL;
5901 return retval;
5904 acl_t
5905 acl_from_text (const char *acl_str)
5907 PSECURITY_DESCRIPTOR psd, retval = NULL;
5908 ULONG sd_size;
5909 int e = errno;
5911 errno = 0;
5913 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5915 errno = e;
5916 retval = xmalloc (sd_size);
5917 memcpy (retval, psd, sd_size);
5918 LocalFree (psd);
5920 else if (errno != ENOTSUP)
5921 errno = EINVAL;
5923 return retval;
5927 acl_free (void *ptr)
5929 xfree (ptr);
5930 return 0;
5933 acl_t
5934 acl_get_file (const char *fname, acl_type_t type)
5936 PSECURITY_DESCRIPTOR psd = NULL;
5937 const char *filename;
5939 if (type == ACL_TYPE_ACCESS)
5941 DWORD sd_len, err;
5942 SECURITY_INFORMATION si =
5943 OWNER_SECURITY_INFORMATION |
5944 GROUP_SECURITY_INFORMATION |
5945 DACL_SECURITY_INFORMATION ;
5946 int e = errno;
5948 filename = map_w32_filename (fname, NULL);
5949 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5950 fname = chase_symlinks (filename);
5951 else
5952 fname = filename;
5954 errno = 0;
5955 if (!get_file_security (fname, si, psd, 0, &sd_len)
5956 && errno != ENOTSUP)
5958 err = GetLastError ();
5959 if (err == ERROR_INSUFFICIENT_BUFFER)
5961 psd = xmalloc (sd_len);
5962 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5964 xfree (psd);
5965 errno = EIO;
5966 psd = NULL;
5969 else if (err == ERROR_FILE_NOT_FOUND
5970 || err == ERROR_PATH_NOT_FOUND
5971 /* ERROR_INVALID_NAME is what we get if
5972 w32-unicode-filenames is nil and the file cannot
5973 be encoded in the current ANSI codepage. */
5974 || err == ERROR_INVALID_NAME)
5975 errno = ENOENT;
5976 else
5977 errno = EIO;
5979 else if (!errno)
5980 errno = e;
5982 else if (type != ACL_TYPE_DEFAULT)
5983 errno = EINVAL;
5985 return psd;
5989 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5991 TOKEN_PRIVILEGES old1, old2;
5992 DWORD err;
5993 int st = 0, retval = -1;
5994 SECURITY_INFORMATION flags = 0;
5995 PSID psidOwner, psidGroup;
5996 PACL pacl;
5997 BOOL dflt;
5998 BOOL dacl_present;
5999 int e;
6000 const char *filename;
6002 if (acl_valid (acl) != 0
6003 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6005 errno = EINVAL;
6006 return -1;
6009 if (type == ACL_TYPE_DEFAULT)
6011 errno = ENOSYS;
6012 return -1;
6015 filename = map_w32_filename (fname, NULL);
6016 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6017 fname = chase_symlinks (filename);
6018 else
6019 fname = filename;
6021 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6022 &dflt)
6023 && psidOwner)
6024 flags |= OWNER_SECURITY_INFORMATION;
6025 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6026 &dflt)
6027 && psidGroup)
6028 flags |= GROUP_SECURITY_INFORMATION;
6029 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6030 &pacl, &dflt)
6031 && dacl_present)
6032 flags |= DACL_SECURITY_INFORMATION;
6033 if (!flags)
6034 return 0;
6036 /* According to KB-245153, setting the owner will succeed if either:
6037 (1) the caller is the user who will be the new owner, and has the
6038 SE_TAKE_OWNERSHIP privilege, or
6039 (2) the caller has the SE_RESTORE privilege, in which case she can
6040 set any valid user or group as the owner
6042 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6043 privileges, and disregard any failures in obtaining them. If
6044 these privileges cannot be obtained, and do not already exist in
6045 the calling thread's security token, this function could fail
6046 with EPERM. */
6047 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6048 st++;
6049 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6050 st++;
6052 e = errno;
6053 errno = 0;
6054 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6055 DACL inheritance is involved, but it seems to preserve ownership
6056 better than SetNamedSecurityInfo, which is important e.g., in
6057 copy-file. */
6058 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6060 err = GetLastError ();
6062 if (errno != ENOTSUP)
6063 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6064 psidOwner, psidGroup, pacl, NULL);
6066 else
6067 err = ERROR_SUCCESS;
6068 if (err != ERROR_SUCCESS)
6070 if (errno == ENOTSUP)
6072 else if (err == ERROR_INVALID_OWNER
6073 || err == ERROR_NOT_ALL_ASSIGNED
6074 || err == ERROR_ACCESS_DENIED)
6076 /* Maybe the requested ACL and the one the file already has
6077 are identical, in which case we can silently ignore the
6078 failure. (And no, Windows doesn't.) */
6079 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6081 errno = EPERM;
6082 if (current_acl)
6084 char *acl_from = acl_to_text (current_acl, NULL);
6085 char *acl_to = acl_to_text (acl, NULL);
6087 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6089 retval = 0;
6090 errno = e;
6092 if (acl_from)
6093 acl_free (acl_from);
6094 if (acl_to)
6095 acl_free (acl_to);
6096 acl_free (current_acl);
6099 else if (err == ERROR_FILE_NOT_FOUND
6100 || err == ERROR_PATH_NOT_FOUND
6101 /* ERROR_INVALID_NAME is what we get if
6102 w32-unicode-filenames is nil and the file cannot be
6103 encoded in the current ANSI codepage. */
6104 || err == ERROR_INVALID_NAME)
6105 errno = ENOENT;
6106 else
6107 errno = EACCES;
6109 else
6111 retval = 0;
6112 errno = e;
6115 if (st)
6117 if (st >= 2)
6118 restore_privilege (&old2);
6119 restore_privilege (&old1);
6120 revert_to_self ();
6123 return retval;
6127 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6128 have a fixed max size for file names, so we don't need the kind of
6129 alloc/malloc/realloc dance the gnulib version does. We also don't
6130 support FD-relative symlinks. */
6131 char *
6132 careadlinkat (int fd, char const *filename,
6133 char *buffer, size_t buffer_size,
6134 struct allocator const *alloc,
6135 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6137 char linkname[MAX_UTF8_PATH];
6138 ssize_t link_size;
6140 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6142 if (link_size > 0)
6144 char *retval = buffer;
6146 linkname[link_size++] = '\0';
6147 if (link_size > buffer_size)
6148 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6149 if (retval)
6150 memcpy (retval, linkname, link_size);
6152 return retval;
6154 return NULL;
6158 w32_copy_file (const char *from, const char *to,
6159 int keep_time, int preserve_ownership, int copy_acls)
6161 acl_t acl = NULL;
6162 BOOL copy_result;
6163 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6164 char from_a[MAX_PATH], to_a[MAX_PATH];
6166 /* We ignore preserve_ownership for now. */
6167 preserve_ownership = preserve_ownership;
6169 if (copy_acls)
6171 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6172 if (acl == NULL && acl_errno_valid (errno))
6173 return -2;
6175 if (w32_unicode_filenames)
6177 filename_to_utf16 (from, from_w);
6178 filename_to_utf16 (to, to_w);
6179 copy_result = CopyFileW (from_w, to_w, FALSE);
6181 else
6183 filename_to_ansi (from, from_a);
6184 filename_to_ansi (to, to_a);
6185 copy_result = CopyFileA (from_a, to_a, FALSE);
6187 if (!copy_result)
6189 /* CopyFile doesn't set errno when it fails. By far the most
6190 "popular" reason is that the target is read-only. */
6191 DWORD err = GetLastError ();
6193 switch (err)
6195 case ERROR_FILE_NOT_FOUND:
6196 errno = ENOENT;
6197 break;
6198 case ERROR_ACCESS_DENIED:
6199 errno = EACCES;
6200 break;
6201 case ERROR_ENCRYPTION_FAILED:
6202 errno = EIO;
6203 break;
6204 default:
6205 errno = EPERM;
6206 break;
6209 if (acl)
6210 acl_free (acl);
6211 return -1;
6213 /* CopyFile retains the timestamp by default. However, see
6214 "Community Additions" for CopyFile: it sounds like that is not
6215 entirely true. Testing on Windows XP confirms that modified time
6216 is copied, but creation and last-access times are not.
6217 FIXME? */
6218 else if (!keep_time)
6220 struct timespec now;
6221 DWORD attributes;
6223 if (w32_unicode_filenames)
6225 /* Ensure file is writable while its times are set. */
6226 attributes = GetFileAttributesW (to_w);
6227 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6228 now = current_timespec ();
6229 if (set_file_times (-1, to, now, now))
6231 /* Restore original attributes. */
6232 SetFileAttributesW (to_w, attributes);
6233 if (acl)
6234 acl_free (acl);
6235 return -3;
6237 /* Restore original attributes. */
6238 SetFileAttributesW (to_w, attributes);
6240 else
6242 attributes = GetFileAttributesA (to_a);
6243 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6244 now = current_timespec ();
6245 if (set_file_times (-1, to, now, now))
6247 SetFileAttributesA (to_a, attributes);
6248 if (acl)
6249 acl_free (acl);
6250 return -3;
6252 SetFileAttributesA (to_a, attributes);
6255 if (acl != NULL)
6257 bool fail =
6258 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6259 acl_free (acl);
6260 if (fail && acl_errno_valid (errno))
6261 return -4;
6264 return 0;
6268 /* Support for browsing other processes and their attributes. See
6269 process.c for the Lisp bindings. */
6271 /* Helper wrapper functions. */
6273 static HANDLE WINAPI
6274 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6276 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6278 if (g_b_init_create_toolhelp32_snapshot == 0)
6280 g_b_init_create_toolhelp32_snapshot = 1;
6281 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6282 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6283 "CreateToolhelp32Snapshot");
6285 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6287 return INVALID_HANDLE_VALUE;
6289 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6292 static BOOL WINAPI
6293 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6295 static Process32First_Proc s_pfn_Process32_First = NULL;
6297 if (g_b_init_process32_first == 0)
6299 g_b_init_process32_first = 1;
6300 s_pfn_Process32_First = (Process32First_Proc)
6301 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6302 "Process32First");
6304 if (s_pfn_Process32_First == NULL)
6306 return FALSE;
6308 return (s_pfn_Process32_First (hSnapshot, lppe));
6311 static BOOL WINAPI
6312 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6314 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6316 if (g_b_init_process32_next == 0)
6318 g_b_init_process32_next = 1;
6319 s_pfn_Process32_Next = (Process32Next_Proc)
6320 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6321 "Process32Next");
6323 if (s_pfn_Process32_Next == NULL)
6325 return FALSE;
6327 return (s_pfn_Process32_Next (hSnapshot, lppe));
6330 static BOOL WINAPI
6331 open_thread_token (HANDLE ThreadHandle,
6332 DWORD DesiredAccess,
6333 BOOL OpenAsSelf,
6334 PHANDLE TokenHandle)
6336 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6337 HMODULE hm_advapi32 = NULL;
6338 if (is_windows_9x () == TRUE)
6340 SetLastError (ERROR_NOT_SUPPORTED);
6341 return FALSE;
6343 if (g_b_init_open_thread_token == 0)
6345 g_b_init_open_thread_token = 1;
6346 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6347 s_pfn_Open_Thread_Token =
6348 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6350 if (s_pfn_Open_Thread_Token == NULL)
6352 SetLastError (ERROR_NOT_SUPPORTED);
6353 return FALSE;
6355 return (
6356 s_pfn_Open_Thread_Token (
6357 ThreadHandle,
6358 DesiredAccess,
6359 OpenAsSelf,
6360 TokenHandle)
6364 static BOOL WINAPI
6365 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6367 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6368 HMODULE hm_advapi32 = NULL;
6369 if (is_windows_9x () == TRUE)
6371 return FALSE;
6373 if (g_b_init_impersonate_self == 0)
6375 g_b_init_impersonate_self = 1;
6376 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6377 s_pfn_Impersonate_Self =
6378 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6380 if (s_pfn_Impersonate_Self == NULL)
6382 return FALSE;
6384 return s_pfn_Impersonate_Self (ImpersonationLevel);
6387 static BOOL WINAPI
6388 revert_to_self (void)
6390 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6391 HMODULE hm_advapi32 = NULL;
6392 if (is_windows_9x () == TRUE)
6394 return FALSE;
6396 if (g_b_init_revert_to_self == 0)
6398 g_b_init_revert_to_self = 1;
6399 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6400 s_pfn_Revert_To_Self =
6401 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6403 if (s_pfn_Revert_To_Self == NULL)
6405 return FALSE;
6407 return s_pfn_Revert_To_Self ();
6410 static BOOL WINAPI
6411 get_process_memory_info (HANDLE h_proc,
6412 PPROCESS_MEMORY_COUNTERS mem_counters,
6413 DWORD bufsize)
6415 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6416 HMODULE hm_psapi = NULL;
6417 if (is_windows_9x () == TRUE)
6419 return FALSE;
6421 if (g_b_init_get_process_memory_info == 0)
6423 g_b_init_get_process_memory_info = 1;
6424 hm_psapi = LoadLibrary ("Psapi.dll");
6425 if (hm_psapi)
6426 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6427 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6429 if (s_pfn_Get_Process_Memory_Info == NULL)
6431 return FALSE;
6433 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6436 static BOOL WINAPI
6437 get_process_working_set_size (HANDLE h_proc,
6438 PSIZE_T minrss,
6439 PSIZE_T maxrss)
6441 static GetProcessWorkingSetSize_Proc
6442 s_pfn_Get_Process_Working_Set_Size = NULL;
6444 if (is_windows_9x () == TRUE)
6446 return FALSE;
6448 if (g_b_init_get_process_working_set_size == 0)
6450 g_b_init_get_process_working_set_size = 1;
6451 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6452 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6453 "GetProcessWorkingSetSize");
6455 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6457 return FALSE;
6459 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6462 static BOOL WINAPI
6463 global_memory_status (MEMORYSTATUS *buf)
6465 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6467 if (is_windows_9x () == TRUE)
6469 return FALSE;
6471 if (g_b_init_global_memory_status == 0)
6473 g_b_init_global_memory_status = 1;
6474 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6475 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6476 "GlobalMemoryStatus");
6478 if (s_pfn_Global_Memory_Status == NULL)
6480 return FALSE;
6482 return s_pfn_Global_Memory_Status (buf);
6485 static BOOL WINAPI
6486 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6488 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6490 if (is_windows_9x () == TRUE)
6492 return FALSE;
6494 if (g_b_init_global_memory_status_ex == 0)
6496 g_b_init_global_memory_status_ex = 1;
6497 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6498 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6499 "GlobalMemoryStatusEx");
6501 if (s_pfn_Global_Memory_Status_Ex == NULL)
6503 return FALSE;
6505 return s_pfn_Global_Memory_Status_Ex (buf);
6508 Lisp_Object
6509 list_system_processes (void)
6511 struct gcpro gcpro1;
6512 Lisp_Object proclist = Qnil;
6513 HANDLE h_snapshot;
6515 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6517 if (h_snapshot != INVALID_HANDLE_VALUE)
6519 PROCESSENTRY32 proc_entry;
6520 DWORD proc_id;
6521 BOOL res;
6523 GCPRO1 (proclist);
6525 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6526 for (res = process32_first (h_snapshot, &proc_entry); res;
6527 res = process32_next (h_snapshot, &proc_entry))
6529 proc_id = proc_entry.th32ProcessID;
6530 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6533 CloseHandle (h_snapshot);
6534 UNGCPRO;
6535 proclist = Fnreverse (proclist);
6538 return proclist;
6541 static int
6542 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6544 TOKEN_PRIVILEGES priv;
6545 DWORD priv_size = sizeof (priv);
6546 DWORD opriv_size = sizeof (*old_priv);
6547 HANDLE h_token = NULL;
6548 HANDLE h_thread = GetCurrentThread ();
6549 int ret_val = 0;
6550 BOOL res;
6552 res = open_thread_token (h_thread,
6553 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6554 FALSE, &h_token);
6555 if (!res && GetLastError () == ERROR_NO_TOKEN)
6557 if (impersonate_self (SecurityImpersonation))
6558 res = open_thread_token (h_thread,
6559 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6560 FALSE, &h_token);
6562 if (res)
6564 priv.PrivilegeCount = 1;
6565 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6566 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6567 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6568 old_priv, &opriv_size)
6569 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6570 ret_val = 1;
6572 if (h_token)
6573 CloseHandle (h_token);
6575 return ret_val;
6578 static int
6579 restore_privilege (TOKEN_PRIVILEGES *priv)
6581 DWORD priv_size = sizeof (*priv);
6582 HANDLE h_token = NULL;
6583 int ret_val = 0;
6585 if (open_thread_token (GetCurrentThread (),
6586 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6587 FALSE, &h_token))
6589 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6590 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6591 ret_val = 1;
6593 if (h_token)
6594 CloseHandle (h_token);
6596 return ret_val;
6599 static Lisp_Object
6600 ltime (ULONGLONG time_100ns)
6602 ULONGLONG time_sec = time_100ns / 10000000;
6603 int subsec = time_100ns % 10000000;
6604 return list4i (time_sec >> 16, time_sec & 0xffff,
6605 subsec / 10, subsec % 10 * 100000);
6608 #define U64_TO_LISP_TIME(time) ltime (time)
6610 static int
6611 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6612 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6613 double *pcpu)
6615 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6616 ULONGLONG tem1, tem2, tem3, tem;
6618 if (!h_proc
6619 || !get_process_times_fn
6620 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6621 &ft_kernel, &ft_user))
6622 return 0;
6624 GetSystemTimeAsFileTime (&ft_current);
6626 FILETIME_TO_U64 (tem1, ft_kernel);
6627 *stime = U64_TO_LISP_TIME (tem1);
6629 FILETIME_TO_U64 (tem2, ft_user);
6630 *utime = U64_TO_LISP_TIME (tem2);
6632 tem3 = tem1 + tem2;
6633 *ttime = U64_TO_LISP_TIME (tem3);
6635 FILETIME_TO_U64 (tem, ft_creation);
6636 /* Process no 4 (System) returns zero creation time. */
6637 if (tem)
6638 tem -= utc_base;
6639 *ctime = U64_TO_LISP_TIME (tem);
6641 if (tem)
6643 FILETIME_TO_U64 (tem3, ft_current);
6644 tem = (tem3 - utc_base) - tem;
6646 *etime = U64_TO_LISP_TIME (tem);
6648 if (tem)
6650 *pcpu = 100.0 * (tem1 + tem2) / tem;
6651 if (*pcpu > 100)
6652 *pcpu = 100.0;
6654 else
6655 *pcpu = 0;
6657 return 1;
6660 Lisp_Object
6661 system_process_attributes (Lisp_Object pid)
6663 struct gcpro gcpro1, gcpro2, gcpro3;
6664 Lisp_Object attrs = Qnil;
6665 Lisp_Object cmd_str, decoded_cmd, tem;
6666 HANDLE h_snapshot, h_proc;
6667 DWORD proc_id;
6668 int found_proc = 0;
6669 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6670 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6671 DWORD glength = sizeof (gname);
6672 HANDLE token = NULL;
6673 SID_NAME_USE user_type;
6674 unsigned char *buf = NULL;
6675 DWORD blen = 0;
6676 TOKEN_USER user_token;
6677 TOKEN_PRIMARY_GROUP group_token;
6678 unsigned euid;
6679 unsigned egid;
6680 PROCESS_MEMORY_COUNTERS mem;
6681 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6682 SIZE_T minrss, maxrss;
6683 MEMORYSTATUS memst;
6684 MEMORY_STATUS_EX memstex;
6685 double totphys = 0.0;
6686 Lisp_Object ctime, stime, utime, etime, ttime;
6687 double pcpu;
6688 BOOL result = FALSE;
6690 CHECK_NUMBER_OR_FLOAT (pid);
6691 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6693 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6695 GCPRO3 (attrs, decoded_cmd, tem);
6697 if (h_snapshot != INVALID_HANDLE_VALUE)
6699 PROCESSENTRY32 pe;
6700 BOOL res;
6702 pe.dwSize = sizeof (PROCESSENTRY32);
6703 for (res = process32_first (h_snapshot, &pe); res;
6704 res = process32_next (h_snapshot, &pe))
6706 if (proc_id == pe.th32ProcessID)
6708 if (proc_id == 0)
6709 decoded_cmd = build_string ("Idle");
6710 else
6712 /* Decode the command name from locale-specific
6713 encoding. */
6714 cmd_str = build_unibyte_string (pe.szExeFile);
6716 decoded_cmd =
6717 code_convert_string_norecord (cmd_str,
6718 Vlocale_coding_system, 0);
6720 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6721 attrs = Fcons (Fcons (Qppid,
6722 make_fixnum_or_float (pe.th32ParentProcessID)),
6723 attrs);
6724 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6725 attrs);
6726 attrs = Fcons (Fcons (Qthcount,
6727 make_fixnum_or_float (pe.cntThreads)),
6728 attrs);
6729 found_proc = 1;
6730 break;
6734 CloseHandle (h_snapshot);
6737 if (!found_proc)
6739 UNGCPRO;
6740 return Qnil;
6743 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6744 FALSE, proc_id);
6745 /* If we were denied a handle to the process, try again after
6746 enabling the SeDebugPrivilege in our process. */
6747 if (!h_proc)
6749 TOKEN_PRIVILEGES priv_current;
6751 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6753 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6754 FALSE, proc_id);
6755 restore_privilege (&priv_current);
6756 revert_to_self ();
6759 if (h_proc)
6761 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6762 if (result)
6764 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6765 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6767 buf = xmalloc (blen);
6768 result = get_token_information (token, TokenUser,
6769 (LPVOID)buf, blen, &needed);
6770 if (result)
6772 memcpy (&user_token, buf, sizeof (user_token));
6773 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6775 euid = get_rid (user_token.User.Sid);
6776 result = lookup_account_sid (NULL, user_token.User.Sid,
6777 uname, &ulength,
6778 domain, &dlength,
6779 &user_type);
6780 if (result)
6781 w32_add_to_cache (user_token.User.Sid, euid, uname);
6782 else
6784 strcpy (uname, "unknown");
6785 result = TRUE;
6788 ulength = strlen (uname);
6792 if (result)
6794 /* Determine a reasonable euid and gid values. */
6795 if (xstrcasecmp ("administrator", uname) == 0)
6797 euid = 500; /* well-known Administrator uid */
6798 egid = 513; /* well-known None gid */
6800 else
6802 /* Get group id and name. */
6803 result = get_token_information (token, TokenPrimaryGroup,
6804 (LPVOID)buf, blen, &needed);
6805 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6807 buf = xrealloc (buf, blen = needed);
6808 result = get_token_information (token, TokenPrimaryGroup,
6809 (LPVOID)buf, blen, &needed);
6811 if (result)
6813 memcpy (&group_token, buf, sizeof (group_token));
6814 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6816 egid = get_rid (group_token.PrimaryGroup);
6817 dlength = sizeof (domain);
6818 result =
6819 lookup_account_sid (NULL, group_token.PrimaryGroup,
6820 gname, &glength, NULL, &dlength,
6821 &user_type);
6822 if (result)
6823 w32_add_to_cache (group_token.PrimaryGroup,
6824 egid, gname);
6825 else
6827 strcpy (gname, "None");
6828 result = TRUE;
6831 glength = strlen (gname);
6835 xfree (buf);
6837 if (!result)
6839 if (!is_windows_9x ())
6841 /* We couldn't open the process token, presumably because of
6842 insufficient access rights. Assume this process is run
6843 by the system. */
6844 strcpy (uname, "SYSTEM");
6845 strcpy (gname, "None");
6846 euid = 18; /* SYSTEM */
6847 egid = 513; /* None */
6848 glength = strlen (gname);
6849 ulength = strlen (uname);
6851 /* If we are running under Windows 9X, where security calls are
6852 not supported, we assume all processes are run by the current
6853 user. */
6854 else if (GetUserName (uname, &ulength))
6856 if (xstrcasecmp ("administrator", uname) == 0)
6857 euid = 0;
6858 else
6859 euid = 123;
6860 egid = euid;
6861 strcpy (gname, "None");
6862 glength = strlen (gname);
6863 ulength = strlen (uname);
6865 else
6867 euid = 123;
6868 egid = 123;
6869 strcpy (uname, "administrator");
6870 ulength = strlen (uname);
6871 strcpy (gname, "None");
6872 glength = strlen (gname);
6874 if (token)
6875 CloseHandle (token);
6878 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
6879 tem = make_unibyte_string (uname, ulength);
6880 attrs = Fcons (Fcons (Quser,
6881 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6882 attrs);
6883 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
6884 tem = make_unibyte_string (gname, glength);
6885 attrs = Fcons (Fcons (Qgroup,
6886 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6887 attrs);
6889 if (global_memory_status_ex (&memstex))
6890 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6891 totphys = memstex.ullTotalPhys / 1024.0;
6892 #else
6893 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6894 double, so we need to do this for it... */
6896 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6897 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6898 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6900 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6902 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6903 else if (global_memory_status (&memst))
6904 totphys = memst.dwTotalPhys / 1024.0;
6906 if (h_proc
6907 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6908 sizeof (mem_ex)))
6910 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6912 attrs = Fcons (Fcons (Qmajflt,
6913 make_fixnum_or_float (mem_ex.PageFaultCount)),
6914 attrs);
6915 attrs = Fcons (Fcons (Qvsize,
6916 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6917 attrs);
6918 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6919 if (totphys)
6920 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6922 else if (h_proc
6923 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6925 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6927 attrs = Fcons (Fcons (Qmajflt,
6928 make_fixnum_or_float (mem.PageFaultCount)),
6929 attrs);
6930 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6931 if (totphys)
6932 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6934 else if (h_proc
6935 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6937 DWORD rss = maxrss / 1024;
6939 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6940 if (totphys)
6941 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6944 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6946 attrs = Fcons (Fcons (Qutime, utime), attrs);
6947 attrs = Fcons (Fcons (Qstime, stime), attrs);
6948 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6949 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6950 attrs = Fcons (Fcons (Qetime, etime), attrs);
6951 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6954 /* FIXME: Retrieve command line by walking the PEB of the process. */
6956 if (h_proc)
6957 CloseHandle (h_proc);
6958 UNGCPRO;
6959 return attrs;
6963 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
6964 unsigned long long *totalswap, unsigned long long *freeswap)
6966 MEMORYSTATUS memst;
6967 MEMORY_STATUS_EX memstex;
6969 /* Use GlobalMemoryStatusEx if available, as it can report more than
6970 2GB of memory. */
6971 if (global_memory_status_ex (&memstex))
6973 *totalram = memstex.ullTotalPhys;
6974 *freeram = memstex.ullAvailPhys;
6975 *totalswap = memstex.ullTotalPageFile;
6976 *freeswap = memstex.ullAvailPageFile;
6977 return 0;
6979 else if (global_memory_status (&memst))
6981 *totalram = memst.dwTotalPhys;
6982 *freeram = memst.dwAvailPhys;
6983 *totalswap = memst.dwTotalPageFile;
6984 *freeswap = memst.dwAvailPageFile;
6985 return 0;
6987 else
6988 return -1;
6992 /* Wrappers for winsock functions to map between our file descriptors
6993 and winsock's handles; also set h_errno for convenience.
6995 To allow Emacs to run on systems which don't have winsock support
6996 installed, we dynamically link to winsock on startup if present, and
6997 otherwise provide the minimum necessary functionality
6998 (eg. gethostname). */
7000 /* function pointers for relevant socket functions */
7001 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7002 void (PASCAL *pfn_WSASetLastError) (int iError);
7003 int (PASCAL *pfn_WSAGetLastError) (void);
7004 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7005 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7006 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7007 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7008 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7009 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7010 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7011 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7012 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7013 int (PASCAL *pfn_closesocket) (SOCKET s);
7014 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7015 int (PASCAL *pfn_WSACleanup) (void);
7017 u_short (PASCAL *pfn_htons) (u_short hostshort);
7018 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7019 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7020 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7021 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7022 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7023 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7024 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7025 const char * optval, int optlen);
7026 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7027 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7028 int * namelen);
7029 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7030 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7031 struct sockaddr * from, int * fromlen);
7032 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7033 const struct sockaddr * to, int tolen);
7035 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7036 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7037 #ifndef HANDLE_FLAG_INHERIT
7038 #define HANDLE_FLAG_INHERIT 1
7039 #endif
7041 HANDLE winsock_lib;
7042 static int winsock_inuse;
7044 BOOL
7045 term_winsock (void)
7047 if (winsock_lib != NULL && winsock_inuse == 0)
7049 release_listen_threads ();
7050 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7051 after WSAStartup returns successfully, but it seems reasonable
7052 to allow unloading winsock anyway in that case. */
7053 if (pfn_WSACleanup () == 0 ||
7054 pfn_WSAGetLastError () == WSAENETDOWN)
7056 if (FreeLibrary (winsock_lib))
7057 winsock_lib = NULL;
7058 return TRUE;
7061 return FALSE;
7064 BOOL
7065 init_winsock (int load_now)
7067 WSADATA winsockData;
7069 if (winsock_lib != NULL)
7070 return TRUE;
7072 pfn_SetHandleInformation
7073 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7074 "SetHandleInformation");
7076 winsock_lib = LoadLibrary ("Ws2_32.dll");
7078 if (winsock_lib != NULL)
7080 /* dynamically link to socket functions */
7082 #define LOAD_PROC(fn) \
7083 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7084 goto fail;
7086 LOAD_PROC (WSAStartup);
7087 LOAD_PROC (WSASetLastError);
7088 LOAD_PROC (WSAGetLastError);
7089 LOAD_PROC (WSAEventSelect);
7090 LOAD_PROC (WSACreateEvent);
7091 LOAD_PROC (WSACloseEvent);
7092 LOAD_PROC (socket);
7093 LOAD_PROC (bind);
7094 LOAD_PROC (connect);
7095 LOAD_PROC (ioctlsocket);
7096 LOAD_PROC (recv);
7097 LOAD_PROC (send);
7098 LOAD_PROC (closesocket);
7099 LOAD_PROC (shutdown);
7100 LOAD_PROC (htons);
7101 LOAD_PROC (ntohs);
7102 LOAD_PROC (inet_addr);
7103 LOAD_PROC (gethostname);
7104 LOAD_PROC (gethostbyname);
7105 LOAD_PROC (getservbyname);
7106 LOAD_PROC (getpeername);
7107 LOAD_PROC (WSACleanup);
7108 LOAD_PROC (setsockopt);
7109 LOAD_PROC (listen);
7110 LOAD_PROC (getsockname);
7111 LOAD_PROC (accept);
7112 LOAD_PROC (recvfrom);
7113 LOAD_PROC (sendto);
7114 #undef LOAD_PROC
7116 /* specify version 1.1 of winsock */
7117 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7119 if (winsockData.wVersion != 0x101)
7120 goto fail;
7122 if (!load_now)
7124 /* Report that winsock exists and is usable, but leave
7125 socket functions disabled. I am assuming that calling
7126 WSAStartup does not require any network interaction,
7127 and in particular does not cause or require a dial-up
7128 connection to be established. */
7130 pfn_WSACleanup ();
7131 FreeLibrary (winsock_lib);
7132 winsock_lib = NULL;
7134 winsock_inuse = 0;
7135 return TRUE;
7138 fail:
7139 FreeLibrary (winsock_lib);
7140 winsock_lib = NULL;
7143 return FALSE;
7147 int h_errno = 0;
7149 /* Function to map winsock error codes to errno codes for those errno
7150 code defined in errno.h (errno values not defined by errno.h are
7151 already in nt/inc/sys/socket.h). */
7152 static void
7153 set_errno (void)
7155 int wsa_err;
7157 h_errno = 0;
7158 if (winsock_lib == NULL)
7159 wsa_err = EINVAL;
7160 else
7161 wsa_err = pfn_WSAGetLastError ();
7163 switch (wsa_err)
7165 case WSAEACCES: errno = EACCES; break;
7166 case WSAEBADF: errno = EBADF; break;
7167 case WSAEFAULT: errno = EFAULT; break;
7168 case WSAEINTR: errno = EINTR; break;
7169 case WSAEINVAL: errno = EINVAL; break;
7170 case WSAEMFILE: errno = EMFILE; break;
7171 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7172 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7173 default: errno = wsa_err; break;
7177 static void
7178 check_errno (void)
7180 h_errno = 0;
7181 if (winsock_lib != NULL)
7182 pfn_WSASetLastError (0);
7185 /* Extend strerror to handle the winsock-specific error codes. */
7186 struct {
7187 int errnum;
7188 char * msg;
7189 } _wsa_errlist[] = {
7190 {WSAEINTR , "Interrupted function call"},
7191 {WSAEBADF , "Bad file descriptor"},
7192 {WSAEACCES , "Permission denied"},
7193 {WSAEFAULT , "Bad address"},
7194 {WSAEINVAL , "Invalid argument"},
7195 {WSAEMFILE , "Too many open files"},
7197 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7198 {WSAEINPROGRESS , "Operation now in progress"},
7199 {WSAEALREADY , "Operation already in progress"},
7200 {WSAENOTSOCK , "Socket operation on non-socket"},
7201 {WSAEDESTADDRREQ , "Destination address required"},
7202 {WSAEMSGSIZE , "Message too long"},
7203 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7204 {WSAENOPROTOOPT , "Bad protocol option"},
7205 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7206 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7207 {WSAEOPNOTSUPP , "Operation not supported"},
7208 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7209 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7210 {WSAEADDRINUSE , "Address already in use"},
7211 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7212 {WSAENETDOWN , "Network is down"},
7213 {WSAENETUNREACH , "Network is unreachable"},
7214 {WSAENETRESET , "Network dropped connection on reset"},
7215 {WSAECONNABORTED , "Software caused connection abort"},
7216 {WSAECONNRESET , "Connection reset by peer"},
7217 {WSAENOBUFS , "No buffer space available"},
7218 {WSAEISCONN , "Socket is already connected"},
7219 {WSAENOTCONN , "Socket is not connected"},
7220 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7221 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7222 {WSAETIMEDOUT , "Connection timed out"},
7223 {WSAECONNREFUSED , "Connection refused"},
7224 {WSAELOOP , "Network loop"}, /* not sure */
7225 {WSAENAMETOOLONG , "Name is too long"},
7226 {WSAEHOSTDOWN , "Host is down"},
7227 {WSAEHOSTUNREACH , "No route to host"},
7228 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7229 {WSAEPROCLIM , "Too many processes"},
7230 {WSAEUSERS , "Too many users"}, /* not sure */
7231 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7232 {WSAESTALE , "Data is stale"}, /* not sure */
7233 {WSAEREMOTE , "Remote error"}, /* not sure */
7235 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7236 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7237 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7238 {WSAEDISCON , "Graceful shutdown in progress"},
7239 #ifdef WSAENOMORE
7240 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7241 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7242 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7243 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7244 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7245 {WSASYSCALLFAILURE , "System call failure"},
7246 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7247 {WSATYPE_NOT_FOUND , "Class type not found"},
7248 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7249 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7250 {WSAEREFUSED , "Operation refused"}, /* not sure */
7251 #endif
7253 {WSAHOST_NOT_FOUND , "Host not found"},
7254 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7255 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7256 {WSANO_DATA , "Valid name, no data record of requested type"},
7258 {-1, NULL}
7261 char *
7262 sys_strerror (int error_no)
7264 int i;
7265 static char unknown_msg[40];
7267 if (error_no >= 0 && error_no < sys_nerr)
7268 return sys_errlist[error_no];
7270 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7271 if (_wsa_errlist[i].errnum == error_no)
7272 return _wsa_errlist[i].msg;
7274 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7275 return unknown_msg;
7278 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7279 but I believe the method of keeping the socket handle separate (and
7280 insuring it is not inheritable) is the correct one. */
7282 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7284 static int socket_to_fd (SOCKET s);
7287 sys_socket (int af, int type, int protocol)
7289 SOCKET s;
7291 if (winsock_lib == NULL)
7293 errno = ENETDOWN;
7294 return INVALID_SOCKET;
7297 check_errno ();
7299 /* call the real socket function */
7300 s = pfn_socket (af, type, protocol);
7302 if (s != INVALID_SOCKET)
7303 return socket_to_fd (s);
7305 set_errno ();
7306 return -1;
7309 /* Convert a SOCKET to a file descriptor. */
7310 static int
7311 socket_to_fd (SOCKET s)
7313 int fd;
7314 child_process * cp;
7316 /* Although under NT 3.5 _open_osfhandle will accept a socket
7317 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7318 that does not work under NT 3.1. However, we can get the same
7319 effect by using a backdoor function to replace an existing
7320 descriptor handle with the one we want. */
7322 /* allocate a file descriptor (with appropriate flags) */
7323 fd = _open ("NUL:", _O_RDWR);
7324 if (fd >= 0)
7326 /* Make a non-inheritable copy of the socket handle. Note
7327 that it is possible that sockets aren't actually kernel
7328 handles, which appears to be the case on Windows 9x when
7329 the MS Proxy winsock client is installed. */
7331 /* Apparently there is a bug in NT 3.51 with some service
7332 packs, which prevents using DuplicateHandle to make a
7333 socket handle non-inheritable (causes WSACleanup to
7334 hang). The work-around is to use SetHandleInformation
7335 instead if it is available and implemented. */
7336 if (pfn_SetHandleInformation)
7338 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7340 else
7342 HANDLE parent = GetCurrentProcess ();
7343 HANDLE new_s = INVALID_HANDLE_VALUE;
7345 if (DuplicateHandle (parent,
7346 (HANDLE) s,
7347 parent,
7348 &new_s,
7350 FALSE,
7351 DUPLICATE_SAME_ACCESS))
7353 /* It is possible that DuplicateHandle succeeds even
7354 though the socket wasn't really a kernel handle,
7355 because a real handle has the same value. So
7356 test whether the new handle really is a socket. */
7357 long nonblocking = 0;
7358 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7360 pfn_closesocket (s);
7361 s = (SOCKET) new_s;
7363 else
7365 CloseHandle (new_s);
7370 eassert (fd < MAXDESC);
7371 fd_info[fd].hnd = (HANDLE) s;
7373 /* set our own internal flags */
7374 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7376 cp = new_child ();
7377 if (cp)
7379 cp->fd = fd;
7380 cp->status = STATUS_READ_ACKNOWLEDGED;
7382 /* attach child_process to fd_info */
7383 if (fd_info[ fd ].cp != NULL)
7385 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7386 emacs_abort ();
7389 fd_info[ fd ].cp = cp;
7391 /* success! */
7392 winsock_inuse++; /* count open sockets */
7393 return fd;
7396 /* clean up */
7397 _close (fd);
7399 else
7400 pfn_closesocket (s);
7401 errno = EMFILE;
7402 return -1;
7406 sys_bind (int s, const struct sockaddr * addr, int namelen)
7408 if (winsock_lib == NULL)
7410 errno = ENOTSOCK;
7411 return SOCKET_ERROR;
7414 check_errno ();
7415 if (fd_info[s].flags & FILE_SOCKET)
7417 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7418 if (rc == SOCKET_ERROR)
7419 set_errno ();
7420 return rc;
7422 errno = ENOTSOCK;
7423 return SOCKET_ERROR;
7427 sys_connect (int s, const struct sockaddr * name, int namelen)
7429 if (winsock_lib == NULL)
7431 errno = ENOTSOCK;
7432 return SOCKET_ERROR;
7435 check_errno ();
7436 if (fd_info[s].flags & FILE_SOCKET)
7438 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7439 if (rc == SOCKET_ERROR)
7440 set_errno ();
7441 return rc;
7443 errno = ENOTSOCK;
7444 return SOCKET_ERROR;
7447 u_short
7448 sys_htons (u_short hostshort)
7450 return (winsock_lib != NULL) ?
7451 pfn_htons (hostshort) : hostshort;
7454 u_short
7455 sys_ntohs (u_short netshort)
7457 return (winsock_lib != NULL) ?
7458 pfn_ntohs (netshort) : netshort;
7461 unsigned long
7462 sys_inet_addr (const char * cp)
7464 return (winsock_lib != NULL) ?
7465 pfn_inet_addr (cp) : INADDR_NONE;
7469 sys_gethostname (char * name, int namelen)
7471 if (winsock_lib != NULL)
7473 int retval;
7475 check_errno ();
7476 retval = pfn_gethostname (name, namelen);
7477 if (retval == SOCKET_ERROR)
7478 set_errno ();
7479 return retval;
7482 if (namelen > MAX_COMPUTERNAME_LENGTH)
7483 return !GetComputerName (name, (DWORD *)&namelen);
7485 errno = EFAULT;
7486 return SOCKET_ERROR;
7489 struct hostent *
7490 sys_gethostbyname (const char * name)
7492 struct hostent * host;
7493 int h_err = h_errno;
7495 if (winsock_lib == NULL)
7497 h_errno = NO_RECOVERY;
7498 errno = ENETDOWN;
7499 return NULL;
7502 check_errno ();
7503 host = pfn_gethostbyname (name);
7504 if (!host)
7506 set_errno ();
7507 h_errno = errno;
7509 else
7510 h_errno = h_err;
7511 return host;
7514 struct servent *
7515 sys_getservbyname (const char * name, const char * proto)
7517 struct servent * serv;
7519 if (winsock_lib == NULL)
7521 errno = ENETDOWN;
7522 return NULL;
7525 check_errno ();
7526 serv = pfn_getservbyname (name, proto);
7527 if (!serv)
7528 set_errno ();
7529 return serv;
7533 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7535 if (winsock_lib == NULL)
7537 errno = ENETDOWN;
7538 return SOCKET_ERROR;
7541 check_errno ();
7542 if (fd_info[s].flags & FILE_SOCKET)
7544 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7545 if (rc == SOCKET_ERROR)
7546 set_errno ();
7547 return rc;
7549 errno = ENOTSOCK;
7550 return SOCKET_ERROR;
7554 sys_shutdown (int s, int how)
7556 if (winsock_lib == NULL)
7558 errno = ENETDOWN;
7559 return SOCKET_ERROR;
7562 check_errno ();
7563 if (fd_info[s].flags & FILE_SOCKET)
7565 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7566 if (rc == SOCKET_ERROR)
7567 set_errno ();
7568 return rc;
7570 errno = ENOTSOCK;
7571 return SOCKET_ERROR;
7575 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7577 if (winsock_lib == NULL)
7579 errno = ENETDOWN;
7580 return SOCKET_ERROR;
7583 check_errno ();
7584 if (fd_info[s].flags & FILE_SOCKET)
7586 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7587 (const char *)optval, optlen);
7588 if (rc == SOCKET_ERROR)
7589 set_errno ();
7590 return rc;
7592 errno = ENOTSOCK;
7593 return SOCKET_ERROR;
7597 sys_listen (int s, int backlog)
7599 if (winsock_lib == NULL)
7601 errno = ENETDOWN;
7602 return SOCKET_ERROR;
7605 check_errno ();
7606 if (fd_info[s].flags & FILE_SOCKET)
7608 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7609 if (rc == SOCKET_ERROR)
7610 set_errno ();
7611 else
7612 fd_info[s].flags |= FILE_LISTEN;
7613 return rc;
7615 errno = ENOTSOCK;
7616 return SOCKET_ERROR;
7620 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7622 if (winsock_lib == NULL)
7624 errno = ENETDOWN;
7625 return SOCKET_ERROR;
7628 check_errno ();
7629 if (fd_info[s].flags & FILE_SOCKET)
7631 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7632 if (rc == SOCKET_ERROR)
7633 set_errno ();
7634 return rc;
7636 errno = ENOTSOCK;
7637 return SOCKET_ERROR;
7641 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7643 if (winsock_lib == NULL)
7645 errno = ENETDOWN;
7646 return -1;
7649 check_errno ();
7650 if (fd_info[s].flags & FILE_LISTEN)
7652 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7653 int fd = -1;
7654 if (t == INVALID_SOCKET)
7655 set_errno ();
7656 else
7657 fd = socket_to_fd (t);
7659 if (fd >= 0)
7661 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7662 ResetEvent (fd_info[s].cp->char_avail);
7664 return fd;
7666 errno = ENOTSOCK;
7667 return -1;
7671 sys_recvfrom (int s, char * buf, int len, int flags,
7672 struct sockaddr * from, int * fromlen)
7674 if (winsock_lib == NULL)
7676 errno = ENETDOWN;
7677 return SOCKET_ERROR;
7680 check_errno ();
7681 if (fd_info[s].flags & FILE_SOCKET)
7683 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7684 if (rc == SOCKET_ERROR)
7685 set_errno ();
7686 return rc;
7688 errno = ENOTSOCK;
7689 return SOCKET_ERROR;
7693 sys_sendto (int s, const char * buf, int len, int flags,
7694 const struct sockaddr * to, int tolen)
7696 if (winsock_lib == NULL)
7698 errno = ENETDOWN;
7699 return SOCKET_ERROR;
7702 check_errno ();
7703 if (fd_info[s].flags & FILE_SOCKET)
7705 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7706 if (rc == SOCKET_ERROR)
7707 set_errno ();
7708 return rc;
7710 errno = ENOTSOCK;
7711 return SOCKET_ERROR;
7714 /* Windows does not have an fcntl function. Provide an implementation
7715 good enough for Emacs. */
7717 fcntl (int s, int cmd, int options)
7719 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7720 invoked in a context where fd1 is closed and all descriptors less
7721 than fd1 are open, so sys_dup is an adequate implementation. */
7722 if (cmd == F_DUPFD_CLOEXEC)
7723 return sys_dup (s);
7725 check_errno ();
7726 if (fd_info[s].flags & FILE_SOCKET)
7728 if (winsock_lib == NULL)
7730 errno = ENETDOWN;
7731 return -1;
7734 if (cmd == F_SETFL && options == O_NONBLOCK)
7736 unsigned long nblock = 1;
7737 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7738 if (rc == SOCKET_ERROR)
7739 set_errno ();
7740 /* Keep track of the fact that we set this to non-blocking. */
7741 fd_info[s].flags |= FILE_NDELAY;
7742 return rc;
7744 else
7746 errno = EINVAL;
7747 return SOCKET_ERROR;
7750 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7751 == (FILE_PIPE | FILE_WRITE))
7753 /* Force our writes to pipes be non-blocking. */
7754 if (cmd == F_SETFL && options == O_NONBLOCK)
7756 HANDLE h = (HANDLE)_get_osfhandle (s);
7757 DWORD pipe_mode = PIPE_NOWAIT;
7759 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7761 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7762 return SOCKET_ERROR;
7764 fd_info[s].flags |= FILE_NDELAY;
7765 return 0;
7767 else
7769 errno = EINVAL;
7770 return SOCKET_ERROR;
7773 errno = ENOTSOCK;
7774 return SOCKET_ERROR;
7778 /* Shadow main io functions: we need to handle pipes and sockets more
7779 intelligently. */
7782 sys_close (int fd)
7784 int rc;
7786 if (fd < 0)
7788 errno = EBADF;
7789 return -1;
7792 if (fd < MAXDESC && fd_info[fd].cp)
7794 child_process * cp = fd_info[fd].cp;
7796 fd_info[fd].cp = NULL;
7798 if (CHILD_ACTIVE (cp))
7800 /* if last descriptor to active child_process then cleanup */
7801 int i;
7802 for (i = 0; i < MAXDESC; i++)
7804 if (i == fd)
7805 continue;
7806 if (fd_info[i].cp == cp)
7807 break;
7809 if (i == MAXDESC)
7811 if (fd_info[fd].flags & FILE_SOCKET)
7813 if (winsock_lib == NULL) emacs_abort ();
7815 pfn_shutdown (SOCK_HANDLE (fd), 2);
7816 rc = pfn_closesocket (SOCK_HANDLE (fd));
7818 winsock_inuse--; /* count open sockets */
7820 /* If the process handle is NULL, it's either a socket
7821 or serial connection, or a subprocess that was
7822 already reaped by reap_subprocess, but whose
7823 resources were not yet freed, because its output was
7824 not fully read yet by the time it was reaped. (This
7825 usually happens with async subprocesses whose output
7826 is being read by Emacs.) Otherwise, this process was
7827 not reaped yet, so we set its FD to a negative value
7828 to make sure sys_select will eventually get to
7829 calling the SIGCHLD handler for it, which will then
7830 invoke waitpid and reap_subprocess. */
7831 if (cp->procinfo.hProcess == NULL)
7832 delete_child (cp);
7833 else
7834 cp->fd = -1;
7839 if (fd >= 0 && fd < MAXDESC)
7840 fd_info[fd].flags = 0;
7842 /* Note that sockets do not need special treatment here (at least on
7843 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7844 closesocket is equivalent to CloseHandle, which is to be expected
7845 because socket handles are fully fledged kernel handles. */
7846 rc = _close (fd);
7848 return rc;
7852 sys_dup (int fd)
7854 int new_fd;
7856 new_fd = _dup (fd);
7857 if (new_fd >= 0 && new_fd < MAXDESC)
7859 /* duplicate our internal info as well */
7860 fd_info[new_fd] = fd_info[fd];
7862 return new_fd;
7866 sys_dup2 (int src, int dst)
7868 int rc;
7870 if (dst < 0 || dst >= MAXDESC)
7872 errno = EBADF;
7873 return -1;
7876 /* make sure we close the destination first if it's a pipe or socket */
7877 if (src != dst && fd_info[dst].flags != 0)
7878 sys_close (dst);
7880 rc = _dup2 (src, dst);
7881 if (rc == 0)
7883 /* duplicate our internal info as well */
7884 fd_info[dst] = fd_info[src];
7886 return rc;
7890 pipe2 (int * phandles, int pipe2_flags)
7892 int rc;
7893 unsigned flags;
7895 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
7897 /* make pipe handles non-inheritable; when we spawn a child, we
7898 replace the relevant handle with an inheritable one. Also put
7899 pipes into binary mode; we will do text mode translation ourselves
7900 if required. */
7901 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
7903 if (rc == 0)
7905 /* Protect against overflow, since Windows can open more handles than
7906 our fd_info array has room for. */
7907 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
7909 _close (phandles[0]);
7910 _close (phandles[1]);
7911 errno = EMFILE;
7912 rc = -1;
7914 else
7916 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
7917 fd_info[phandles[0]].flags = flags;
7919 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
7920 fd_info[phandles[1]].flags = flags;
7924 return rc;
7927 /* Function to do blocking read of one byte, needed to implement
7928 select. It is only allowed on communication ports, sockets, or
7929 pipes. */
7931 _sys_read_ahead (int fd)
7933 child_process * cp;
7934 int rc;
7936 if (fd < 0 || fd >= MAXDESC)
7937 return STATUS_READ_ERROR;
7939 cp = fd_info[fd].cp;
7941 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7942 return STATUS_READ_ERROR;
7944 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
7945 || (fd_info[fd].flags & FILE_READ) == 0)
7947 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
7948 emacs_abort ();
7951 cp->status = STATUS_READ_IN_PROGRESS;
7953 if (fd_info[fd].flags & FILE_PIPE)
7955 rc = _read (fd, &cp->chr, sizeof (char));
7957 /* Give subprocess time to buffer some more output for us before
7958 reporting that input is available; we need this because Windows 95
7959 connects DOS programs to pipes by making the pipe appear to be
7960 the normal console stdout - as a result most DOS programs will
7961 write to stdout without buffering, ie. one character at a
7962 time. Even some W32 programs do this - "dir" in a command
7963 shell on NT is very slow if we don't do this. */
7964 if (rc > 0)
7966 int wait = w32_pipe_read_delay;
7968 if (wait > 0)
7969 Sleep (wait);
7970 else if (wait < 0)
7971 while (++wait <= 0)
7972 /* Yield remainder of our time slice, effectively giving a
7973 temporary priority boost to the child process. */
7974 Sleep (0);
7977 else if (fd_info[fd].flags & FILE_SERIAL)
7979 HANDLE hnd = fd_info[fd].hnd;
7980 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7981 COMMTIMEOUTS ct;
7983 /* Configure timeouts for blocking read. */
7984 if (!GetCommTimeouts (hnd, &ct))
7986 cp->status = STATUS_READ_ERROR;
7987 return STATUS_READ_ERROR;
7989 ct.ReadIntervalTimeout = 0;
7990 ct.ReadTotalTimeoutMultiplier = 0;
7991 ct.ReadTotalTimeoutConstant = 0;
7992 if (!SetCommTimeouts (hnd, &ct))
7994 cp->status = STATUS_READ_ERROR;
7995 return STATUS_READ_ERROR;
7998 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8000 if (GetLastError () != ERROR_IO_PENDING)
8002 cp->status = STATUS_READ_ERROR;
8003 return STATUS_READ_ERROR;
8005 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8007 cp->status = STATUS_READ_ERROR;
8008 return STATUS_READ_ERROR;
8012 else if (fd_info[fd].flags & FILE_SOCKET)
8014 unsigned long nblock = 0;
8015 /* We always want this to block, so temporarily disable NDELAY. */
8016 if (fd_info[fd].flags & FILE_NDELAY)
8017 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8019 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8021 if (fd_info[fd].flags & FILE_NDELAY)
8023 nblock = 1;
8024 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8028 if (rc == sizeof (char))
8029 cp->status = STATUS_READ_SUCCEEDED;
8030 else
8031 cp->status = STATUS_READ_FAILED;
8033 return cp->status;
8037 _sys_wait_accept (int fd)
8039 HANDLE hEv;
8040 child_process * cp;
8041 int rc;
8043 if (fd < 0 || fd >= MAXDESC)
8044 return STATUS_READ_ERROR;
8046 cp = fd_info[fd].cp;
8048 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8049 return STATUS_READ_ERROR;
8051 cp->status = STATUS_READ_FAILED;
8053 hEv = pfn_WSACreateEvent ();
8054 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8055 if (rc != SOCKET_ERROR)
8057 do {
8058 rc = WaitForSingleObject (hEv, 500);
8059 Sleep (5);
8060 } while (rc == WAIT_TIMEOUT
8061 && cp->status != STATUS_READ_ERROR
8062 && cp->char_avail);
8063 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8064 if (rc == WAIT_OBJECT_0)
8065 cp->status = STATUS_READ_SUCCEEDED;
8067 pfn_WSACloseEvent (hEv);
8069 return cp->status;
8073 sys_read (int fd, char * buffer, unsigned int count)
8075 int nchars;
8076 int to_read;
8077 DWORD waiting;
8078 char * orig_buffer = buffer;
8080 if (fd < 0)
8082 errno = EBADF;
8083 return -1;
8086 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8088 child_process *cp = fd_info[fd].cp;
8090 if ((fd_info[fd].flags & FILE_READ) == 0)
8092 errno = EBADF;
8093 return -1;
8096 nchars = 0;
8098 /* re-read CR carried over from last read */
8099 if (fd_info[fd].flags & FILE_LAST_CR)
8101 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8102 *buffer++ = 0x0d;
8103 count--;
8104 nchars++;
8105 fd_info[fd].flags &= ~FILE_LAST_CR;
8108 /* presence of a child_process structure means we are operating in
8109 non-blocking mode - otherwise we just call _read directly.
8110 Note that the child_process structure might be missing because
8111 reap_subprocess has been called; in this case the pipe is
8112 already broken, so calling _read on it is okay. */
8113 if (cp)
8115 int current_status = cp->status;
8117 switch (current_status)
8119 case STATUS_READ_FAILED:
8120 case STATUS_READ_ERROR:
8121 /* report normal EOF if nothing in buffer */
8122 if (nchars <= 0)
8123 fd_info[fd].flags |= FILE_AT_EOF;
8124 return nchars;
8126 case STATUS_READ_READY:
8127 case STATUS_READ_IN_PROGRESS:
8128 DebPrint (("sys_read called when read is in progress\n"));
8129 errno = EWOULDBLOCK;
8130 return -1;
8132 case STATUS_READ_SUCCEEDED:
8133 /* consume read-ahead char */
8134 *buffer++ = cp->chr;
8135 count--;
8136 nchars++;
8137 cp->status = STATUS_READ_ACKNOWLEDGED;
8138 ResetEvent (cp->char_avail);
8140 case STATUS_READ_ACKNOWLEDGED:
8141 break;
8143 default:
8144 DebPrint (("sys_read: bad status %d\n", current_status));
8145 errno = EBADF;
8146 return -1;
8149 if (fd_info[fd].flags & FILE_PIPE)
8151 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8152 to_read = min (waiting, (DWORD) count);
8154 if (to_read > 0)
8155 nchars += _read (fd, buffer, to_read);
8157 else if (fd_info[fd].flags & FILE_SERIAL)
8159 HANDLE hnd = fd_info[fd].hnd;
8160 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8161 int rc = 0;
8162 COMMTIMEOUTS ct;
8164 if (count > 0)
8166 /* Configure timeouts for non-blocking read. */
8167 if (!GetCommTimeouts (hnd, &ct))
8169 errno = EIO;
8170 return -1;
8172 ct.ReadIntervalTimeout = MAXDWORD;
8173 ct.ReadTotalTimeoutMultiplier = 0;
8174 ct.ReadTotalTimeoutConstant = 0;
8175 if (!SetCommTimeouts (hnd, &ct))
8177 errno = EIO;
8178 return -1;
8181 if (!ResetEvent (ovl->hEvent))
8183 errno = EIO;
8184 return -1;
8186 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8188 if (GetLastError () != ERROR_IO_PENDING)
8190 errno = EIO;
8191 return -1;
8193 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8195 errno = EIO;
8196 return -1;
8199 nchars += rc;
8202 else /* FILE_SOCKET */
8204 if (winsock_lib == NULL) emacs_abort ();
8206 /* do the equivalent of a non-blocking read */
8207 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8208 if (waiting == 0 && nchars == 0)
8210 errno = EWOULDBLOCK;
8211 return -1;
8214 if (waiting)
8216 /* always use binary mode for sockets */
8217 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8218 if (res == SOCKET_ERROR)
8220 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8221 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8222 set_errno ();
8223 return -1;
8225 nchars += res;
8229 else
8231 int nread = _read (fd, buffer, count);
8232 if (nread >= 0)
8233 nchars += nread;
8234 else if (nchars == 0)
8235 nchars = nread;
8238 if (nchars <= 0)
8239 fd_info[fd].flags |= FILE_AT_EOF;
8240 /* Perform text mode translation if required. */
8241 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8243 nchars = crlf_to_lf (nchars, orig_buffer);
8244 /* If buffer contains only CR, return that. To be absolutely
8245 sure we should attempt to read the next char, but in
8246 practice a CR to be followed by LF would not appear by
8247 itself in the buffer. */
8248 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8250 fd_info[fd].flags |= FILE_LAST_CR;
8251 nchars--;
8255 else
8256 nchars = _read (fd, buffer, count);
8258 return nchars;
8261 /* From w32xfns.c */
8262 extern HANDLE interrupt_handle;
8265 sys_write (int fd, const void * buffer, unsigned int count)
8267 int nchars;
8268 USE_SAFE_ALLOCA;
8270 if (fd < 0)
8272 errno = EBADF;
8273 return -1;
8276 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8278 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8280 errno = EBADF;
8281 return -1;
8284 /* Perform text mode translation if required. */
8285 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8287 char * tmpbuf;
8288 const unsigned char * src = buffer;
8289 unsigned char * dst;
8290 int nbytes = count;
8292 SAFE_NALLOCA (tmpbuf, 2, count);
8293 dst = tmpbuf;
8295 while (1)
8297 unsigned char *next;
8298 /* Copy next line or remaining bytes. */
8299 next = _memccpy (dst, src, '\n', nbytes);
8300 if (next)
8302 /* Copied one line ending with '\n'. */
8303 int copied = next - dst;
8304 nbytes -= copied;
8305 src += copied;
8306 /* Insert '\r' before '\n'. */
8307 next[-1] = '\r';
8308 next[0] = '\n';
8309 dst = next + 1;
8310 count++;
8312 else
8313 /* Copied remaining partial line -> now finished. */
8314 break;
8316 buffer = tmpbuf;
8320 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8322 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8323 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8324 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8325 DWORD active = 0;
8327 /* This is async (a.k.a. "overlapped") I/O, so the return value
8328 of FALSE from WriteFile means either an error or the output
8329 will be completed asynchronously (ERROR_IO_PENDING). */
8330 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8332 if (GetLastError () != ERROR_IO_PENDING)
8334 errno = EIO;
8335 nchars = -1;
8337 else
8339 /* Wait for the write to complete, and watch C-g while
8340 at that. */
8341 if (detect_input_pending ())
8342 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8343 INFINITE, QS_ALLINPUT);
8344 else
8345 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8346 switch (active)
8348 case WAIT_OBJECT_0:
8349 /* User pressed C-g, cancel write, then leave.
8350 Don't bother cleaning up as we may only get stuck
8351 in buggy drivers. */
8352 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8353 CancelIo (hnd);
8354 errno = EIO; /* Why not EINTR? */
8355 nchars = -1;
8356 break;
8357 case WAIT_OBJECT_0 + 1:
8358 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8360 errno = EIO;
8361 nchars = -1;
8363 break;
8368 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8370 unsigned long nblock = 0;
8371 if (winsock_lib == NULL) emacs_abort ();
8373 /* TODO: implement select() properly so non-blocking I/O works. */
8374 /* For now, make sure the write blocks. */
8375 if (fd_info[fd].flags & FILE_NDELAY)
8376 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8378 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8380 /* Set the socket back to non-blocking if it was before,
8381 for other operations that support it. */
8382 if (fd_info[fd].flags & FILE_NDELAY)
8384 nblock = 1;
8385 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8388 if (nchars == SOCKET_ERROR)
8390 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8391 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8392 set_errno ();
8395 else
8397 /* Some networked filesystems don't like too large writes, so
8398 break them into smaller chunks. See the Comments section of
8399 the MSDN documentation of WriteFile for details behind the
8400 choice of the value of CHUNK below. See also the thread
8401 http://thread.gmane.org/gmane.comp.version-control.git/145294
8402 in the git mailing list. */
8403 const unsigned char *p = buffer;
8404 const unsigned chunk = 30 * 1024 * 1024;
8406 nchars = 0;
8407 while (count > 0)
8409 unsigned this_chunk = count < chunk ? count : chunk;
8410 int n = _write (fd, p, this_chunk);
8412 nchars += n;
8413 if (n < 0)
8415 /* When there's no buffer space in a pipe that is in the
8416 non-blocking mode, _write returns ENOSPC. We return
8417 EAGAIN instead, which should trigger the logic in
8418 send_process that enters waiting loop and calls
8419 wait_reading_process_output to allow process input to
8420 be accepted during the wait. Those calls to
8421 wait_reading_process_output allow sys_select to
8422 notice when process input becomes available, thus
8423 avoiding deadlock whereby each side of the pipe is
8424 blocked on write, waiting for the other party to read
8425 its end of the pipe. */
8426 if (errno == ENOSPC
8427 && fd < MAXDESC
8428 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8429 == (FILE_PIPE | FILE_NDELAY)))
8430 errno = EAGAIN;
8431 nchars = n;
8432 break;
8434 else if (n < this_chunk)
8435 break;
8436 count -= n;
8437 p += n;
8441 SAFE_FREE ();
8442 return nchars;
8446 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8448 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8450 /* Return information about network interface IFNAME, or about all
8451 interfaces (if IFNAME is nil). */
8452 static Lisp_Object
8453 network_interface_get_info (Lisp_Object ifname)
8455 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8456 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8457 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8458 Lisp_Object res = Qnil;
8460 if (retval == ERROR_BUFFER_OVERFLOW)
8462 ainfo = xrealloc (ainfo, ainfo_len);
8463 retval = get_adapters_info (ainfo, &ainfo_len);
8466 if (retval == ERROR_SUCCESS)
8468 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8469 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8470 int if_num;
8471 struct sockaddr_in sa;
8473 /* For the below, we need some winsock functions, so make sure
8474 the winsock DLL is loaded. If we cannot successfully load
8475 it, they will have no use of the information we provide,
8476 anyway, so punt. */
8477 if (!winsock_lib && !init_winsock (1))
8478 goto done;
8480 for (adapter = ainfo; adapter; adapter = adapter->Next)
8482 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8483 u_long ip_addr;
8484 /* Present Unix-compatible interface names, instead of the
8485 Windows names, which are really GUIDs not readable by
8486 humans. */
8487 static const char *ifmt[] = {
8488 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8489 "lo", "ifx%d"
8491 enum {
8492 NONE = -1,
8493 ETHERNET = 0,
8494 TOKENRING = 1,
8495 FDDI = 2,
8496 PPP = 3,
8497 SLIP = 4,
8498 WLAN = 5,
8499 LOOPBACK = 6,
8500 OTHER_IF = 7
8501 } ifmt_idx;
8503 switch (adapter->Type)
8505 case MIB_IF_TYPE_ETHERNET:
8506 /* Windows before Vista reports wireless adapters as
8507 Ethernet. Work around by looking at the Description
8508 string. */
8509 if (strstr (adapter->Description, "Wireless "))
8511 ifmt_idx = WLAN;
8512 if_num = wlan_count++;
8514 else
8516 ifmt_idx = ETHERNET;
8517 if_num = eth_count++;
8519 break;
8520 case MIB_IF_TYPE_TOKENRING:
8521 ifmt_idx = TOKENRING;
8522 if_num = tr_count++;
8523 break;
8524 case MIB_IF_TYPE_FDDI:
8525 ifmt_idx = FDDI;
8526 if_num = fddi_count++;
8527 break;
8528 case MIB_IF_TYPE_PPP:
8529 ifmt_idx = PPP;
8530 if_num = ppp_count++;
8531 break;
8532 case MIB_IF_TYPE_SLIP:
8533 ifmt_idx = SLIP;
8534 if_num = sl_count++;
8535 break;
8536 case IF_TYPE_IEEE80211:
8537 ifmt_idx = WLAN;
8538 if_num = wlan_count++;
8539 break;
8540 case MIB_IF_TYPE_LOOPBACK:
8541 if (lo_count < 0)
8543 ifmt_idx = LOOPBACK;
8544 if_num = lo_count++;
8546 else
8547 ifmt_idx = NONE;
8548 break;
8549 default:
8550 ifmt_idx = OTHER_IF;
8551 if_num = ifx_count++;
8552 break;
8554 if (ifmt_idx == NONE)
8555 continue;
8556 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8558 sa.sin_family = AF_INET;
8559 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8560 if (ip_addr == INADDR_NONE)
8562 /* Bogus address, skip this interface. */
8563 continue;
8565 sa.sin_addr.s_addr = ip_addr;
8566 sa.sin_port = 0;
8567 if (NILP (ifname))
8568 res = Fcons (Fcons (build_string (namebuf),
8569 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8570 sizeof (struct sockaddr))),
8571 res);
8572 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8574 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8575 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8576 Lisp_Object flags = Qnil;
8577 int n;
8578 u_long net_mask;
8580 /* Flags. We guess most of them by type, since the
8581 Windows flags are different and hard to get by. */
8582 flags = Fcons (intern ("up"), flags);
8583 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8585 flags = Fcons (intern ("broadcast"), flags);
8586 flags = Fcons (intern ("multicast"), flags);
8588 flags = Fcons (intern ("running"), flags);
8589 if (ifmt_idx == PPP)
8591 flags = Fcons (intern ("pointopoint"), flags);
8592 flags = Fcons (intern ("noarp"), flags);
8594 if (adapter->HaveWins)
8595 flags = Fcons (intern ("WINS"), flags);
8596 if (adapter->DhcpEnabled)
8597 flags = Fcons (intern ("dynamic"), flags);
8599 res = Fcons (flags, res);
8601 /* Hardware address and its family. */
8602 for (n = 0; n < adapter->AddressLength; n++)
8603 p->contents[n] = make_number ((int) adapter->Address[n]);
8604 /* Windows does not support AF_LINK or AF_PACKET family
8605 of addresses. Use an arbitrary family number that is
8606 identical to what GNU/Linux returns. */
8607 res = Fcons (Fcons (make_number (1), hwaddr), res);
8609 /* Network mask. */
8610 sa.sin_family = AF_INET;
8611 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8612 if (net_mask != INADDR_NONE)
8614 sa.sin_addr.s_addr = net_mask;
8615 sa.sin_port = 0;
8616 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8617 sizeof (struct sockaddr)),
8618 res);
8620 else
8621 res = Fcons (Qnil, res);
8623 sa.sin_family = AF_INET;
8624 if (ip_addr != INADDR_NONE)
8626 /* Broadcast address is only reported by
8627 GetAdaptersAddresses, which is of limited
8628 availability. Generate it on our own. */
8629 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8631 sa.sin_addr.s_addr = bcast_addr;
8632 sa.sin_port = 0;
8633 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8634 sizeof (struct sockaddr)),
8635 res);
8637 /* IP address. */
8638 sa.sin_addr.s_addr = ip_addr;
8639 sa.sin_port = 0;
8640 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8641 sizeof (struct sockaddr)),
8642 res);
8644 else
8645 res = Fcons (Qnil, Fcons (Qnil, res));
8648 /* GetAdaptersInfo is documented to not report loopback
8649 interfaces, so we generate one out of thin air. */
8650 if (!lo_count)
8652 sa.sin_family = AF_INET;
8653 sa.sin_port = 0;
8654 if (NILP (ifname))
8656 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8657 res = Fcons (Fcons (build_string ("lo"),
8658 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8659 sizeof (struct sockaddr))),
8660 res);
8662 else if (strcmp (SSDATA (ifname), "lo") == 0)
8664 res = Fcons (Fcons (intern ("running"),
8665 Fcons (intern ("loopback"),
8666 Fcons (intern ("up"), Qnil))), Qnil);
8667 /* 772 is what 3 different GNU/Linux systems report for
8668 the loopback interface. */
8669 res = Fcons (Fcons (make_number (772),
8670 Fmake_vector (make_number (6),
8671 make_number (0))),
8672 res);
8673 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8674 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8675 sizeof (struct sockaddr)),
8676 res);
8677 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8678 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8679 sizeof (struct sockaddr)),
8680 res);
8681 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8682 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8683 sizeof (struct sockaddr)),
8684 res);
8690 done:
8691 xfree (ainfo);
8692 return res;
8695 Lisp_Object
8696 network_interface_list (void)
8698 return network_interface_get_info (Qnil);
8701 Lisp_Object
8702 network_interface_info (Lisp_Object ifname)
8704 CHECK_STRING (ifname);
8705 return network_interface_get_info (ifname);
8709 /* The Windows CRT functions are "optimized for speed", so they don't
8710 check for timezone and DST changes if they were last called less
8711 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8712 all Emacs features that repeatedly call time functions (e.g.,
8713 display-time) are in real danger of missing timezone and DST
8714 changes. Calling tzset before each localtime call fixes that. */
8715 struct tm *
8716 sys_localtime (const time_t *t)
8718 tzset ();
8719 return localtime (t);
8724 /* Try loading LIBRARY_ID from the file(s) specified in
8725 Vdynamic_library_alist. If the library is loaded successfully,
8726 return the handle of the DLL, and record the filename in the
8727 property :loaded-from of LIBRARY_ID. If the library could not be
8728 found, or when it was already loaded (because the handle is not
8729 recorded anywhere, and so is lost after use), return NULL.
8731 We could also save the handle in :loaded-from, but currently
8732 there's no use case for it. */
8733 HMODULE
8734 w32_delayed_load (Lisp_Object library_id)
8736 HMODULE dll_handle = NULL;
8738 CHECK_SYMBOL (library_id);
8740 if (CONSP (Vdynamic_library_alist)
8741 && NILP (Fassq (library_id, Vlibrary_cache)))
8743 Lisp_Object found = Qnil;
8744 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
8746 if (CONSP (dlls))
8747 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
8749 Lisp_Object dll = XCAR (dlls);
8750 char name[MAX_UTF8_PATH];
8751 DWORD res = -1;
8753 CHECK_STRING (dll);
8754 dll = ENCODE_FILE (dll);
8755 if (w32_unicode_filenames)
8757 wchar_t name_w[MAX_PATH];
8759 filename_to_utf16 (SSDATA (dll), name_w);
8760 dll_handle = LoadLibraryW (name_w);
8761 if (dll_handle)
8763 res = GetModuleFileNameW (dll_handle, name_w,
8764 sizeof (name_w));
8765 if (res > 0)
8766 filename_from_utf16 (name_w, name);
8769 else
8771 char name_a[MAX_PATH];
8773 filename_to_ansi (SSDATA (dll), name_a);
8774 dll_handle = LoadLibraryA (name_a);
8775 if (dll_handle)
8777 res = GetModuleFileNameA (dll_handle, name_a,
8778 sizeof (name_a));
8779 if (res > 0)
8780 filename_from_ansi (name_a, name);
8783 if (dll_handle)
8785 ptrdiff_t len = strlen (name);
8786 found = Fcons (dll,
8787 (res > 0)
8788 /* Possibly truncated */
8789 ? make_specified_string (name, -1, len, 1)
8790 : Qnil);
8791 /* This prevents thread start and end notifications
8792 from being sent to the DLL, for every thread we
8793 start. We don't need those notifications because
8794 threads we create never use any of these DLLs, only
8795 the main thread uses them. This is supposed to
8796 speed up thread creation. */
8797 DisableThreadLibraryCalls (dll_handle);
8798 break;
8802 Fput (library_id, QCloaded_from, found);
8805 return dll_handle;
8809 void
8810 check_windows_init_file (void)
8812 /* A common indication that Emacs is not installed properly is when
8813 it cannot find the Windows installation file. If this file does
8814 not exist in the expected place, tell the user. */
8816 if (!noninteractive && !inhibit_window_system
8817 /* Vload_path is not yet initialized when we are loading
8818 loadup.el. */
8819 && NILP (Vpurify_flag))
8821 Lisp_Object init_file;
8822 int fd;
8824 /* Implementation note: this function runs early during Emacs
8825 startup, before startup.el is run. So Vload_path is still in
8826 its initial unibyte form, but it holds UTF-8 encoded file
8827 names, since init_callproc was already called. So we do not
8828 need to ENCODE_FILE here, but we do need to convert the file
8829 names from UTF-8 to ANSI. */
8830 init_file = build_string ("term/w32-win");
8831 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
8832 if (fd < 0)
8834 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
8835 char *init_file_name = SDATA (init_file);
8836 char *load_path = SDATA (load_path_print);
8837 char *buffer = alloca (1024
8838 + strlen (init_file_name)
8839 + strlen (load_path));
8840 char *msg = buffer;
8841 int needed;
8843 sprintf (buffer,
8844 "The Emacs Windows initialization file \"%s.el\" "
8845 "could not be found in your Emacs installation. "
8846 "Emacs checked the following directories for this file:\n"
8847 "\n%s\n\n"
8848 "When Emacs cannot find this file, it usually means that it "
8849 "was not installed properly, or its distribution file was "
8850 "not unpacked properly.\nSee the README.W32 file in the "
8851 "top-level Emacs directory for more information.",
8852 init_file_name, load_path);
8853 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer,
8854 -1, NULL, 0);
8855 if (needed > 0)
8857 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
8859 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer, -1,
8860 msg_w, needed);
8861 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
8862 NULL, 0, NULL, NULL);
8863 if (needed > 0)
8865 char *msg_a = alloca (needed + 1);
8867 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
8868 NULL, NULL);
8869 msg = msg_a;
8872 MessageBox (NULL,
8873 msg,
8874 "Emacs Abort Dialog",
8875 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
8876 /* Use the low-level system abort. */
8877 abort ();
8879 else
8881 _close (fd);
8886 void
8887 term_ntproc (int ignored)
8889 (void)ignored;
8891 term_timers ();
8893 /* shutdown the socket interface if necessary */
8894 term_winsock ();
8896 term_w32select ();
8899 void
8900 init_ntproc (int dumping)
8902 sigset_t initial_mask = 0;
8904 /* Initialize the socket interface now if available and requested by
8905 the user by defining PRELOAD_WINSOCK; otherwise loading will be
8906 delayed until open-network-stream is called (w32-has-winsock can
8907 also be used to dynamically load or reload winsock).
8909 Conveniently, init_environment is called before us, so
8910 PRELOAD_WINSOCK can be set in the registry. */
8912 /* Always initialize this correctly. */
8913 winsock_lib = NULL;
8915 if (getenv ("PRELOAD_WINSOCK") != NULL)
8916 init_winsock (TRUE);
8918 /* Initial preparation for subprocess support: replace our standard
8919 handles with non-inheritable versions. */
8921 HANDLE parent;
8922 HANDLE stdin_save = INVALID_HANDLE_VALUE;
8923 HANDLE stdout_save = INVALID_HANDLE_VALUE;
8924 HANDLE stderr_save = INVALID_HANDLE_VALUE;
8926 parent = GetCurrentProcess ();
8928 /* ignore errors when duplicating and closing; typically the
8929 handles will be invalid when running as a gui program. */
8930 DuplicateHandle (parent,
8931 GetStdHandle (STD_INPUT_HANDLE),
8932 parent,
8933 &stdin_save,
8935 FALSE,
8936 DUPLICATE_SAME_ACCESS);
8938 DuplicateHandle (parent,
8939 GetStdHandle (STD_OUTPUT_HANDLE),
8940 parent,
8941 &stdout_save,
8943 FALSE,
8944 DUPLICATE_SAME_ACCESS);
8946 DuplicateHandle (parent,
8947 GetStdHandle (STD_ERROR_HANDLE),
8948 parent,
8949 &stderr_save,
8951 FALSE,
8952 DUPLICATE_SAME_ACCESS);
8954 fclose (stdin);
8955 fclose (stdout);
8956 fclose (stderr);
8958 if (stdin_save != INVALID_HANDLE_VALUE)
8959 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
8960 else
8961 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
8962 _fdopen (0, "r");
8964 if (stdout_save != INVALID_HANDLE_VALUE)
8965 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
8966 else
8967 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8968 _fdopen (1, "w");
8970 if (stderr_save != INVALID_HANDLE_VALUE)
8971 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
8972 else
8973 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8974 _fdopen (2, "w");
8977 /* unfortunately, atexit depends on implementation of malloc */
8978 /* atexit (term_ntproc); */
8979 if (!dumping)
8981 /* Make sure we start with all signals unblocked. */
8982 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
8983 signal (SIGABRT, term_ntproc);
8985 init_timers ();
8987 /* determine which drives are fixed, for GetCachedVolumeInformation */
8989 /* GetDriveType must have trailing backslash. */
8990 char drive[] = "A:\\";
8992 /* Loop over all possible drive letters */
8993 while (*drive <= 'Z')
8995 /* Record if this drive letter refers to a fixed drive. */
8996 fixed_drives[DRIVE_INDEX (*drive)] =
8997 (GetDriveType (drive) == DRIVE_FIXED);
8999 (*drive)++;
9002 /* Reset the volume info cache. */
9003 volume_cache = NULL;
9008 shutdown_handler ensures that buffers' autosave files are
9009 up to date when the user logs off, or the system shuts down.
9011 static BOOL WINAPI
9012 shutdown_handler (DWORD type)
9014 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9015 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9016 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9017 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9019 /* Shut down cleanly, making sure autosave files are up to date. */
9020 shut_down_emacs (0, Qnil);
9023 /* Allow other handlers to handle this signal. */
9024 return FALSE;
9027 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9028 NT, return a handle to GDI32.DLL. */
9029 HANDLE
9030 maybe_load_unicows_dll (void)
9032 if (os_subtype == OS_9X)
9034 HANDLE ret = LoadLibrary ("Unicows.dll");
9035 if (ret)
9037 /* These two functions are present on Windows 9X as stubs
9038 that always fail. We need the real implementations from
9039 UNICOWS.DLL, so we must call these functions through
9040 pointers, and assign the correct addresses to these
9041 pointers at program startup (see emacs.c, which calls
9042 this function early on). */
9043 pMultiByteToWideChar = GetProcAddress (ret, "MultiByteToWideChar");
9044 pWideCharToMultiByte = GetProcAddress (ret, "WideCharToMultiByte");
9045 return ret;
9047 else
9049 int button;
9051 button = MessageBox (NULL,
9052 "Emacs cannot load the UNICOWS.DLL library.\n"
9053 "This library is essential for using Emacs\n"
9054 "on this system. You need to install it.\n\n"
9055 "Emacs will exit when you click OK.",
9056 "Emacs cannot load UNICOWS.DLL",
9057 MB_ICONERROR | MB_TASKMODAL
9058 | MB_SETFOREGROUND | MB_OK);
9059 switch (button)
9061 case IDOK:
9062 default:
9063 exit (1);
9067 else
9069 /* On NT family of Windows, these two functions are always
9070 linked in, so we just assign their addresses to the 2
9071 pointers; no need for the LoadLibrary dance. */
9072 pMultiByteToWideChar = MultiByteToWideChar;
9073 pWideCharToMultiByte = WideCharToMultiByte;
9074 return LoadLibrary ("Gdi32.dll");
9079 globals_of_w32 is used to initialize those global variables that
9080 must always be initialized on startup even when the global variable
9081 initialized is non zero (see the function main in emacs.c).
9083 void
9084 globals_of_w32 (void)
9086 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9088 get_process_times_fn = (GetProcessTimes_Proc)
9089 GetProcAddress (kernel32, "GetProcessTimes");
9091 DEFSYM (QCloaded_from, ":loaded-from");
9093 g_b_init_is_windows_9x = 0;
9094 g_b_init_open_process_token = 0;
9095 g_b_init_get_token_information = 0;
9096 g_b_init_lookup_account_sid = 0;
9097 g_b_init_get_sid_sub_authority = 0;
9098 g_b_init_get_sid_sub_authority_count = 0;
9099 g_b_init_get_security_info = 0;
9100 g_b_init_get_file_security_w = 0;
9101 g_b_init_get_file_security_a = 0;
9102 g_b_init_get_security_descriptor_owner = 0;
9103 g_b_init_get_security_descriptor_group = 0;
9104 g_b_init_is_valid_sid = 0;
9105 g_b_init_create_toolhelp32_snapshot = 0;
9106 g_b_init_process32_first = 0;
9107 g_b_init_process32_next = 0;
9108 g_b_init_open_thread_token = 0;
9109 g_b_init_impersonate_self = 0;
9110 g_b_init_revert_to_self = 0;
9111 g_b_init_get_process_memory_info = 0;
9112 g_b_init_get_process_working_set_size = 0;
9113 g_b_init_global_memory_status = 0;
9114 g_b_init_global_memory_status_ex = 0;
9115 g_b_init_equal_sid = 0;
9116 g_b_init_copy_sid = 0;
9117 g_b_init_get_length_sid = 0;
9118 g_b_init_get_native_system_info = 0;
9119 g_b_init_get_system_times = 0;
9120 g_b_init_create_symbolic_link_w = 0;
9121 g_b_init_create_symbolic_link_a = 0;
9122 g_b_init_get_security_descriptor_dacl = 0;
9123 g_b_init_convert_sd_to_sddl = 0;
9124 g_b_init_convert_sddl_to_sd = 0;
9125 g_b_init_is_valid_security_descriptor = 0;
9126 g_b_init_set_file_security_w = 0;
9127 g_b_init_set_file_security_a = 0;
9128 g_b_init_set_named_security_info_w = 0;
9129 g_b_init_set_named_security_info_a = 0;
9130 g_b_init_get_adapters_info = 0;
9131 g_b_init_compare_string_w = 0;
9132 num_of_processors = 0;
9133 /* The following sets a handler for shutdown notifications for
9134 console apps. This actually applies to Emacs in both console and
9135 GUI modes, since we had to fool windows into thinking emacs is a
9136 console application to get console mode to work. */
9137 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9139 /* "None" is the default group name on standalone workstations. */
9140 strcpy (dflt_group_name, "None");
9142 /* Reset, in case it has some value inherited from dump time. */
9143 w32_stat_get_owner_group = 0;
9145 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9146 (a.k.a. "wide") APIs to invoke functions that accept file
9147 names. */
9148 if (is_windows_9x ())
9149 w32_unicode_filenames = 0;
9150 else
9151 w32_unicode_filenames = 1;
9154 /* For make-serial-process */
9156 serial_open (Lisp_Object port_obj)
9158 char *port = SSDATA (port_obj);
9159 HANDLE hnd;
9160 child_process *cp;
9161 int fd = -1;
9163 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9164 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9165 if (hnd == INVALID_HANDLE_VALUE)
9166 error ("Could not open %s", port);
9167 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9168 if (fd == -1)
9169 error ("Could not open %s", port);
9171 cp = new_child ();
9172 if (!cp)
9173 error ("Could not create child process");
9174 cp->fd = fd;
9175 cp->status = STATUS_READ_ACKNOWLEDGED;
9176 fd_info[ fd ].hnd = hnd;
9177 fd_info[ fd ].flags |=
9178 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9179 if (fd_info[ fd ].cp != NULL)
9181 error ("fd_info[fd = %d] is already in use", fd);
9183 fd_info[ fd ].cp = cp;
9184 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9185 if (cp->ovl_read.hEvent == NULL)
9186 error ("Could not create read event");
9187 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9188 if (cp->ovl_write.hEvent == NULL)
9189 error ("Could not create write event");
9191 return fd;
9194 /* For serial-process-configure */
9195 void
9196 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9198 Lisp_Object childp2 = Qnil;
9199 Lisp_Object tem = Qnil;
9200 HANDLE hnd;
9201 DCB dcb;
9202 COMMTIMEOUTS ct;
9203 char summary[4] = "???"; /* This usually becomes "8N1". */
9205 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9206 error ("Not a serial process");
9207 hnd = fd_info[ p->outfd ].hnd;
9209 childp2 = Fcopy_sequence (p->childp);
9211 /* Initialize timeouts for blocking read and blocking write. */
9212 if (!GetCommTimeouts (hnd, &ct))
9213 error ("GetCommTimeouts() failed");
9214 ct.ReadIntervalTimeout = 0;
9215 ct.ReadTotalTimeoutMultiplier = 0;
9216 ct.ReadTotalTimeoutConstant = 0;
9217 ct.WriteTotalTimeoutMultiplier = 0;
9218 ct.WriteTotalTimeoutConstant = 0;
9219 if (!SetCommTimeouts (hnd, &ct))
9220 error ("SetCommTimeouts() failed");
9221 /* Read port attributes and prepare default configuration. */
9222 memset (&dcb, 0, sizeof (dcb));
9223 dcb.DCBlength = sizeof (DCB);
9224 if (!GetCommState (hnd, &dcb))
9225 error ("GetCommState() failed");
9226 dcb.fBinary = TRUE;
9227 dcb.fNull = FALSE;
9228 dcb.fAbortOnError = FALSE;
9229 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9230 dcb.ErrorChar = 0;
9231 dcb.EofChar = 0;
9232 dcb.EvtChar = 0;
9234 /* Configure speed. */
9235 if (!NILP (Fplist_member (contact, QCspeed)))
9236 tem = Fplist_get (contact, QCspeed);
9237 else
9238 tem = Fplist_get (p->childp, QCspeed);
9239 CHECK_NUMBER (tem);
9240 dcb.BaudRate = XINT (tem);
9241 childp2 = Fplist_put (childp2, QCspeed, tem);
9243 /* Configure bytesize. */
9244 if (!NILP (Fplist_member (contact, QCbytesize)))
9245 tem = Fplist_get (contact, QCbytesize);
9246 else
9247 tem = Fplist_get (p->childp, QCbytesize);
9248 if (NILP (tem))
9249 tem = make_number (8);
9250 CHECK_NUMBER (tem);
9251 if (XINT (tem) != 7 && XINT (tem) != 8)
9252 error (":bytesize must be nil (8), 7, or 8");
9253 dcb.ByteSize = XINT (tem);
9254 summary[0] = XINT (tem) + '0';
9255 childp2 = Fplist_put (childp2, QCbytesize, tem);
9257 /* Configure parity. */
9258 if (!NILP (Fplist_member (contact, QCparity)))
9259 tem = Fplist_get (contact, QCparity);
9260 else
9261 tem = Fplist_get (p->childp, QCparity);
9262 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9263 error (":parity must be nil (no parity), `even', or `odd'");
9264 dcb.fParity = FALSE;
9265 dcb.Parity = NOPARITY;
9266 dcb.fErrorChar = FALSE;
9267 if (NILP (tem))
9269 summary[1] = 'N';
9271 else if (EQ (tem, Qeven))
9273 summary[1] = 'E';
9274 dcb.fParity = TRUE;
9275 dcb.Parity = EVENPARITY;
9276 dcb.fErrorChar = TRUE;
9278 else if (EQ (tem, Qodd))
9280 summary[1] = 'O';
9281 dcb.fParity = TRUE;
9282 dcb.Parity = ODDPARITY;
9283 dcb.fErrorChar = TRUE;
9285 childp2 = Fplist_put (childp2, QCparity, tem);
9287 /* Configure stopbits. */
9288 if (!NILP (Fplist_member (contact, QCstopbits)))
9289 tem = Fplist_get (contact, QCstopbits);
9290 else
9291 tem = Fplist_get (p->childp, QCstopbits);
9292 if (NILP (tem))
9293 tem = make_number (1);
9294 CHECK_NUMBER (tem);
9295 if (XINT (tem) != 1 && XINT (tem) != 2)
9296 error (":stopbits must be nil (1 stopbit), 1, or 2");
9297 summary[2] = XINT (tem) + '0';
9298 if (XINT (tem) == 1)
9299 dcb.StopBits = ONESTOPBIT;
9300 else if (XINT (tem) == 2)
9301 dcb.StopBits = TWOSTOPBITS;
9302 childp2 = Fplist_put (childp2, QCstopbits, tem);
9304 /* Configure flowcontrol. */
9305 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9306 tem = Fplist_get (contact, QCflowcontrol);
9307 else
9308 tem = Fplist_get (p->childp, QCflowcontrol);
9309 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9310 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9311 dcb.fOutxCtsFlow = FALSE;
9312 dcb.fOutxDsrFlow = FALSE;
9313 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9314 dcb.fDsrSensitivity = FALSE;
9315 dcb.fTXContinueOnXoff = FALSE;
9316 dcb.fOutX = FALSE;
9317 dcb.fInX = FALSE;
9318 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9319 dcb.XonChar = 17; /* Control-Q */
9320 dcb.XoffChar = 19; /* Control-S */
9321 if (NILP (tem))
9323 /* Already configured. */
9325 else if (EQ (tem, Qhw))
9327 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9328 dcb.fOutxCtsFlow = TRUE;
9330 else if (EQ (tem, Qsw))
9332 dcb.fOutX = TRUE;
9333 dcb.fInX = TRUE;
9335 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9337 /* Activate configuration. */
9338 if (!SetCommState (hnd, &dcb))
9339 error ("SetCommState() failed");
9341 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9342 pset_childp (p, childp2);
9345 #ifdef HAVE_GNUTLS
9347 ssize_t
9348 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9350 int n, err;
9351 struct Lisp_Process *process = (struct Lisp_Process *)p;
9352 int fd = process->infd;
9354 n = sys_read (fd, (char*)buf, sz);
9356 if (n >= 0)
9357 return n;
9359 err = errno;
9361 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9362 if (err == EWOULDBLOCK)
9363 err = EAGAIN;
9365 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9367 return -1;
9370 ssize_t
9371 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9373 struct Lisp_Process *process = (struct Lisp_Process *)p;
9374 int fd = process->outfd;
9375 ssize_t n = sys_write (fd, buf, sz);
9377 /* 0 or more bytes written means everything went fine. */
9378 if (n >= 0)
9379 return n;
9381 /* Negative bytes written means we got an error in errno.
9382 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9383 emacs_gnutls_transport_set_errno (process->gnutls_state,
9384 errno == EWOULDBLOCK ? EAGAIN : errno);
9386 return -1;
9388 #endif /* HAVE_GNUTLS */
9390 /* end of w32.c */