Make CC Mode load cl-lib rather than cl in Emacs 26.
[emacs.git] / src / w32.c
blobfa3cbe183fb035abe8ef8e25c7c7c5464ac4df13
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2017 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 (at
10 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 #define DEFER_MS_W32_H
25 #include <config.h>
27 #include <mingw_time.h>
28 #include <stddef.h> /* for offsetof */
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <float.h> /* for DBL_EPSILON */
32 #include <io.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <sys/file.h>
38 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
39 #include <sys/time.h>
40 #include <sys/utime.h>
41 #include <math.h>
43 /* Include (most) CRT headers *before* ms-w32.h. */
44 #include <ms-w32.h>
46 #include <string.h> /* for strerror, needed by sys_strerror */
47 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
49 #undef access
50 #undef chdir
51 #undef chmod
52 #undef creat
53 #undef ctime
54 #undef fopen
55 #undef link
56 #undef mkdir
57 #undef open
58 #undef rename
59 #undef rmdir
60 #undef unlink
62 #undef close
63 #undef dup
64 #undef dup2
65 #undef pipe
66 #undef read
67 #undef write
69 #undef strerror
71 #undef localtime
73 char *sys_ctime (const time_t *);
74 int sys_chdir (const char *);
75 int sys_creat (const char *, int);
76 FILE *sys_fopen (const char *, const char *);
77 int sys_mkdir (const char *);
78 int sys_open (const char *, int, int);
79 int sys_rename (char const *, char const *);
80 int sys_rmdir (const char *);
81 int sys_close (int);
82 int sys_dup2 (int, int);
83 int sys_read (int, char *, unsigned int);
84 int sys_write (int, const void *, unsigned int);
85 struct tm *sys_localtime (const time_t *);
87 #ifdef HAVE_MODULES
88 extern void dynlib_reset_last_error (void);
89 #endif
91 #include "lisp.h"
92 #include "epaths.h" /* for PATH_EXEC */
94 #include <pwd.h>
95 #include <grp.h>
97 #include <windows.h>
98 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
99 use a different name to avoid compilation problems. */
100 typedef struct _MEMORY_STATUS_EX {
101 DWORD dwLength;
102 DWORD dwMemoryLoad;
103 DWORDLONG ullTotalPhys;
104 DWORDLONG ullAvailPhys;
105 DWORDLONG ullTotalPageFile;
106 DWORDLONG ullAvailPageFile;
107 DWORDLONG ullTotalVirtual;
108 DWORDLONG ullAvailVirtual;
109 DWORDLONG ullAvailExtendedVirtual;
110 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
112 /* These are here so that GDB would know about these data types. This
113 allows attaching GDB to Emacs when a fatal exception is triggered
114 and Windows pops up the "application needs to be closed" dialog.
115 At that point, _gnu_exception_handler, the top-level exception
116 handler installed by the MinGW startup code, is somewhere on the
117 call-stack of the main thread, so going to that call frame and
118 looking at the argument to _gnu_exception_handler, which is a
119 PEXCEPTION_POINTERS pointer, can reveal the exception code
120 (excptr->ExceptionRecord->ExceptionCode) and the address where the
121 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
122 well as some additional information specific to the exception. */
123 PEXCEPTION_POINTERS excptr;
124 PEXCEPTION_RECORD excprec;
125 PCONTEXT ctxrec;
127 #include <lmcons.h>
128 #include <shlobj.h>
130 #include <tlhelp32.h>
131 #include <psapi.h>
132 #ifndef _MSC_VER
133 #include <w32api.h>
134 #endif
135 #if _WIN32_WINNT < 0x0500
136 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
137 /* This either is not in psapi.h or guarded by higher value of
138 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
139 defines it in psapi.h */
140 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
141 DWORD cb;
142 DWORD PageFaultCount;
143 SIZE_T PeakWorkingSetSize;
144 SIZE_T WorkingSetSize;
145 SIZE_T QuotaPeakPagedPoolUsage;
146 SIZE_T QuotaPagedPoolUsage;
147 SIZE_T QuotaPeakNonPagedPoolUsage;
148 SIZE_T QuotaNonPagedPoolUsage;
149 SIZE_T PagefileUsage;
150 SIZE_T PeakPagefileUsage;
151 SIZE_T PrivateUsage;
152 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
153 #endif
154 #endif
156 #include <winioctl.h>
157 #include <aclapi.h>
158 #include <sddl.h>
160 #include <sys/acl.h>
161 #include <acl.h>
163 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
164 define them by hand if not already defined. */
165 #ifndef SDDL_REVISION_1
166 #define SDDL_REVISION_1 1
167 #endif /* SDDL_REVISION_1 */
169 #if defined(_MSC_VER) || defined(MINGW_W64)
170 /* MSVC and MinGW64 don't provide the definition of
171 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
172 which cannot be included because it triggers conflicts with other
173 Windows API headers. So we define it here by hand. */
175 typedef struct _REPARSE_DATA_BUFFER {
176 ULONG ReparseTag;
177 USHORT ReparseDataLength;
178 USHORT Reserved;
179 union {
180 struct {
181 USHORT SubstituteNameOffset;
182 USHORT SubstituteNameLength;
183 USHORT PrintNameOffset;
184 USHORT PrintNameLength;
185 ULONG Flags;
186 WCHAR PathBuffer[1];
187 } SymbolicLinkReparseBuffer;
188 struct {
189 USHORT SubstituteNameOffset;
190 USHORT SubstituteNameLength;
191 USHORT PrintNameOffset;
192 USHORT PrintNameLength;
193 WCHAR PathBuffer[1];
194 } MountPointReparseBuffer;
195 struct {
196 UCHAR DataBuffer[1];
197 } GenericReparseBuffer;
198 } DUMMYUNIONNAME;
199 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
201 #ifndef FILE_DEVICE_FILE_SYSTEM
202 #define FILE_DEVICE_FILE_SYSTEM 9
203 #endif
204 #ifndef METHOD_BUFFERED
205 #define METHOD_BUFFERED 0
206 #endif
207 #ifndef FILE_ANY_ACCESS
208 #define FILE_ANY_ACCESS 0x00000000
209 #endif
210 #ifndef CTL_CODE
211 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
212 #endif
213 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
214 #ifndef FSCTL_GET_REPARSE_POINT
215 #define FSCTL_GET_REPARSE_POINT \
216 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
217 #endif
218 #endif
220 /* TCP connection support. */
221 #include <sys/socket.h>
222 #undef socket
223 #undef bind
224 #undef connect
225 #undef htons
226 #undef ntohs
227 #undef inet_addr
228 #undef gethostname
229 #undef gethostbyname
230 #undef getservbyname
231 #undef getpeername
232 #undef shutdown
233 #undef setsockopt
234 #undef listen
235 #undef getsockname
236 #undef accept
237 #undef recvfrom
238 #undef sendto
240 #include <iphlpapi.h> /* should be after winsock2.h */
242 #include <wincrypt.h>
244 #include <c-strcase.h>
245 #include <utimens.h> /* for fdutimens */
247 #include "w32.h"
248 #include <dirent.h>
249 #include "w32common.h"
250 #include "w32select.h"
251 #include "systime.h" /* for current_timespec, struct timespec */
252 #include "dispextern.h" /* for xstrcasecmp */
253 #include "coding.h" /* for Vlocale_coding_system */
255 #include "careadlinkat.h"
256 #include "allocator.h"
258 /* For Lisp_Process, serial_configure and serial_open. */
259 #include "process.h"
260 #include "systty.h"
262 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
263 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
265 static DWORD get_rid (PSID);
266 static int is_symlink (const char *);
267 static char * chase_symlinks (const char *);
268 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
269 static int restore_privilege (TOKEN_PRIVILEGES *);
270 static BOOL WINAPI revert_to_self (void);
272 static int sys_access (const char *, int);
273 extern void *e_malloc (size_t);
274 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
275 const struct timespec *, const sigset_t *);
276 extern int sys_dup (int);
279 /* Initialization states.
281 WARNING: If you add any more such variables for additional APIs,
282 you MUST add initialization for them to globals_of_w32
283 below. This is because these variables might get set
284 to non-NULL values during dumping, but the dumped Emacs
285 cannot reuse those values, because it could be run on a
286 different version of the OS, where API addresses are
287 different. */
288 static BOOL g_b_init_is_windows_9x;
289 static BOOL g_b_init_open_process_token;
290 static BOOL g_b_init_get_token_information;
291 static BOOL g_b_init_lookup_account_sid;
292 static BOOL g_b_init_get_sid_sub_authority;
293 static BOOL g_b_init_get_sid_sub_authority_count;
294 static BOOL g_b_init_get_security_info;
295 static BOOL g_b_init_get_file_security_w;
296 static BOOL g_b_init_get_file_security_a;
297 static BOOL g_b_init_get_security_descriptor_owner;
298 static BOOL g_b_init_get_security_descriptor_group;
299 static BOOL g_b_init_is_valid_sid;
300 static BOOL g_b_init_create_toolhelp32_snapshot;
301 static BOOL g_b_init_process32_first;
302 static BOOL g_b_init_process32_next;
303 static BOOL g_b_init_open_thread_token;
304 static BOOL g_b_init_impersonate_self;
305 static BOOL g_b_init_revert_to_self;
306 static BOOL g_b_init_get_process_memory_info;
307 static BOOL g_b_init_get_process_working_set_size;
308 static BOOL g_b_init_global_memory_status;
309 static BOOL g_b_init_global_memory_status_ex;
310 static BOOL g_b_init_get_length_sid;
311 static BOOL g_b_init_equal_sid;
312 static BOOL g_b_init_copy_sid;
313 static BOOL g_b_init_get_native_system_info;
314 static BOOL g_b_init_get_system_times;
315 static BOOL g_b_init_create_symbolic_link_w;
316 static BOOL g_b_init_create_symbolic_link_a;
317 static BOOL g_b_init_get_security_descriptor_dacl;
318 static BOOL g_b_init_convert_sd_to_sddl;
319 static BOOL g_b_init_convert_sddl_to_sd;
320 static BOOL g_b_init_is_valid_security_descriptor;
321 static BOOL g_b_init_set_file_security_w;
322 static BOOL g_b_init_set_file_security_a;
323 static BOOL g_b_init_set_named_security_info_w;
324 static BOOL g_b_init_set_named_security_info_a;
325 static BOOL g_b_init_get_adapters_info;
327 BOOL g_b_init_compare_string_w;
328 BOOL g_b_init_debug_break_process;
331 BEGIN: Wrapper functions around OpenProcessToken
332 and other functions in advapi32.dll that are only
333 supported in Windows NT / 2k / XP
335 /* ** Function pointer typedefs ** */
336 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
337 HANDLE ProcessHandle,
338 DWORD DesiredAccess,
339 PHANDLE TokenHandle);
340 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
341 HANDLE TokenHandle,
342 TOKEN_INFORMATION_CLASS TokenInformationClass,
343 LPVOID TokenInformation,
344 DWORD TokenInformationLength,
345 PDWORD ReturnLength);
346 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
347 HANDLE process_handle,
348 LPFILETIME creation_time,
349 LPFILETIME exit_time,
350 LPFILETIME kernel_time,
351 LPFILETIME user_time);
353 GetProcessTimes_Proc get_process_times_fn = NULL;
355 #ifdef _UNICODE
356 const char * const LookupAccountSid_Name = "LookupAccountSidW";
357 #else
358 const char * const LookupAccountSid_Name = "LookupAccountSidA";
359 #endif
360 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
361 LPCTSTR lpSystemName,
362 PSID Sid,
363 LPTSTR Name,
364 LPDWORD cbName,
365 LPTSTR DomainName,
366 LPDWORD cbDomainName,
367 PSID_NAME_USE peUse);
368 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
369 PSID pSid,
370 DWORD n);
371 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
372 PSID pSid);
373 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
374 HANDLE handle,
375 SE_OBJECT_TYPE ObjectType,
376 SECURITY_INFORMATION SecurityInfo,
377 PSID *ppsidOwner,
378 PSID *ppsidGroup,
379 PACL *ppDacl,
380 PACL *ppSacl,
381 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
382 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
383 LPCWSTR lpFileName,
384 SECURITY_INFORMATION RequestedInformation,
385 PSECURITY_DESCRIPTOR pSecurityDescriptor,
386 DWORD nLength,
387 LPDWORD lpnLengthNeeded);
388 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
389 LPCSTR lpFileName,
390 SECURITY_INFORMATION RequestedInformation,
391 PSECURITY_DESCRIPTOR pSecurityDescriptor,
392 DWORD nLength,
393 LPDWORD lpnLengthNeeded);
394 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
395 LPCWSTR lpFileName,
396 SECURITY_INFORMATION SecurityInformation,
397 PSECURITY_DESCRIPTOR pSecurityDescriptor);
398 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
399 LPCSTR lpFileName,
400 SECURITY_INFORMATION SecurityInformation,
401 PSECURITY_DESCRIPTOR pSecurityDescriptor);
402 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
403 LPCWSTR lpObjectName,
404 SE_OBJECT_TYPE ObjectType,
405 SECURITY_INFORMATION SecurityInformation,
406 PSID psidOwner,
407 PSID psidGroup,
408 PACL pDacl,
409 PACL pSacl);
410 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
411 LPCSTR lpObjectName,
412 SE_OBJECT_TYPE ObjectType,
413 SECURITY_INFORMATION SecurityInformation,
414 PSID psidOwner,
415 PSID psidGroup,
416 PACL pDacl,
417 PACL pSacl);
418 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
419 PSECURITY_DESCRIPTOR pSecurityDescriptor,
420 PSID *pOwner,
421 LPBOOL lpbOwnerDefaulted);
422 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
423 PSECURITY_DESCRIPTOR pSecurityDescriptor,
424 PSID *pGroup,
425 LPBOOL lpbGroupDefaulted);
426 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
427 PSECURITY_DESCRIPTOR pSecurityDescriptor,
428 LPBOOL lpbDaclPresent,
429 PACL *pDacl,
430 LPBOOL lpbDaclDefaulted);
431 typedef BOOL (WINAPI * IsValidSid_Proc) (
432 PSID sid);
433 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
434 DWORD dwFlags,
435 DWORD th32ProcessID);
436 typedef BOOL (WINAPI * Process32First_Proc) (
437 HANDLE hSnapshot,
438 LPPROCESSENTRY32 lppe);
439 typedef BOOL (WINAPI * Process32Next_Proc) (
440 HANDLE hSnapshot,
441 LPPROCESSENTRY32 lppe);
442 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
443 HANDLE ThreadHandle,
444 DWORD DesiredAccess,
445 BOOL OpenAsSelf,
446 PHANDLE TokenHandle);
447 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
448 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
449 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
450 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
451 HANDLE Process,
452 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
453 DWORD cb);
454 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
455 HANDLE hProcess,
456 PSIZE_T lpMinimumWorkingSetSize,
457 PSIZE_T lpMaximumWorkingSetSize);
458 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
459 LPMEMORYSTATUS lpBuffer);
460 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
461 LPMEMORY_STATUS_EX lpBuffer);
462 typedef BOOL (WINAPI * CopySid_Proc) (
463 DWORD nDestinationSidLength,
464 PSID pDestinationSid,
465 PSID pSourceSid);
466 typedef BOOL (WINAPI * EqualSid_Proc) (
467 PSID pSid1,
468 PSID pSid2);
469 typedef DWORD (WINAPI * GetLengthSid_Proc) (
470 PSID pSid);
471 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
472 LPSYSTEM_INFO lpSystemInfo);
473 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
474 LPFILETIME lpIdleTime,
475 LPFILETIME lpKernelTime,
476 LPFILETIME lpUserTime);
477 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
478 LPCWSTR lpSymlinkFileName,
479 LPCWSTR lpTargetFileName,
480 DWORD dwFlags);
481 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
482 LPCSTR lpSymlinkFileName,
483 LPCSTR lpTargetFileName,
484 DWORD dwFlags);
485 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
486 LPCTSTR StringSecurityDescriptor,
487 DWORD StringSDRevision,
488 PSECURITY_DESCRIPTOR *SecurityDescriptor,
489 PULONG SecurityDescriptorSize);
490 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
491 PSECURITY_DESCRIPTOR SecurityDescriptor,
492 DWORD RequestedStringSDRevision,
493 SECURITY_INFORMATION SecurityInformation,
494 LPTSTR *StringSecurityDescriptor,
495 PULONG StringSecurityDescriptorLen);
496 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
497 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
498 PIP_ADAPTER_INFO pAdapterInfo,
499 PULONG pOutBufLen);
501 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
502 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
503 DWORD multiByteToWideCharFlags;
505 /* ** A utility function ** */
506 static BOOL
507 is_windows_9x (void)
509 static BOOL s_b_ret = 0;
510 OSVERSIONINFO os_ver;
511 if (g_b_init_is_windows_9x == 0)
513 g_b_init_is_windows_9x = 1;
514 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
515 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
516 if (GetVersionEx (&os_ver))
518 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
521 return s_b_ret;
524 static Lisp_Object ltime (ULONGLONG);
526 /* Get total user and system times for get-internal-run-time.
527 Returns a list of integers if the times are provided by the OS
528 (NT derivatives), otherwise it returns the result of current-time. */
529 Lisp_Object w32_get_internal_run_time (void);
531 Lisp_Object
532 w32_get_internal_run_time (void)
534 if (get_process_times_fn)
536 FILETIME create, exit, kernel, user;
537 HANDLE proc = GetCurrentProcess ();
538 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
540 LARGE_INTEGER user_int, kernel_int, total;
541 user_int.LowPart = user.dwLowDateTime;
542 user_int.HighPart = user.dwHighDateTime;
543 kernel_int.LowPart = kernel.dwLowDateTime;
544 kernel_int.HighPart = kernel.dwHighDateTime;
545 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
546 return ltime (total.QuadPart);
550 return Fcurrent_time ();
553 /* ** The wrapper functions ** */
555 static BOOL WINAPI
556 open_process_token (HANDLE ProcessHandle,
557 DWORD DesiredAccess,
558 PHANDLE TokenHandle)
560 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
561 HMODULE hm_advapi32 = NULL;
562 if (is_windows_9x () == TRUE)
564 return FALSE;
566 if (g_b_init_open_process_token == 0)
568 g_b_init_open_process_token = 1;
569 hm_advapi32 = LoadLibrary ("Advapi32.dll");
570 s_pfn_Open_Process_Token =
571 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
573 if (s_pfn_Open_Process_Token == NULL)
575 return FALSE;
577 return (
578 s_pfn_Open_Process_Token (
579 ProcessHandle,
580 DesiredAccess,
581 TokenHandle)
585 static BOOL WINAPI
586 get_token_information (HANDLE TokenHandle,
587 TOKEN_INFORMATION_CLASS TokenInformationClass,
588 LPVOID TokenInformation,
589 DWORD TokenInformationLength,
590 PDWORD ReturnLength)
592 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
593 HMODULE hm_advapi32 = NULL;
594 if (is_windows_9x () == TRUE)
596 return FALSE;
598 if (g_b_init_get_token_information == 0)
600 g_b_init_get_token_information = 1;
601 hm_advapi32 = LoadLibrary ("Advapi32.dll");
602 s_pfn_Get_Token_Information =
603 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
605 if (s_pfn_Get_Token_Information == NULL)
607 return FALSE;
609 return (
610 s_pfn_Get_Token_Information (
611 TokenHandle,
612 TokenInformationClass,
613 TokenInformation,
614 TokenInformationLength,
615 ReturnLength)
619 static BOOL WINAPI
620 lookup_account_sid (LPCTSTR lpSystemName,
621 PSID Sid,
622 LPTSTR Name,
623 LPDWORD cbName,
624 LPTSTR DomainName,
625 LPDWORD cbDomainName,
626 PSID_NAME_USE peUse)
628 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
629 HMODULE hm_advapi32 = NULL;
630 if (is_windows_9x () == TRUE)
632 return FALSE;
634 if (g_b_init_lookup_account_sid == 0)
636 g_b_init_lookup_account_sid = 1;
637 hm_advapi32 = LoadLibrary ("Advapi32.dll");
638 s_pfn_Lookup_Account_Sid =
639 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
641 if (s_pfn_Lookup_Account_Sid == NULL)
643 return FALSE;
645 return (
646 s_pfn_Lookup_Account_Sid (
647 lpSystemName,
648 Sid,
649 Name,
650 cbName,
651 DomainName,
652 cbDomainName,
653 peUse)
657 static PDWORD WINAPI
658 get_sid_sub_authority (PSID pSid, DWORD n)
660 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
661 static DWORD zero = 0U;
662 HMODULE hm_advapi32 = NULL;
663 if (is_windows_9x () == TRUE)
665 return &zero;
667 if (g_b_init_get_sid_sub_authority == 0)
669 g_b_init_get_sid_sub_authority = 1;
670 hm_advapi32 = LoadLibrary ("Advapi32.dll");
671 s_pfn_Get_Sid_Sub_Authority =
672 (GetSidSubAuthority_Proc) GetProcAddress (
673 hm_advapi32, "GetSidSubAuthority");
675 if (s_pfn_Get_Sid_Sub_Authority == NULL)
677 return &zero;
679 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
682 static PUCHAR WINAPI
683 get_sid_sub_authority_count (PSID pSid)
685 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
686 static UCHAR zero = 0U;
687 HMODULE hm_advapi32 = NULL;
688 if (is_windows_9x () == TRUE)
690 return &zero;
692 if (g_b_init_get_sid_sub_authority_count == 0)
694 g_b_init_get_sid_sub_authority_count = 1;
695 hm_advapi32 = LoadLibrary ("Advapi32.dll");
696 s_pfn_Get_Sid_Sub_Authority_Count =
697 (GetSidSubAuthorityCount_Proc) GetProcAddress (
698 hm_advapi32, "GetSidSubAuthorityCount");
700 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
702 return &zero;
704 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
707 static DWORD WINAPI
708 get_security_info (HANDLE handle,
709 SE_OBJECT_TYPE ObjectType,
710 SECURITY_INFORMATION SecurityInfo,
711 PSID *ppsidOwner,
712 PSID *ppsidGroup,
713 PACL *ppDacl,
714 PACL *ppSacl,
715 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
717 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
718 HMODULE hm_advapi32 = NULL;
719 if (is_windows_9x () == TRUE)
721 return FALSE;
723 if (g_b_init_get_security_info == 0)
725 g_b_init_get_security_info = 1;
726 hm_advapi32 = LoadLibrary ("Advapi32.dll");
727 s_pfn_Get_Security_Info =
728 (GetSecurityInfo_Proc) GetProcAddress (
729 hm_advapi32, "GetSecurityInfo");
731 if (s_pfn_Get_Security_Info == NULL)
733 return FALSE;
735 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
736 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
737 ppSecurityDescriptor));
740 static BOOL WINAPI
741 get_file_security (const char *lpFileName,
742 SECURITY_INFORMATION RequestedInformation,
743 PSECURITY_DESCRIPTOR pSecurityDescriptor,
744 DWORD nLength,
745 LPDWORD lpnLengthNeeded)
747 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
748 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
749 HMODULE hm_advapi32 = NULL;
750 if (is_windows_9x () == TRUE)
752 errno = ENOTSUP;
753 return FALSE;
755 if (w32_unicode_filenames)
757 wchar_t filename_w[MAX_PATH];
759 if (g_b_init_get_file_security_w == 0)
761 g_b_init_get_file_security_w = 1;
762 hm_advapi32 = LoadLibrary ("Advapi32.dll");
763 s_pfn_Get_File_SecurityW =
764 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
765 "GetFileSecurityW");
767 if (s_pfn_Get_File_SecurityW == NULL)
769 errno = ENOTSUP;
770 return FALSE;
772 filename_to_utf16 (lpFileName, filename_w);
773 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
774 pSecurityDescriptor, nLength,
775 lpnLengthNeeded));
777 else
779 char filename_a[MAX_PATH];
781 if (g_b_init_get_file_security_a == 0)
783 g_b_init_get_file_security_a = 1;
784 hm_advapi32 = LoadLibrary ("Advapi32.dll");
785 s_pfn_Get_File_SecurityA =
786 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
787 "GetFileSecurityA");
789 if (s_pfn_Get_File_SecurityA == NULL)
791 errno = ENOTSUP;
792 return FALSE;
794 filename_to_ansi (lpFileName, filename_a);
795 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
796 pSecurityDescriptor, nLength,
797 lpnLengthNeeded));
801 static BOOL WINAPI
802 set_file_security (const char *lpFileName,
803 SECURITY_INFORMATION SecurityInformation,
804 PSECURITY_DESCRIPTOR pSecurityDescriptor)
806 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
807 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
808 HMODULE hm_advapi32 = NULL;
809 if (is_windows_9x () == TRUE)
811 errno = ENOTSUP;
812 return FALSE;
814 if (w32_unicode_filenames)
816 wchar_t filename_w[MAX_PATH];
818 if (g_b_init_set_file_security_w == 0)
820 g_b_init_set_file_security_w = 1;
821 hm_advapi32 = LoadLibrary ("Advapi32.dll");
822 s_pfn_Set_File_SecurityW =
823 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
824 "SetFileSecurityW");
826 if (s_pfn_Set_File_SecurityW == NULL)
828 errno = ENOTSUP;
829 return FALSE;
831 filename_to_utf16 (lpFileName, filename_w);
832 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
833 pSecurityDescriptor));
835 else
837 char filename_a[MAX_PATH];
839 if (g_b_init_set_file_security_a == 0)
841 g_b_init_set_file_security_a = 1;
842 hm_advapi32 = LoadLibrary ("Advapi32.dll");
843 s_pfn_Set_File_SecurityA =
844 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
845 "SetFileSecurityA");
847 if (s_pfn_Set_File_SecurityA == NULL)
849 errno = ENOTSUP;
850 return FALSE;
852 filename_to_ansi (lpFileName, filename_a);
853 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
854 pSecurityDescriptor));
858 static DWORD WINAPI
859 set_named_security_info (LPCTSTR lpObjectName,
860 SE_OBJECT_TYPE ObjectType,
861 SECURITY_INFORMATION SecurityInformation,
862 PSID psidOwner,
863 PSID psidGroup,
864 PACL pDacl,
865 PACL pSacl)
867 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
868 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
869 HMODULE hm_advapi32 = NULL;
870 if (is_windows_9x () == TRUE)
872 errno = ENOTSUP;
873 return ENOTSUP;
875 if (w32_unicode_filenames)
877 wchar_t filename_w[MAX_PATH];
879 if (g_b_init_set_named_security_info_w == 0)
881 g_b_init_set_named_security_info_w = 1;
882 hm_advapi32 = LoadLibrary ("Advapi32.dll");
883 s_pfn_Set_Named_Security_InfoW =
884 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
885 "SetNamedSecurityInfoW");
887 if (s_pfn_Set_Named_Security_InfoW == NULL)
889 errno = ENOTSUP;
890 return ENOTSUP;
892 filename_to_utf16 (lpObjectName, filename_w);
893 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
894 SecurityInformation, psidOwner,
895 psidGroup, pDacl, pSacl));
897 else
899 char filename_a[MAX_PATH];
901 if (g_b_init_set_named_security_info_a == 0)
903 g_b_init_set_named_security_info_a = 1;
904 hm_advapi32 = LoadLibrary ("Advapi32.dll");
905 s_pfn_Set_Named_Security_InfoA =
906 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
907 "SetNamedSecurityInfoA");
909 if (s_pfn_Set_Named_Security_InfoA == NULL)
911 errno = ENOTSUP;
912 return ENOTSUP;
914 filename_to_ansi (lpObjectName, filename_a);
915 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
916 SecurityInformation, psidOwner,
917 psidGroup, pDacl, pSacl));
921 static BOOL WINAPI
922 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
923 PSID *pOwner,
924 LPBOOL lpbOwnerDefaulted)
926 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
927 HMODULE hm_advapi32 = NULL;
928 if (is_windows_9x () == TRUE)
930 errno = ENOTSUP;
931 return FALSE;
933 if (g_b_init_get_security_descriptor_owner == 0)
935 g_b_init_get_security_descriptor_owner = 1;
936 hm_advapi32 = LoadLibrary ("Advapi32.dll");
937 s_pfn_Get_Security_Descriptor_Owner =
938 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
939 hm_advapi32, "GetSecurityDescriptorOwner");
941 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
943 errno = ENOTSUP;
944 return FALSE;
946 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
947 lpbOwnerDefaulted));
950 static BOOL WINAPI
951 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
952 PSID *pGroup,
953 LPBOOL lpbGroupDefaulted)
955 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
956 HMODULE hm_advapi32 = NULL;
957 if (is_windows_9x () == TRUE)
959 errno = ENOTSUP;
960 return FALSE;
962 if (g_b_init_get_security_descriptor_group == 0)
964 g_b_init_get_security_descriptor_group = 1;
965 hm_advapi32 = LoadLibrary ("Advapi32.dll");
966 s_pfn_Get_Security_Descriptor_Group =
967 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
968 hm_advapi32, "GetSecurityDescriptorGroup");
970 if (s_pfn_Get_Security_Descriptor_Group == NULL)
972 errno = ENOTSUP;
973 return FALSE;
975 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
976 lpbGroupDefaulted));
979 static BOOL WINAPI
980 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
981 LPBOOL lpbDaclPresent,
982 PACL *pDacl,
983 LPBOOL lpbDaclDefaulted)
985 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
986 HMODULE hm_advapi32 = NULL;
987 if (is_windows_9x () == TRUE)
989 errno = ENOTSUP;
990 return FALSE;
992 if (g_b_init_get_security_descriptor_dacl == 0)
994 g_b_init_get_security_descriptor_dacl = 1;
995 hm_advapi32 = LoadLibrary ("Advapi32.dll");
996 s_pfn_Get_Security_Descriptor_Dacl =
997 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
998 hm_advapi32, "GetSecurityDescriptorDacl");
1000 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
1002 errno = ENOTSUP;
1003 return FALSE;
1005 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
1006 lpbDaclPresent, pDacl,
1007 lpbDaclDefaulted));
1010 static BOOL WINAPI
1011 is_valid_sid (PSID sid)
1013 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
1014 HMODULE hm_advapi32 = NULL;
1015 if (is_windows_9x () == TRUE)
1017 return FALSE;
1019 if (g_b_init_is_valid_sid == 0)
1021 g_b_init_is_valid_sid = 1;
1022 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1023 s_pfn_Is_Valid_Sid =
1024 (IsValidSid_Proc) GetProcAddress (
1025 hm_advapi32, "IsValidSid");
1027 if (s_pfn_Is_Valid_Sid == NULL)
1029 return FALSE;
1031 return (s_pfn_Is_Valid_Sid (sid));
1034 static BOOL WINAPI
1035 equal_sid (PSID sid1, PSID sid2)
1037 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1038 HMODULE hm_advapi32 = NULL;
1039 if (is_windows_9x () == TRUE)
1041 return FALSE;
1043 if (g_b_init_equal_sid == 0)
1045 g_b_init_equal_sid = 1;
1046 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1047 s_pfn_Equal_Sid =
1048 (EqualSid_Proc) GetProcAddress (
1049 hm_advapi32, "EqualSid");
1051 if (s_pfn_Equal_Sid == NULL)
1053 return FALSE;
1055 return (s_pfn_Equal_Sid (sid1, sid2));
1058 static DWORD WINAPI
1059 get_length_sid (PSID sid)
1061 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1062 HMODULE hm_advapi32 = NULL;
1063 if (is_windows_9x () == TRUE)
1065 return 0;
1067 if (g_b_init_get_length_sid == 0)
1069 g_b_init_get_length_sid = 1;
1070 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1071 s_pfn_Get_Length_Sid =
1072 (GetLengthSid_Proc) GetProcAddress (
1073 hm_advapi32, "GetLengthSid");
1075 if (s_pfn_Get_Length_Sid == NULL)
1077 return 0;
1079 return (s_pfn_Get_Length_Sid (sid));
1082 static BOOL WINAPI
1083 copy_sid (DWORD destlen, PSID dest, PSID src)
1085 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1086 HMODULE hm_advapi32 = NULL;
1087 if (is_windows_9x () == TRUE)
1089 return FALSE;
1091 if (g_b_init_copy_sid == 0)
1093 g_b_init_copy_sid = 1;
1094 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1095 s_pfn_Copy_Sid =
1096 (CopySid_Proc) GetProcAddress (
1097 hm_advapi32, "CopySid");
1099 if (s_pfn_Copy_Sid == NULL)
1101 return FALSE;
1103 return (s_pfn_Copy_Sid (destlen, dest, src));
1107 END: Wrapper functions around OpenProcessToken
1108 and other functions in advapi32.dll that are only
1109 supported in Windows NT / 2k / XP
1112 static void WINAPI
1113 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1115 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1116 if (is_windows_9x () != TRUE)
1118 if (g_b_init_get_native_system_info == 0)
1120 g_b_init_get_native_system_info = 1;
1121 s_pfn_Get_Native_System_Info =
1122 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1123 "GetNativeSystemInfo");
1125 if (s_pfn_Get_Native_System_Info != NULL)
1126 s_pfn_Get_Native_System_Info (lpSystemInfo);
1128 else
1129 lpSystemInfo->dwNumberOfProcessors = -1;
1132 static BOOL WINAPI
1133 get_system_times (LPFILETIME lpIdleTime,
1134 LPFILETIME lpKernelTime,
1135 LPFILETIME lpUserTime)
1137 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1138 if (is_windows_9x () == TRUE)
1140 return FALSE;
1142 if (g_b_init_get_system_times == 0)
1144 g_b_init_get_system_times = 1;
1145 s_pfn_Get_System_times =
1146 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1147 "GetSystemTimes");
1149 if (s_pfn_Get_System_times == NULL)
1150 return FALSE;
1151 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1154 static BOOLEAN WINAPI
1155 create_symbolic_link (LPCSTR lpSymlinkFilename,
1156 LPCSTR lpTargetFileName,
1157 DWORD dwFlags)
1159 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1160 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1161 BOOLEAN retval;
1163 if (is_windows_9x () == TRUE)
1165 errno = ENOSYS;
1166 return 0;
1168 if (w32_unicode_filenames)
1170 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1172 if (g_b_init_create_symbolic_link_w == 0)
1174 g_b_init_create_symbolic_link_w = 1;
1175 s_pfn_Create_Symbolic_LinkW =
1176 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1177 "CreateSymbolicLinkW");
1179 if (s_pfn_Create_Symbolic_LinkW == NULL)
1181 errno = ENOSYS;
1182 return 0;
1185 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1186 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1187 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1188 /* If we were denied creation of the symlink, try again after
1189 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1190 if (!retval)
1192 TOKEN_PRIVILEGES priv_current;
1194 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1195 &priv_current))
1197 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1198 restore_privilege (&priv_current);
1199 revert_to_self ();
1203 else
1205 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1207 if (g_b_init_create_symbolic_link_a == 0)
1209 g_b_init_create_symbolic_link_a = 1;
1210 s_pfn_Create_Symbolic_LinkA =
1211 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1212 "CreateSymbolicLinkA");
1214 if (s_pfn_Create_Symbolic_LinkA == NULL)
1216 errno = ENOSYS;
1217 return 0;
1220 filename_to_ansi (lpSymlinkFilename, symfn_a);
1221 filename_to_ansi (lpTargetFileName, tgtfn_a);
1222 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1223 /* If we were denied creation of the symlink, try again after
1224 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1225 if (!retval)
1227 TOKEN_PRIVILEGES priv_current;
1229 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1230 &priv_current))
1232 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1233 restore_privilege (&priv_current);
1234 revert_to_self ();
1238 return retval;
1241 static BOOL WINAPI
1242 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1244 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1246 if (is_windows_9x () == TRUE)
1248 errno = ENOTSUP;
1249 return FALSE;
1252 if (g_b_init_is_valid_security_descriptor == 0)
1254 g_b_init_is_valid_security_descriptor = 1;
1255 s_pfn_Is_Valid_Security_Descriptor_Proc =
1256 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1257 "IsValidSecurityDescriptor");
1259 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1261 errno = ENOTSUP;
1262 return FALSE;
1265 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1268 static BOOL WINAPI
1269 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1270 DWORD RequestedStringSDRevision,
1271 SECURITY_INFORMATION SecurityInformation,
1272 LPTSTR *StringSecurityDescriptor,
1273 PULONG StringSecurityDescriptorLen)
1275 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1276 BOOL retval;
1278 if (is_windows_9x () == TRUE)
1280 errno = ENOTSUP;
1281 return FALSE;
1284 if (g_b_init_convert_sd_to_sddl == 0)
1286 g_b_init_convert_sd_to_sddl = 1;
1287 #ifdef _UNICODE
1288 s_pfn_Convert_SD_To_SDDL =
1289 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1290 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1291 #else
1292 s_pfn_Convert_SD_To_SDDL =
1293 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1294 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1295 #endif
1297 if (s_pfn_Convert_SD_To_SDDL == NULL)
1299 errno = ENOTSUP;
1300 return FALSE;
1303 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1304 RequestedStringSDRevision,
1305 SecurityInformation,
1306 StringSecurityDescriptor,
1307 StringSecurityDescriptorLen);
1309 return retval;
1312 static BOOL WINAPI
1313 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1314 DWORD StringSDRevision,
1315 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1316 PULONG SecurityDescriptorSize)
1318 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1319 BOOL retval;
1321 if (is_windows_9x () == TRUE)
1323 errno = ENOTSUP;
1324 return FALSE;
1327 if (g_b_init_convert_sddl_to_sd == 0)
1329 g_b_init_convert_sddl_to_sd = 1;
1330 #ifdef _UNICODE
1331 s_pfn_Convert_SDDL_To_SD =
1332 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1333 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1334 #else
1335 s_pfn_Convert_SDDL_To_SD =
1336 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1337 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1338 #endif
1340 if (s_pfn_Convert_SDDL_To_SD == NULL)
1342 errno = ENOTSUP;
1343 return FALSE;
1346 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1347 StringSDRevision,
1348 SecurityDescriptor,
1349 SecurityDescriptorSize);
1351 return retval;
1354 static DWORD WINAPI
1355 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1357 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1358 HMODULE hm_iphlpapi = NULL;
1360 if (is_windows_9x () == TRUE)
1361 return ERROR_NOT_SUPPORTED;
1363 if (g_b_init_get_adapters_info == 0)
1365 g_b_init_get_adapters_info = 1;
1366 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1367 if (hm_iphlpapi)
1368 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1369 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1371 if (s_pfn_Get_Adapters_Info == NULL)
1372 return ERROR_NOT_SUPPORTED;
1373 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1378 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1379 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1381 This is called from alloc.c:valid_pointer_p. */
1383 w32_valid_pointer_p (void *p, int size)
1385 SIZE_T done;
1386 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1388 if (h)
1390 unsigned char *buf = alloca (size);
1391 int retval = ReadProcessMemory (h, p, buf, size, &done);
1393 CloseHandle (h);
1394 return retval;
1396 else
1397 return -1;
1402 /* Here's an overview of how the Windows build supports file names
1403 that cannot be encoded by the current system codepage.
1405 From the POV of Lisp and layers of C code above the functions here,
1406 Emacs on Windows pretends that its file names are encoded in UTF-8;
1407 see encode_file and decode_file on coding.c. Any file name that is
1408 passed as a unibyte string to C functions defined here is assumed
1409 to be in UTF-8 encoding. Any file name returned by functions
1410 defined here must be in UTF-8 encoding, with only a few exceptions
1411 reserved for a couple of special cases. (Be sure to use
1412 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1413 as they can be much longer than MAX_PATH!)
1415 The UTF-8 encoded file names cannot be passed to system APIs, as
1416 Windows does not support that. Therefore, they are converted
1417 either to UTF-16 or to the ANSI codepage, depending on the value of
1418 w32-unicode-filenames, before calling any system APIs or CRT library
1419 functions. The default value of that variable is determined by the
1420 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1421 user can change that default (although I don't see why would she
1422 want to).
1424 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1425 filename_from_utf16, and filename_from_ansi, are the workhorses of
1426 these conversions. They rely on Windows native APIs
1427 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1428 functions from coding.c here, because they allocate memory, which
1429 is a bad idea on the level of libc, which is what the functions
1430 here emulate. (If you worry about performance due to constant
1431 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1432 it was measured to take only a few microseconds on a not-so-fast
1433 machine, and second, that's exactly what the ANSI APIs we used
1434 before did anyway, because they are just thin wrappers around the
1435 Unicode APIs.)
1437 The variables file-name-coding-system and default-file-name-coding-system
1438 still exist, but are actually used only when a file name needs to
1439 be converted to the ANSI codepage. This happens all the time when
1440 w32-unicode-filenames is nil, but can also happen from time to time
1441 when it is t. Otherwise, these variables have no effect on file-name
1442 encoding when w32-unicode-filenames is t; this is similar to
1443 selection-coding-system.
1445 This arrangement works very well, but it has a few gotchas and
1446 limitations:
1448 . Lisp code that encodes or decodes file names manually should
1449 normally use 'utf-8' as the coding-system on Windows,
1450 disregarding file-name-coding-system. This is a somewhat
1451 unpleasant consequence, but it cannot be avoided. Fortunately,
1452 very few Lisp packages need to do that.
1454 More generally, passing to library functions (e.g., fopen or
1455 opendir) file names already encoded in the ANSI codepage is
1456 explicitly *verboten*, as all those functions, as shadowed and
1457 emulated here, assume they will receive UTF-8 encoded file names.
1459 For the same reasons, no CRT function or Win32 API can be called
1460 directly in Emacs sources, without either converting the file
1461 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1462 some shadowing function defined here.
1464 . Environment variables stored in Vprocess_environment are encoded
1465 in the ANSI codepage, so if getenv/egetenv is used for a variable
1466 whose value is a file name or a list of directories, it needs to
1467 be converted to UTF-8, before it is used as argument to functions
1468 or decoded into a Lisp string.
1470 . File names passed to external libraries, like the image libraries
1471 and GnuTLS, need special handling. These libraries generally
1472 don't support UTF-16 or UTF-8 file names, so they must get file
1473 names encoded in the ANSI codepage. To facilitate using these
1474 libraries with file names that are not encodable in the ANSI
1475 codepage, use the function ansi_encode_filename, which will try
1476 to use the short 8+3 alias of a file name if that file name is
1477 not encodable in the ANSI codepage. See image.c and gnutls.c for
1478 examples of how this should be done.
1480 . Running subprocesses in non-ASCII directories and with non-ASCII
1481 file arguments is limited to the current codepage (even though
1482 Emacs is perfectly capable of finding an executable program file
1483 in a directory whose name cannot be encoded in the current
1484 codepage). This is because the command-line arguments are
1485 encoded _before_ they get to the w32-specific level, and the
1486 encoding is not known in advance (it doesn't have to be the
1487 current ANSI codepage), so w32proc.c functions cannot re-encode
1488 them in UTF-16. This should be fixed, but will also require
1489 changes in cmdproxy. The current limitation is not terribly bad
1490 anyway, since very few, if any, Windows console programs that are
1491 likely to be invoked by Emacs support UTF-16 encoded command
1492 lines.
1494 . For similar reasons, server.el and emacsclient are also limited
1495 to the current ANSI codepage for now.
1497 . Emacs itself can only handle command-line arguments encoded in
1498 the current codepage.
1500 . Turning on w32-unicode-filename on Windows 9X (if it at all
1501 works) requires UNICOWS.DLL, which is thus a requirement even in
1502 non-GUI sessions, something the we previously avoided. */
1506 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1507 codepage defined by file-name-coding-system. */
1509 /* Current codepage for encoding file names. */
1510 static int file_name_codepage;
1512 /* Initialize the codepage used for decoding file names. This is
1513 needed to undo the value recorded during dumping, which might not
1514 be correct when we run the dumped Emacs. */
1515 void
1516 w32_init_file_name_codepage (void)
1518 file_name_codepage = CP_ACP;
1519 w32_ansi_code_page = CP_ACP;
1522 /* Produce a Windows ANSI codepage suitable for encoding file names.
1523 Return the information about that codepage in CP_INFO. */
1525 codepage_for_filenames (CPINFO *cp_info)
1527 /* A simple cache to avoid calling GetCPInfo every time we need to
1528 encode/decode a file name. The file-name encoding is not
1529 supposed to be changed too frequently, if ever. */
1530 static Lisp_Object last_file_name_encoding;
1531 static CPINFO cp;
1532 Lisp_Object current_encoding;
1534 current_encoding = Vfile_name_coding_system;
1535 if (NILP (current_encoding))
1536 current_encoding = Vdefault_file_name_coding_system;
1538 if (!EQ (last_file_name_encoding, current_encoding)
1539 || NILP (last_file_name_encoding))
1541 /* Default to the current ANSI codepage. */
1542 file_name_codepage = w32_ansi_code_page;
1544 if (!NILP (current_encoding))
1546 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1547 char *cp = NULL, *end;
1548 int cpnum;
1550 if (strncmp (cpname, "cp", 2) == 0)
1551 cp = cpname + 2;
1552 else if (strncmp (cpname, "windows-", 8) == 0)
1553 cp = cpname + 8;
1555 if (cp)
1557 end = cp;
1558 cpnum = strtol (cp, &end, 10);
1559 if (cpnum && *end == '\0' && end - cp >= 2)
1560 file_name_codepage = cpnum;
1564 if (!file_name_codepage)
1565 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1567 if (!GetCPInfo (file_name_codepage, &cp))
1569 file_name_codepage = CP_ACP;
1570 if (!GetCPInfo (file_name_codepage, &cp))
1571 emacs_abort ();
1574 /* Cache the new value. */
1575 last_file_name_encoding = current_encoding;
1577 if (cp_info)
1578 *cp_info = cp;
1580 return file_name_codepage;
1584 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1586 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1587 -1, fn_out, MAX_PATH);
1589 if (!result)
1591 DWORD err = GetLastError ();
1593 switch (err)
1595 case ERROR_INVALID_FLAGS:
1596 case ERROR_INVALID_PARAMETER:
1597 errno = EINVAL;
1598 break;
1599 case ERROR_INSUFFICIENT_BUFFER:
1600 case ERROR_NO_UNICODE_TRANSLATION:
1601 default:
1602 errno = ENOENT;
1603 break;
1605 return -1;
1607 return 0;
1611 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1613 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1614 fn_out, MAX_UTF8_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;
1638 filename_to_ansi (const char *fn_in, char *fn_out)
1640 wchar_t fn_utf16[MAX_PATH];
1642 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1644 int result;
1645 int codepage = codepage_for_filenames (NULL);
1647 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1648 fn_out, MAX_PATH, NULL, NULL);
1649 if (!result)
1651 DWORD err = GetLastError ();
1653 switch (err)
1655 case ERROR_INVALID_FLAGS:
1656 case ERROR_INVALID_PARAMETER:
1657 errno = EINVAL;
1658 break;
1659 case ERROR_INSUFFICIENT_BUFFER:
1660 case ERROR_NO_UNICODE_TRANSLATION:
1661 default:
1662 errno = ENOENT;
1663 break;
1665 return -1;
1667 return 0;
1669 return -1;
1673 filename_from_ansi (const char *fn_in, char *fn_out)
1675 wchar_t fn_utf16[MAX_PATH];
1676 int codepage = codepage_for_filenames (NULL);
1677 int result = pMultiByteToWideChar (codepage, multiByteToWideCharFlags, fn_in,
1678 -1, fn_utf16, MAX_PATH);
1680 if (!result)
1682 DWORD err = GetLastError ();
1684 switch (err)
1686 case ERROR_INVALID_FLAGS:
1687 case ERROR_INVALID_PARAMETER:
1688 errno = EINVAL;
1689 break;
1690 case ERROR_INSUFFICIENT_BUFFER:
1691 case ERROR_NO_UNICODE_TRANSLATION:
1692 default:
1693 errno = ENOENT;
1694 break;
1696 return -1;
1698 return filename_from_utf16 (fn_utf16, fn_out);
1703 /* The directory where we started, in UTF-8. */
1704 static char startup_dir[MAX_UTF8_PATH];
1706 /* Get the current working directory. */
1707 char *
1708 getcwd (char *dir, int dirsize)
1710 if (!dirsize)
1712 errno = EINVAL;
1713 return NULL;
1715 if (dirsize <= strlen (startup_dir))
1717 errno = ERANGE;
1718 return NULL;
1720 #if 0
1721 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1722 return dir;
1723 return NULL;
1724 #else
1725 /* Emacs doesn't actually change directory itself, it stays in the
1726 same directory where it was started. */
1727 strcpy (dir, startup_dir);
1728 return dir;
1729 #endif
1732 /* Emulate getloadavg. */
1734 struct load_sample {
1735 time_t sample_time;
1736 ULONGLONG idle;
1737 ULONGLONG kernel;
1738 ULONGLONG user;
1741 /* Number of processors on this machine. */
1742 static unsigned num_of_processors;
1744 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1745 static struct load_sample samples[16*60];
1746 static int first_idx = -1, last_idx = -1;
1747 static int max_idx = ARRAYELTS (samples);
1749 static int
1750 buf_next (int from)
1752 int next_idx = from + 1;
1754 if (next_idx >= max_idx)
1755 next_idx = 0;
1757 return next_idx;
1760 static int
1761 buf_prev (int from)
1763 int prev_idx = from - 1;
1765 if (prev_idx < 0)
1766 prev_idx = max_idx - 1;
1768 return prev_idx;
1771 static void
1772 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1774 SYSTEM_INFO sysinfo;
1775 FILETIME ft_idle, ft_user, ft_kernel;
1777 /* Initialize the number of processors on this machine. */
1778 if (num_of_processors <= 0)
1780 get_native_system_info (&sysinfo);
1781 num_of_processors = sysinfo.dwNumberOfProcessors;
1782 if (num_of_processors <= 0)
1784 GetSystemInfo (&sysinfo);
1785 num_of_processors = sysinfo.dwNumberOfProcessors;
1787 if (num_of_processors <= 0)
1788 num_of_processors = 1;
1791 /* TODO: Take into account threads that are ready to run, by
1792 sampling the "\System\Processor Queue Length" performance
1793 counter. The code below accounts only for threads that are
1794 actually running. */
1796 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1798 ULARGE_INTEGER uidle, ukernel, uuser;
1800 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1801 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1802 memcpy (&uuser, &ft_user, sizeof (ft_user));
1803 *idle = uidle.QuadPart;
1804 *kernel = ukernel.QuadPart;
1805 *user = uuser.QuadPart;
1807 else
1809 *idle = 0;
1810 *kernel = 0;
1811 *user = 0;
1815 /* Produce the load average for a given time interval, using the
1816 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1817 1-minute, 5-minute, or 15-minute average, respectively. */
1818 static double
1819 getavg (int which)
1821 double retval = -1.0;
1822 double tdiff;
1823 int idx;
1824 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1825 time_t now = samples[last_idx].sample_time;
1827 if (first_idx != last_idx)
1829 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1831 tdiff = difftime (now, samples[idx].sample_time);
1832 if (tdiff >= span - 2*DBL_EPSILON*now)
1834 long double sys =
1835 samples[last_idx].kernel + samples[last_idx].user
1836 - (samples[idx].kernel + samples[idx].user);
1837 long double idl = samples[last_idx].idle - samples[idx].idle;
1839 retval = (1.0 - idl / sys) * num_of_processors;
1840 break;
1842 if (idx == first_idx)
1843 break;
1847 return retval;
1851 getloadavg (double loadavg[], int nelem)
1853 int elem;
1854 ULONGLONG idle, kernel, user;
1855 time_t now = time (NULL);
1857 /* If system time jumped back for some reason, delete all samples
1858 whose time is later than the current wall-clock time. This
1859 prevents load average figures from becoming frozen for prolonged
1860 periods of time, when system time is reset backwards. */
1861 if (last_idx >= 0)
1863 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1865 if (last_idx == first_idx)
1867 first_idx = last_idx = -1;
1868 break;
1870 last_idx = buf_prev (last_idx);
1874 /* Store another sample. We ignore samples that are less than 1 sec
1875 apart. */
1876 if (last_idx < 0
1877 || (difftime (now, samples[last_idx].sample_time)
1878 >= 1.0 - 2*DBL_EPSILON*now))
1880 sample_system_load (&idle, &kernel, &user);
1881 last_idx = buf_next (last_idx);
1882 samples[last_idx].sample_time = now;
1883 samples[last_idx].idle = idle;
1884 samples[last_idx].kernel = kernel;
1885 samples[last_idx].user = user;
1886 /* If the buffer has more that 15 min worth of samples, discard
1887 the old ones. */
1888 if (first_idx == -1)
1889 first_idx = last_idx;
1890 while (first_idx != last_idx
1891 && (difftime (now, samples[first_idx].sample_time)
1892 >= 15.0*60 + 2*DBL_EPSILON*now))
1893 first_idx = buf_next (first_idx);
1896 for (elem = 0; elem < nelem; elem++)
1898 double avg = getavg (elem);
1900 if (avg < 0)
1901 break;
1902 loadavg[elem] = avg;
1905 return elem;
1908 /* Emulate getpwuid, getpwnam and others. */
1910 #define PASSWD_FIELD_SIZE 256
1912 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1913 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1914 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1915 static char dflt_passwd_dir[MAX_UTF8_PATH];
1916 static char dflt_passwd_shell[MAX_UTF8_PATH];
1918 static struct passwd dflt_passwd =
1920 dflt_passwd_name,
1921 dflt_passwd_passwd,
1925 dflt_passwd_gecos,
1926 dflt_passwd_dir,
1927 dflt_passwd_shell,
1930 static char dflt_group_name[GNLEN+1];
1932 static struct group dflt_group =
1934 /* When group information is not available, we return this as the
1935 group for all files. */
1936 dflt_group_name,
1940 unsigned
1941 getuid (void)
1943 return dflt_passwd.pw_uid;
1946 unsigned
1947 geteuid (void)
1949 /* I could imagine arguing for checking to see whether the user is
1950 in the Administrators group and returning a UID of 0 for that
1951 case, but I don't know how wise that would be in the long run. */
1952 return getuid ();
1955 unsigned
1956 getgid (void)
1958 return dflt_passwd.pw_gid;
1961 unsigned
1962 getegid (void)
1964 return getgid ();
1967 struct passwd *
1968 getpwuid (unsigned uid)
1970 if (uid == dflt_passwd.pw_uid)
1971 return &dflt_passwd;
1972 return NULL;
1975 struct group *
1976 getgrgid (gid_t gid)
1978 return &dflt_group;
1981 struct passwd *
1982 getpwnam (char *name)
1984 struct passwd *pw;
1986 pw = getpwuid (getuid ());
1987 if (!pw)
1988 return pw;
1990 if (xstrcasecmp (name, pw->pw_name))
1991 return NULL;
1993 return pw;
1996 static void
1997 init_user_info (void)
1999 /* Find the user's real name by opening the process token and
2000 looking up the name associated with the user-sid in that token.
2002 Use the relative portion of the identifier authority value from
2003 the user-sid as the user id value (same for group id using the
2004 primary group sid from the process token). */
2006 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
2007 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
2008 DWORD glength = sizeof (gname);
2009 HANDLE token = NULL;
2010 SID_NAME_USE user_type;
2011 unsigned char *buf = NULL;
2012 DWORD blen = 0;
2013 TOKEN_USER user_token;
2014 TOKEN_PRIMARY_GROUP group_token;
2015 BOOL result;
2017 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
2018 if (result)
2020 result = get_token_information (token, TokenUser, NULL, 0, &blen);
2021 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2023 buf = xmalloc (blen);
2024 result = get_token_information (token, TokenUser,
2025 (LPVOID)buf, blen, &needed);
2026 if (result)
2028 memcpy (&user_token, buf, sizeof (user_token));
2029 result = lookup_account_sid (NULL, user_token.User.Sid,
2030 uname, &ulength,
2031 domain, &dlength, &user_type);
2034 else
2035 result = FALSE;
2037 if (result)
2039 strcpy (dflt_passwd.pw_name, uname);
2040 /* Determine a reasonable uid value. */
2041 if (xstrcasecmp ("administrator", uname) == 0)
2043 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2044 dflt_passwd.pw_gid = 513; /* well-known None gid */
2046 else
2048 /* Use the last sub-authority value of the RID, the relative
2049 portion of the SID, as user/group ID. */
2050 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2052 /* Get group id and name. */
2053 result = get_token_information (token, TokenPrimaryGroup,
2054 (LPVOID)buf, blen, &needed);
2055 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2057 buf = xrealloc (buf, blen = needed);
2058 result = get_token_information (token, TokenPrimaryGroup,
2059 (LPVOID)buf, blen, &needed);
2061 if (result)
2063 memcpy (&group_token, buf, sizeof (group_token));
2064 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2065 dlength = sizeof (domain);
2066 /* If we can get at the real Primary Group name, use that.
2067 Otherwise, the default group name was already set to
2068 "None" in globals_of_w32. */
2069 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2070 gname, &glength, NULL, &dlength,
2071 &user_type))
2072 strcpy (dflt_group_name, gname);
2074 else
2075 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2078 /* If security calls are not supported (presumably because we
2079 are running under Windows 9X), fallback to this: */
2080 else if (GetUserName (uname, &ulength))
2082 strcpy (dflt_passwd.pw_name, uname);
2083 if (xstrcasecmp ("administrator", uname) == 0)
2084 dflt_passwd.pw_uid = 0;
2085 else
2086 dflt_passwd.pw_uid = 123;
2087 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2089 else
2091 strcpy (dflt_passwd.pw_name, "unknown");
2092 dflt_passwd.pw_uid = 123;
2093 dflt_passwd.pw_gid = 123;
2095 dflt_group.gr_gid = dflt_passwd.pw_gid;
2097 /* Set dir and shell from environment variables. */
2098 if (w32_unicode_filenames)
2100 wchar_t *home = _wgetenv (L"HOME");
2101 wchar_t *shell = _wgetenv (L"SHELL");
2103 /* Ensure HOME and SHELL are defined. */
2104 if (home == NULL)
2105 emacs_abort ();
2106 if (shell == NULL)
2107 emacs_abort ();
2108 filename_from_utf16 (home, dflt_passwd.pw_dir);
2109 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2111 else
2113 char *home = getenv ("HOME");
2114 char *shell = getenv ("SHELL");
2116 if (home == NULL)
2117 emacs_abort ();
2118 if (shell == NULL)
2119 emacs_abort ();
2120 filename_from_ansi (home, dflt_passwd.pw_dir);
2121 filename_from_ansi (shell, dflt_passwd.pw_shell);
2124 xfree (buf);
2125 if (token)
2126 CloseHandle (token);
2129 static HCRYPTPROV w32_crypto_hprov;
2130 static int
2131 w32_init_crypt_random (void)
2133 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2134 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2136 DebPrint (("CryptAcquireContext failed with error %x\n",
2137 GetLastError ()));
2138 w32_crypto_hprov = 0;
2139 return -1;
2141 return 0;
2145 w32_init_random (void *buf, ptrdiff_t buflen)
2147 if (!w32_crypto_hprov)
2148 w32_init_crypt_random ();
2149 if (w32_crypto_hprov)
2151 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2152 return 0;
2154 return -1;
2157 /* MS-Windows 'rand' produces separate identical series for each
2158 thread, so we replace it with our version. */
2160 /* Algorithm AS183: An Efficient and Portable Pseudo-random Number
2161 Generator, by B.A. Wichmann, I.D. Hill. AS, v31, No. 2 (1982). */
2162 static int ix = 3172, iy = 9814, iz = 20125;
2163 #define RAND_MAX_X 30269
2164 #define RAND_MAX_Y 30307
2165 #define RAND_MAX_Z 30323
2167 static int
2168 rand_as183 (void)
2170 ix = (171 * ix) % RAND_MAX_X;
2171 iy = (172 * iy) % RAND_MAX_Y;
2172 iz = (170 * iz) % RAND_MAX_Z;
2174 return (ix + iy + iz) & 0x7fff;
2178 random (void)
2180 /* rand_as183 () gives us 15 random bits...hack together 30 bits. */
2181 return ((rand_as183 () << 15) | rand_as183 ());
2184 void
2185 srandom (int seed)
2187 srand (seed);
2188 ix = rand () % RAND_MAX_X;
2189 iy = rand () % RAND_MAX_Y;
2190 iz = rand () % RAND_MAX_Z;
2193 /* Return the maximum length in bytes of a multibyte character
2194 sequence encoded in the current ANSI codepage. This is required to
2195 correctly walk the encoded file names one character at a time. */
2196 static int
2197 max_filename_mbslen (void)
2199 CPINFO cp_info;
2201 codepage_for_filenames (&cp_info);
2202 return cp_info.MaxCharSize;
2205 /* Normalize filename by converting in-place all of its path
2206 separators to the separator specified by PATH_SEP. */
2208 static void
2209 normalize_filename (register char *fp, char path_sep)
2211 char *p2;
2213 /* Always lower-case drive letters a-z, even if the filesystem
2214 preserves case in filenames.
2215 This is so filenames can be compared by string comparison
2216 functions that are case-sensitive. Even case-preserving filesystems
2217 do not distinguish case in drive letters. */
2218 p2 = fp + 1;
2220 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2222 *fp += 'a' - 'A';
2223 fp += 2;
2226 while (*fp)
2228 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2229 *fp = path_sep;
2230 fp++;
2234 /* Destructively turn backslashes into slashes. */
2235 void
2236 dostounix_filename (register char *p)
2238 normalize_filename (p, '/');
2241 /* Destructively turn slashes into backslashes. */
2242 void
2243 unixtodos_filename (register char *p)
2245 normalize_filename (p, '\\');
2248 /* Remove all CR's that are followed by a LF.
2249 (From msdos.c...probably should figure out a way to share it,
2250 although this code isn't going to ever change.) */
2251 static int
2252 crlf_to_lf (register int n, register char *buf)
2254 unsigned char *np = (unsigned char *)buf;
2255 unsigned char *startp = np;
2256 char *endp = buf + n;
2258 if (n == 0)
2259 return n;
2260 while (buf < endp - 1)
2262 if (*buf == 0x0d)
2264 if (*(++buf) != 0x0a)
2265 *np++ = 0x0d;
2267 else
2268 *np++ = *buf++;
2270 if (buf < endp)
2271 *np++ = *buf++;
2272 return np - startp;
2275 /* Parse the root part of file name, if present. Return length and
2276 optionally store pointer to char after root. */
2277 static int
2278 parse_root (const char * name, const char ** pPath)
2280 const char * start = name;
2282 if (name == NULL)
2283 return 0;
2285 /* find the root name of the volume if given */
2286 if (isalpha (name[0]) && name[1] == ':')
2288 /* skip past drive specifier */
2289 name += 2;
2290 if (IS_DIRECTORY_SEP (name[0]))
2291 name++;
2293 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2295 int slashes = 2;
2297 name += 2;
2300 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2301 break;
2302 name++;
2304 while ( *name );
2305 if (IS_DIRECTORY_SEP (name[0]))
2306 name++;
2309 if (pPath)
2310 *pPath = name;
2312 return name - start;
2315 /* Get long base name for name; name is assumed to be absolute. */
2316 static int
2317 get_long_basename (char * name, char * buf, int size)
2319 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2320 char fname_utf8[MAX_UTF8_PATH];
2321 int len = 0;
2322 int cstatus = -1;
2324 /* Must be valid filename, no wild cards or other invalid characters. */
2325 if (strpbrk (name, "*?|<>\""))
2326 return 0;
2328 if (w32_unicode_filenames)
2330 wchar_t fname_utf16[MAX_PATH];
2331 WIN32_FIND_DATAW find_data_wide;
2333 filename_to_utf16 (name, fname_utf16);
2334 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2335 if (dir_handle != INVALID_HANDLE_VALUE)
2336 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2338 else
2340 char fname_ansi[MAX_PATH];
2341 WIN32_FIND_DATAA find_data_ansi;
2343 filename_to_ansi (name, fname_ansi);
2344 /* If the ANSI name includes ? characters, it is not encodable
2345 in the ANSI codepage. In that case, we deliver the question
2346 marks to the caller; calling FindFirstFileA in this case
2347 could return some unrelated file name in the same
2348 directory. */
2349 if (_mbspbrk (fname_ansi, "?"))
2351 /* Find the basename of fname_ansi. */
2352 char *p = strrchr (fname_ansi, '\\');
2354 if (!p)
2355 p = fname_ansi;
2356 else
2357 p++;
2358 cstatus = filename_from_ansi (p, fname_utf8);
2360 else
2362 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2363 if (dir_handle != INVALID_HANDLE_VALUE)
2364 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2368 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2369 memcpy (buf, fname_utf8, len + 1);
2370 else
2371 len = 0;
2373 if (dir_handle != INVALID_HANDLE_VALUE)
2374 FindClose (dir_handle);
2376 return len;
2379 /* Get long name for file, if possible (assumed to be absolute). */
2380 BOOL
2381 w32_get_long_filename (const char * name, char * buf, int size)
2383 char * o = buf;
2384 char * p;
2385 const char * q;
2386 char full[ MAX_UTF8_PATH ];
2387 int len;
2389 len = strlen (name);
2390 if (len >= MAX_UTF8_PATH)
2391 return FALSE;
2393 /* Use local copy for destructive modification. */
2394 memcpy (full, name, len+1);
2395 unixtodos_filename (full);
2397 /* Copy root part verbatim. */
2398 len = parse_root (full, (const char **)&p);
2399 memcpy (o, full, len);
2400 o += len;
2401 *o = '\0';
2402 size -= len;
2404 while (p != NULL && *p)
2406 q = p;
2407 p = strchr (q, '\\');
2408 if (p) *p = '\0';
2409 len = get_long_basename (full, o, size);
2410 if (len > 0)
2412 o += len;
2413 size -= len;
2414 if (p != NULL)
2416 *p++ = '\\';
2417 if (size < 2)
2418 return FALSE;
2419 *o++ = '\\';
2420 size--;
2421 *o = '\0';
2424 else
2425 return FALSE;
2428 return TRUE;
2431 unsigned int
2432 w32_get_short_filename (const char * name, char * buf, int size)
2434 if (w32_unicode_filenames)
2436 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2437 unsigned int retval;
2439 filename_to_utf16 (name, name_utf16);
2440 retval = GetShortPathNameW (name_utf16, short_name, size);
2441 if (retval && retval < size)
2442 filename_from_utf16 (short_name, buf);
2443 return retval;
2445 else
2447 char name_ansi[MAX_PATH];
2449 filename_to_ansi (name, name_ansi);
2450 return GetShortPathNameA (name_ansi, buf, size);
2454 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2455 MS-Windows ANSI codepage. If FILENAME includes characters not
2456 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2457 if it exists. This is needed because the w32 build wants to
2458 support file names outside of the system locale, but image
2459 libraries typically don't support wide (a.k.a. "Unicode") APIs
2460 required for that. */
2462 Lisp_Object
2463 ansi_encode_filename (Lisp_Object filename)
2465 Lisp_Object encoded_filename;
2466 char fname[MAX_PATH];
2468 filename_to_ansi (SSDATA (filename), fname);
2469 if (_mbspbrk (fname, "?"))
2471 char shortname[MAX_PATH];
2473 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2475 dostounix_filename (shortname);
2476 encoded_filename = build_string (shortname);
2478 else
2479 encoded_filename = build_unibyte_string (fname);
2481 else
2482 encoded_filename = build_unibyte_string (fname);
2483 return encoded_filename;
2486 static int
2487 is_unc_volume (const char *filename)
2489 const char *ptr = filename;
2491 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2492 return 0;
2494 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2495 return 0;
2497 return 1;
2500 /* Emulate the Posix unsetenv. */
2502 unsetenv (const char *name)
2504 char *var;
2505 size_t name_len;
2507 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2509 errno = EINVAL;
2510 return -1;
2512 name_len = strlen (name);
2513 /* MS docs says an environment variable cannot be longer than 32K. */
2514 if (name_len > 32767)
2516 errno = ENOMEM;
2517 return 0;
2519 /* It is safe to use 'alloca' with 32K size, since the stack is at
2520 least 2MB, and we set it to 8MB in the link command line. */
2521 var = alloca (name_len + 2);
2522 strncpy (var, name, name_len);
2523 var[name_len++] = '=';
2524 var[name_len] = '\0';
2525 return _putenv (var);
2528 /* MS _putenv doesn't support removing a variable when the argument
2529 does not include the '=' character, so we fix that here. */
2531 sys_putenv (char *str)
2533 const char *const name_end = strchr (str, '=');
2535 if (name_end == NULL)
2537 /* Remove the variable from the environment. */
2538 return unsetenv (str);
2541 if (strncmp (str, "TZ=<", 4) == 0)
2543 /* MS-Windows does not support POSIX.1-2001 angle-bracket TZ
2544 abbreviation syntax. Convert to POSIX.1-1988 syntax if possible,
2545 and to the undocumented placeholder "ZZZ" otherwise. */
2546 bool supported_abbr = true;
2547 for (char *p = str + 4; *p; p++)
2549 if (('0' <= *p && *p <= '9') || *p == '-' || *p == '+')
2550 supported_abbr = false;
2551 else if (*p == '>')
2553 ptrdiff_t abbrlen;
2554 if (supported_abbr)
2556 abbrlen = p - (str + 4);
2557 memmove (str + 3, str + 4, abbrlen);
2559 else
2561 abbrlen = 3;
2562 memset (str + 3, 'Z', abbrlen);
2564 memmove (str + 3 + abbrlen, p + 1, strlen (p));
2565 break;
2570 return _putenv (str);
2573 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2575 LPBYTE
2576 w32_get_resource (const char *key, LPDWORD lpdwtype)
2578 LPBYTE lpvalue;
2579 HKEY hrootkey = NULL;
2580 DWORD cbData;
2582 /* Check both the current user and the local machine to see if
2583 we have any resources. */
2585 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2587 lpvalue = NULL;
2589 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2590 && (lpvalue = xmalloc (cbData)) != NULL
2591 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2593 RegCloseKey (hrootkey);
2594 return (lpvalue);
2597 xfree (lpvalue);
2599 RegCloseKey (hrootkey);
2602 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2604 lpvalue = NULL;
2606 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2607 && (lpvalue = xmalloc (cbData)) != NULL
2608 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2610 RegCloseKey (hrootkey);
2611 return (lpvalue);
2614 xfree (lpvalue);
2616 RegCloseKey (hrootkey);
2619 return (NULL);
2622 /* The argv[] array holds ANSI-encoded strings, and so this function
2623 works with ANS_encoded strings. */
2624 void
2625 init_environment (char ** argv)
2627 static const char * const tempdirs[] = {
2628 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2631 int i;
2633 const int imax = ARRAYELTS (tempdirs);
2635 /* Implementation note: This function explicitly works with ANSI
2636 file names, not with UTF-8 encoded file names. This is because
2637 this function pushes variables into the Emacs's environment, and
2638 the environment variables are always assumed to be in the
2639 locale-specific encoding. Do NOT call any functions that accept
2640 UTF-8 file names from this function! */
2642 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2643 temporary files and assume "/tmp" if $TMPDIR is unset, which
2644 will break on DOS/Windows. Refuse to work if we cannot find
2645 a directory, not even "c:/", usable for that purpose. */
2646 for (i = 0; i < imax ; i++)
2648 const char *tmp = tempdirs[i];
2650 if (*tmp == '$')
2651 tmp = getenv (tmp + 1);
2652 /* Note that `access' can lie to us if the directory resides on a
2653 read-only filesystem, like CD-ROM or a write-protected floppy.
2654 The only way to be really sure is to actually create a file and
2655 see if it succeeds. But I think that's too much to ask. */
2657 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2658 if (tmp && sys_access (tmp, D_OK) == 0)
2660 char * var = alloca (strlen (tmp) + 8);
2661 sprintf (var, "TMPDIR=%s", tmp);
2662 _putenv (strdup (var));
2663 break;
2666 if (i >= imax)
2667 cmd_error_internal
2668 (Fcons (Qerror,
2669 Fcons (build_string ("no usable temporary directories found!!"),
2670 Qnil)),
2671 "While setting TMPDIR: ");
2673 /* Check for environment variables and use registry settings if they
2674 don't exist. Fallback on default values where applicable. */
2676 int i;
2677 LPBYTE lpval;
2678 DWORD dwType;
2679 char locale_name[32];
2680 char default_home[MAX_PATH];
2681 int appdata = 0;
2683 static const struct env_entry
2685 const char * name;
2686 const char * def_value;
2687 } dflt_envvars[] =
2689 /* If the default value is NULL, we will use the value from the
2690 outside environment or the Registry, but will not push the
2691 variable into the Emacs environment if it is defined neither
2692 in the Registry nor in the outside environment. */
2693 {"HOME", "C:/"},
2694 {"PRELOAD_WINSOCK", NULL},
2695 {"emacs_dir", "C:/emacs"},
2696 {"EMACSLOADPATH", NULL},
2697 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2698 {"EMACSDATA", NULL},
2699 {"EMACSPATH", NULL},
2700 {"INFOPATH", NULL},
2701 {"EMACSDOC", NULL},
2702 {"TERM", "cmd"},
2703 {"LANG", NULL},
2706 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2708 /* We need to copy dflt_envvars[] and work on the copy because we
2709 don't want the dumped Emacs to inherit the values of
2710 environment variables we saw during dumping (which could be on
2711 a different system). The defaults above must be left intact. */
2712 struct env_entry env_vars[N_ENV_VARS];
2714 for (i = 0; i < N_ENV_VARS; i++)
2715 env_vars[i] = dflt_envvars[i];
2717 /* For backwards compatibility, check if a .emacs file exists in C:/
2718 If not, then we can try to default to the appdata directory under the
2719 user's profile, which is more likely to be writable. */
2720 if (sys_access ("C:/.emacs", F_OK) != 0)
2722 HRESULT profile_result;
2723 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2724 of Windows 95 and NT4 that have not been updated to include
2725 MSIE 5. */
2726 ShGetFolderPath_fn get_folder_path;
2727 get_folder_path = (ShGetFolderPath_fn)
2728 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2730 if (get_folder_path != NULL)
2732 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2733 0, default_home);
2735 /* If we can't get the appdata dir, revert to old behavior. */
2736 if (profile_result == S_OK)
2738 env_vars[0].def_value = default_home;
2739 appdata = 1;
2744 /* Get default locale info and use it for LANG. */
2745 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2746 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2747 locale_name, sizeof (locale_name)))
2749 for (i = 0; i < N_ENV_VARS; i++)
2751 if (strcmp (env_vars[i].name, "LANG") == 0)
2753 env_vars[i].def_value = locale_name;
2754 break;
2759 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2761 /* Treat emacs_dir specially: set it unconditionally based on our
2762 location. */
2764 char *p;
2765 char modname[MAX_PATH];
2767 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2768 emacs_abort ();
2769 if ((p = _mbsrchr (modname, '\\')) == NULL)
2770 emacs_abort ();
2771 *p = 0;
2773 if ((p = _mbsrchr (modname, '\\'))
2774 /* From bin means installed Emacs, from src means uninstalled. */
2775 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2777 char buf[SET_ENV_BUF_SIZE];
2778 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2780 *p = 0;
2781 for (p = modname; *p; p = CharNext (p))
2782 if (*p == '\\') *p = '/';
2784 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2785 _putenv (strdup (buf));
2786 /* If we are running from the Posix-like build tree, define
2787 SHELL to point to our own cmdproxy. The loop below will
2788 then disregard PATH_EXEC and the default value. */
2789 if (within_build_tree)
2791 _snprintf (buf, sizeof (buf) - 1,
2792 "SHELL=%s/nt/cmdproxy.exe", modname);
2793 _putenv (strdup (buf));
2798 for (i = 0; i < N_ENV_VARS; i++)
2800 if (!getenv (env_vars[i].name))
2802 int dont_free = 0;
2803 char bufc[SET_ENV_BUF_SIZE];
2805 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2806 /* Also ignore empty environment variables. */
2807 || *lpval == 0)
2809 xfree (lpval);
2810 dont_free = 1;
2811 if (strcmp (env_vars[i].name, "SHELL") == 0)
2813 /* Look for cmdproxy.exe in every directory in
2814 PATH_EXEC. FIXME: This does not find cmdproxy
2815 in nt/ when we run uninstalled. */
2816 char fname[MAX_PATH];
2817 const char *pstart = PATH_EXEC, *pend;
2819 do {
2820 pend = _mbschr (pstart, ';');
2821 if (!pend)
2822 pend = pstart + strlen (pstart);
2823 /* Be defensive against series of ;;; characters. */
2824 if (pend > pstart)
2826 strncpy (fname, pstart, pend - pstart);
2827 fname[pend - pstart] = '/';
2828 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2829 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2830 sizeof (bufc));
2831 if (sys_access (bufc, F_OK) == 0)
2833 lpval = bufc;
2834 dwType = REG_SZ;
2835 break;
2838 if (*pend)
2839 pstart = pend + 1;
2840 else
2841 pstart = pend;
2842 if (!*pstart)
2844 /* If not found in any directory, use the
2845 default as the last resort. */
2846 lpval = (char *)env_vars[i].def_value;
2847 dwType = REG_EXPAND_SZ;
2849 } while (*pstart);
2851 else
2853 lpval = (char *)env_vars[i].def_value;
2854 dwType = REG_EXPAND_SZ;
2856 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2857 Vdelayed_warnings_list
2858 = Fcons
2859 (listn (CONSTYPE_HEAP, 2,
2860 intern ("initialization"), build_string
2861 ("Use of `C:\\.emacs' without defining `HOME'\n"
2862 "in the environment is deprecated, "
2863 "see `Windows HOME' in the Emacs manual.")),
2864 Vdelayed_warnings_list);
2867 if (lpval)
2869 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2871 if (dwType == REG_EXPAND_SZ)
2872 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2873 else if (dwType == REG_SZ)
2874 strcpy (buf1, (char *)lpval);
2875 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2877 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2878 buf1);
2879 _putenv (strdup (buf2));
2882 if (!dont_free)
2883 xfree (lpval);
2889 /* Rebuild system configuration to reflect invoking system. */
2890 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2892 /* Another special case: on NT, the PATH variable is actually named
2893 "Path" although cmd.exe (perhaps NT itself) arranges for
2894 environment variable lookup and setting to be case insensitive.
2895 However, Emacs assumes a fully case sensitive environment, so we
2896 need to change "Path" to "PATH" to match the expectations of
2897 various elisp packages. We do this by the sneaky method of
2898 modifying the string in the C runtime environ entry.
2900 The same applies to COMSPEC. */
2902 char ** envp;
2903 const char *path = "PATH=";
2904 int path_len = strlen (path);
2905 const char *comspec = "COMSPEC=";
2906 int comspec_len = strlen (comspec);
2908 for (envp = environ; *envp; envp++)
2909 if (_strnicmp (*envp, path, path_len) == 0)
2910 memcpy (*envp, path, path_len);
2911 else if (_strnicmp (*envp, comspec, comspec_len) == 0)
2912 memcpy (*envp, comspec, comspec_len);
2914 /* Make the same modification to `process-environment' which has
2915 already been initialized in set_initial_environment. */
2916 for (Lisp_Object env = Vprocess_environment; CONSP (env); env = XCDR (env))
2918 Lisp_Object entry = XCAR (env);
2919 if (_strnicmp (SDATA (entry), path, path_len) == 0)
2920 for (int i = 0; i < path_len; i++)
2921 SSET (entry, i, path[i]);
2922 else if (_strnicmp (SDATA (entry), comspec, comspec_len) == 0)
2923 for (int i = 0; i < comspec_len; i++)
2924 SSET (entry, i, comspec[i]);
2928 /* Remember the initial working directory for getcwd. */
2929 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2930 Does it matter anywhere in Emacs? */
2931 if (w32_unicode_filenames)
2933 wchar_t wstartup_dir[MAX_PATH];
2935 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2936 emacs_abort ();
2937 filename_from_utf16 (wstartup_dir, startup_dir);
2939 else
2941 char astartup_dir[MAX_PATH];
2943 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2944 emacs_abort ();
2945 filename_from_ansi (astartup_dir, startup_dir);
2949 static char modname[MAX_PATH];
2951 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2952 emacs_abort ();
2953 argv[0] = modname;
2956 /* Determine if there is a middle mouse button, to allow parse_button
2957 to decide whether right mouse events should be mouse-2 or
2958 mouse-3. */
2959 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2961 init_user_info ();
2964 /* Called from expand-file-name when default-directory is not a string. */
2966 char *
2967 emacs_root_dir (void)
2969 static char root_dir[MAX_UTF8_PATH];
2970 const char *p;
2972 p = getenv ("emacs_dir");
2973 if (p == NULL)
2974 emacs_abort ();
2975 filename_from_ansi (p, root_dir);
2976 root_dir[parse_root (root_dir, NULL)] = '\0';
2977 dostounix_filename (root_dir);
2978 return root_dir;
2981 /* Emulate fdutimens. */
2983 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2984 TIMESPEC[0] and TIMESPEC[1], respectively.
2985 FD must be either negative -- in which case it is ignored --
2986 or a file descriptor that is open on FILE.
2987 If FD is nonnegative, then FILE can be NULL, which means
2988 use just futimes instead of utimes.
2989 If TIMESPEC is null, FAIL.
2990 Return 0 on success, -1 (setting errno) on failure. */
2993 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2995 if (!timespec)
2997 errno = ENOSYS;
2998 return -1;
3000 if (fd < 0 && !file)
3002 errno = EBADF;
3003 return -1;
3005 /* _futime's prototype defines 2nd arg as having the type 'struct
3006 _utimbuf', while utime needs to accept 'struct utimbuf' for
3007 compatibility with Posix. So we need to use 2 different (but
3008 equivalent) types to avoid compiler warnings, sigh. */
3009 if (fd >= 0)
3011 struct _utimbuf _ut;
3013 _ut.actime = timespec[0].tv_sec;
3014 _ut.modtime = timespec[1].tv_sec;
3015 return _futime (fd, &_ut);
3017 else
3019 struct utimbuf ut;
3021 ut.actime = timespec[0].tv_sec;
3022 ut.modtime = timespec[1].tv_sec;
3023 /* Call 'utime', which is implemented below, not the MS library
3024 function, which fails on directories. */
3025 return utime (file, &ut);
3030 /* ------------------------------------------------------------------------- */
3031 /* IO support and wrapper functions for the Windows API. */
3032 /* ------------------------------------------------------------------------- */
3034 /* Place a wrapper around the MSVC version of ctime. It returns NULL
3035 on network directories, so we handle that case here.
3036 (Ulrich Leodolter, 1/11/95). */
3037 char *
3038 sys_ctime (const time_t *t)
3040 char *str = (char *) ctime (t);
3041 return (str ? str : (char *)"Sun Jan 01 00:00:00 1970");
3044 /* Emulate sleep...we could have done this with a define, but that
3045 would necessitate including windows.h in the files that used it.
3046 This is much easier. */
3047 void
3048 sys_sleep (int seconds)
3050 Sleep (seconds * 1000);
3053 /* Internal MSVC functions for low-level descriptor munging */
3054 extern int __cdecl _set_osfhnd (int fd, long h);
3055 extern int __cdecl _free_osfhnd (int fd);
3057 /* parallel array of private info on file handles */
3058 filedesc fd_info [ MAXDESC ];
3060 typedef struct volume_info_data {
3061 struct volume_info_data * next;
3063 /* time when info was obtained */
3064 DWORD timestamp;
3066 /* actual volume info */
3067 char * root_dir;
3068 DWORD serialnum;
3069 DWORD maxcomp;
3070 DWORD flags;
3071 char * name;
3072 char * type;
3073 } volume_info_data;
3075 /* Global referenced by various functions. */
3076 static volume_info_data volume_info;
3078 /* Vector to indicate which drives are local and fixed (for which cached
3079 data never expires). */
3080 static BOOL fixed_drives[26];
3082 /* Consider cached volume information to be stale if older than 10s,
3083 at least for non-local drives. Info for fixed drives is never stale. */
3084 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3085 #define VOLINFO_STILL_VALID( root_dir, info ) \
3086 ( ( isalpha (root_dir[0]) && \
3087 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3088 || GetTickCount () - info->timestamp < 10000 )
3090 /* Cache support functions. */
3092 /* Simple linked list with linear search is sufficient. */
3093 static volume_info_data *volume_cache = NULL;
3095 static volume_info_data *
3096 lookup_volume_info (char * root_dir)
3098 volume_info_data * info;
3100 for (info = volume_cache; info; info = info->next)
3101 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3102 break;
3103 return info;
3106 static void
3107 add_volume_info (char * root_dir, volume_info_data * info)
3109 info->root_dir = xstrdup (root_dir);
3110 unixtodos_filename (info->root_dir);
3111 info->next = volume_cache;
3112 volume_cache = info;
3116 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3117 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3118 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3119 static volume_info_data *
3120 GetCachedVolumeInformation (char * root_dir)
3122 volume_info_data * info;
3123 char default_root[ MAX_UTF8_PATH ];
3124 char name[MAX_PATH+1];
3125 char type[MAX_PATH+1];
3127 /* NULL for root_dir means use root from current directory. */
3128 if (root_dir == NULL)
3130 if (w32_unicode_filenames)
3132 wchar_t curdirw[MAX_PATH];
3134 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3135 return NULL;
3136 filename_from_utf16 (curdirw, default_root);
3138 else
3140 char curdira[MAX_PATH];
3142 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3143 return NULL;
3144 filename_from_ansi (curdira, default_root);
3146 parse_root (default_root, (const char **)&root_dir);
3147 *root_dir = 0;
3148 root_dir = default_root;
3151 /* Local fixed drives can be cached permanently. Removable drives
3152 cannot be cached permanently, since the volume name and serial
3153 number (if nothing else) can change. Remote drives should be
3154 treated as if they are removable, since there is no sure way to
3155 tell whether they are or not. Also, the UNC association of drive
3156 letters mapped to remote volumes can be changed at any time (even
3157 by other processes) without notice.
3159 As a compromise, so we can benefit from caching info for remote
3160 volumes, we use a simple expiry mechanism to invalidate cache
3161 entries that are more than ten seconds old. */
3163 #if 0
3164 /* No point doing this, because WNetGetConnection is even slower than
3165 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3166 GetDriveType is about the only call of this type which does not
3167 involve network access, and so is extremely quick). */
3169 /* Map drive letter to UNC if remote. */
3170 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3172 char remote_name[ 256 ];
3173 char drive[3] = { root_dir[0], ':' };
3175 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3176 == NO_ERROR)
3177 /* do something */ ;
3179 #endif
3181 info = lookup_volume_info (root_dir);
3183 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3185 DWORD serialnum;
3186 DWORD maxcomp;
3187 DWORD flags;
3189 /* Info is not cached, or is stale. */
3190 if (w32_unicode_filenames)
3192 wchar_t root_w[MAX_PATH];
3193 wchar_t name_w[MAX_PATH+1];
3194 wchar_t type_w[MAX_PATH+1];
3196 filename_to_utf16 (root_dir, root_w);
3197 if (!GetVolumeInformationW (root_w,
3198 name_w, sizeof (name_w),
3199 &serialnum,
3200 &maxcomp,
3201 &flags,
3202 type_w, sizeof (type_w)))
3203 return NULL;
3204 /* Hmm... not really 100% correct, as these 2 are not file
3205 names... */
3206 filename_from_utf16 (name_w, name);
3207 filename_from_utf16 (type_w, type);
3209 else
3211 char root_a[MAX_PATH];
3212 char name_a[MAX_PATH+1];
3213 char type_a[MAX_PATH+1];
3215 filename_to_ansi (root_dir, root_a);
3216 if (!GetVolumeInformationA (root_a,
3217 name_a, sizeof (name_a),
3218 &serialnum,
3219 &maxcomp,
3220 &flags,
3221 type_a, sizeof (type_a)))
3222 return NULL;
3223 filename_from_ansi (name_a, name);
3224 filename_from_ansi (type_a, type);
3227 /* Cache the volume information for future use, overwriting existing
3228 entry if present. */
3229 if (info == NULL)
3231 info = xmalloc (sizeof (volume_info_data));
3232 add_volume_info (root_dir, info);
3234 else
3236 xfree (info->name);
3237 xfree (info->type);
3240 info->name = xstrdup (name);
3241 unixtodos_filename (info->name);
3242 info->serialnum = serialnum;
3243 info->maxcomp = maxcomp;
3244 info->flags = flags;
3245 info->type = xstrdup (type);
3246 info->timestamp = GetTickCount ();
3249 return info;
3252 /* Get information on the volume where NAME is held; set path pointer to
3253 start of pathname in NAME (past UNC header\volume header if present),
3254 if pPath is non-NULL.
3256 Note: if NAME includes symlinks, the information is for the volume
3257 of the symlink, not of its target. That's because, even though
3258 GetVolumeInformation returns information about the symlink target
3259 of its argument, we only pass the root directory to
3260 GetVolumeInformation, not the full NAME. */
3261 static int
3262 get_volume_info (const char * name, const char ** pPath)
3264 char temp[MAX_UTF8_PATH];
3265 char *rootname = NULL; /* default to current volume */
3266 volume_info_data * info;
3267 int root_len = parse_root (name, pPath);
3269 if (name == NULL)
3270 return FALSE;
3272 /* Copy the root name of the volume, if given. */
3273 if (root_len)
3275 strncpy (temp, name, root_len);
3276 temp[root_len] = '\0';
3277 unixtodos_filename (temp);
3278 rootname = temp;
3281 info = GetCachedVolumeInformation (rootname);
3282 if (info != NULL)
3284 /* Set global referenced by other functions. */
3285 volume_info = *info;
3286 return TRUE;
3288 return FALSE;
3291 /* Determine if volume is FAT format (ie. only supports short 8.3
3292 names); also set path pointer to start of pathname in name, if
3293 pPath is non-NULL. */
3294 static int
3295 is_fat_volume (const char * name, const char ** pPath)
3297 if (get_volume_info (name, pPath))
3298 return (volume_info.maxcomp == 12);
3299 return FALSE;
3302 /* Convert all slashes in a filename to backslashes, and map filename
3303 to a valid 8.3 name if necessary. The result is a pointer to a
3304 static buffer, so CAVEAT EMPTOR! */
3305 const char *map_w32_filename (const char *, const char **);
3307 const char *
3308 map_w32_filename (const char * name, const char ** pPath)
3310 static char shortname[MAX_UTF8_PATH];
3311 char * str = shortname;
3312 char c;
3313 char * path;
3314 const char * save_name = name;
3316 if (strlen (name) >= sizeof (shortname))
3318 /* Return a filename which will cause callers to fail. */
3319 strcpy (shortname, "?");
3320 return shortname;
3323 if (!fatal_error_in_progress /* disable fancy processing during crash */
3324 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3326 register int left = 8; /* maximum number of chars in part */
3327 register int extn = 0; /* extension added? */
3328 register int dots = 2; /* maximum number of dots allowed */
3330 while (name < path)
3331 *str++ = *name++; /* skip past UNC header */
3333 while ((c = *name++))
3335 switch ( c )
3337 case ':':
3338 case '\\':
3339 case '/':
3340 *str++ = (c == ':' ? ':' : '\\');
3341 extn = 0; /* reset extension flags */
3342 dots = 2; /* max 2 dots */
3343 left = 8; /* max length 8 for main part */
3344 break;
3345 case '.':
3346 if ( dots )
3348 /* Convert path components of the form .xxx to _xxx,
3349 but leave . and .. as they are. This allows .emacs
3350 to be read as _emacs, for example. */
3352 if (! *name ||
3353 *name == '.' ||
3354 IS_DIRECTORY_SEP (*name))
3356 *str++ = '.';
3357 dots--;
3359 else
3361 *str++ = '_';
3362 left--;
3363 dots = 0;
3366 else if ( !extn )
3368 *str++ = '.';
3369 extn = 1; /* we've got an extension */
3370 left = 3; /* 3 chars in extension */
3372 else
3374 /* any embedded dots after the first are converted to _ */
3375 *str++ = '_';
3377 break;
3378 case '~':
3379 case '#': /* don't lose these, they're important */
3380 if ( ! left )
3381 str[-1] = c; /* replace last character of part */
3382 /* FALLTHRU */
3383 default:
3384 if ( left && 'A' <= c && c <= 'Z' )
3386 *str++ = tolower (c); /* map to lower case (looks nicer) */
3387 left--;
3388 dots = 0; /* started a path component */
3390 break;
3393 *str = '\0';
3395 else
3397 strcpy (shortname, name);
3398 unixtodos_filename (shortname);
3401 if (pPath)
3402 *pPath = shortname + (path - save_name);
3404 return shortname;
3407 static int
3408 is_exec (const char * name)
3410 char * p = strrchr (name, '.');
3411 return
3412 (p != NULL
3413 && (xstrcasecmp (p, ".exe") == 0 ||
3414 xstrcasecmp (p, ".com") == 0 ||
3415 xstrcasecmp (p, ".bat") == 0 ||
3416 xstrcasecmp (p, ".cmd") == 0));
3419 /* Emulate the Unix directory procedures opendir, closedir, and
3420 readdir. We rename them to sys_* names because some versions of
3421 MinGW startup code call opendir and readdir to glob wildcards, and
3422 the code that calls them doesn't grok UTF-8 encoded file names we
3423 produce in dirent->d_name[]. */
3425 struct dirent dir_static; /* simulated directory contents */
3426 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3427 static int dir_is_fat;
3428 static char dir_pathname[MAX_UTF8_PATH];
3429 static WIN32_FIND_DATAW dir_find_data_w;
3430 static WIN32_FIND_DATAA dir_find_data_a;
3431 #define DIR_FIND_DATA_W 1
3432 #define DIR_FIND_DATA_A 2
3433 static int last_dir_find_data = -1;
3435 /* Support shares on a network resource as subdirectories of a read-only
3436 root directory. */
3437 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3438 static HANDLE open_unc_volume (const char *);
3439 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3440 static void close_unc_volume (HANDLE);
3442 DIR *
3443 sys_opendir (const char *filename)
3445 DIR *dirp;
3447 /* Opening is done by FindFirstFile. However, a read is inherent to
3448 this operation, so we defer the open until read time. */
3450 if (dir_find_handle != INVALID_HANDLE_VALUE)
3451 return NULL;
3452 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3453 return NULL;
3455 /* Note: We don't support traversal of UNC volumes via symlinks.
3456 Doing so would mean punishing 99.99% of use cases by resolving
3457 all the possible symlinks in FILENAME, recursively. */
3458 if (is_unc_volume (filename))
3460 wnet_enum_handle = open_unc_volume (filename);
3461 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3462 return NULL;
3465 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3466 return NULL;
3468 dirp->dd_fd = 0;
3469 dirp->dd_loc = 0;
3470 dirp->dd_size = 0;
3472 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3473 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3474 /* Note: We don't support symlinks to file names on FAT volumes.
3475 Doing so would mean punishing 99.99% of use cases by resolving
3476 all the possible symlinks in FILENAME, recursively. */
3477 dir_is_fat = is_fat_volume (filename, NULL);
3479 return dirp;
3482 void
3483 sys_closedir (DIR *dirp)
3485 /* If we have a find-handle open, close it. */
3486 if (dir_find_handle != INVALID_HANDLE_VALUE)
3488 FindClose (dir_find_handle);
3489 dir_find_handle = INVALID_HANDLE_VALUE;
3491 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3493 close_unc_volume (wnet_enum_handle);
3494 wnet_enum_handle = INVALID_HANDLE_VALUE;
3496 xfree ((char *) dirp);
3499 struct dirent *
3500 sys_readdir (DIR *dirp)
3502 int downcase = !NILP (Vw32_downcase_file_names);
3504 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3506 if (!read_unc_volume (wnet_enum_handle,
3507 dir_find_data_w.cFileName,
3508 dir_find_data_a.cFileName,
3509 MAX_PATH))
3510 return NULL;
3512 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3513 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3515 char filename[MAX_UTF8_PATH];
3516 int ln;
3517 bool last_slash = true;
3519 /* Note: We don't need to worry about dir_pathname being longer
3520 than MAX_UTF8_PATH, as sys_opendir already took care of that
3521 when it called map_w32_filename: that function will put a "?"
3522 in its return value in that case, thus failing all the calls
3523 below. */
3524 strcpy (filename, dir_pathname);
3525 ln = strlen (filename);
3526 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3527 last_slash = false;
3529 /* Note: No need to resolve symlinks in FILENAME, because
3530 FindFirst opens the directory that is the target of a
3531 symlink. */
3532 if (w32_unicode_filenames)
3534 wchar_t fnw[MAX_PATH + 2];
3536 filename_to_utf16 (filename, fnw);
3537 if (!last_slash)
3538 wcscat (fnw, L"\\");
3539 wcscat (fnw, L"*");
3540 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3542 else
3544 char fna[MAX_PATH + 2];
3546 filename_to_ansi (filename, fna);
3547 if (!last_slash)
3548 strcat (fna, "\\");
3549 strcat (fna, "*");
3550 /* If FILENAME is not representable by the current ANSI
3551 codepage, we don't want FindFirstFileA to interpret the
3552 '?' characters as a wildcard. */
3553 if (_mbspbrk (fna, "?"))
3554 dir_find_handle = INVALID_HANDLE_VALUE;
3555 else
3556 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3559 if (dir_find_handle == INVALID_HANDLE_VALUE)
3561 /* Any changes in the value of errno here should be in sync
3562 with what directory_files_internal does when it calls
3563 readdir. */
3564 switch (GetLastError ())
3566 /* Windows uses this value when FindFirstFile finds no
3567 files that match the wildcard. This is not supposed
3568 to happen, since our wildcard is "*", but just in
3569 case, if there's some weird empty directory with not
3570 even "." and ".." entries... */
3571 case ERROR_FILE_NOT_FOUND:
3572 errno = 0;
3573 /* FALLTHRU */
3574 default:
3575 break;
3576 case ERROR_ACCESS_DENIED:
3577 case ERROR_NETWORK_ACCESS_DENIED:
3578 errno = EACCES;
3579 break;
3580 case ERROR_PATH_NOT_FOUND:
3581 case ERROR_INVALID_DRIVE:
3582 case ERROR_NOT_READY:
3583 case ERROR_BAD_NETPATH:
3584 case ERROR_BAD_NET_NAME:
3585 errno = ENOENT;
3586 break;
3588 return NULL;
3591 else if (w32_unicode_filenames)
3593 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3595 errno = 0;
3596 return NULL;
3599 else
3601 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3603 errno = 0;
3604 return NULL;
3608 /* Emacs never uses this value, so don't bother making it match
3609 value returned by stat(). */
3610 dir_static.d_ino = 1;
3612 if (w32_unicode_filenames)
3614 if (downcase || dir_is_fat)
3616 wchar_t tem[MAX_PATH];
3618 wcscpy (tem, dir_find_data_w.cFileName);
3619 CharLowerW (tem);
3620 filename_from_utf16 (tem, dir_static.d_name);
3622 else
3623 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3624 last_dir_find_data = DIR_FIND_DATA_W;
3626 else
3628 char tem[MAX_PATH];
3630 /* If the file name in cFileName[] includes `?' characters, it
3631 means the original file name used characters that cannot be
3632 represented by the current ANSI codepage. To avoid total
3633 lossage, retrieve the short 8+3 alias of the long file
3634 name. */
3635 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3637 strcpy (tem, dir_find_data_a.cAlternateFileName);
3638 /* 8+3 aliases are returned in all caps, which could break
3639 various alists that look at filenames' extensions. */
3640 downcase = 1;
3642 else if (downcase || dir_is_fat)
3643 strcpy (tem, dir_find_data_a.cFileName);
3644 else
3645 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3646 if (downcase || dir_is_fat)
3648 _mbslwr (tem);
3649 filename_from_ansi (tem, dir_static.d_name);
3651 last_dir_find_data = DIR_FIND_DATA_A;
3654 dir_static.d_namlen = strlen (dir_static.d_name);
3655 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3656 dir_static.d_namlen - dir_static.d_namlen % 4;
3658 return &dir_static;
3661 static HANDLE
3662 open_unc_volume (const char *path)
3664 const char *fn = map_w32_filename (path, NULL);
3665 DWORD result;
3666 HANDLE henum;
3668 if (w32_unicode_filenames)
3670 NETRESOURCEW nrw;
3671 wchar_t fnw[MAX_PATH];
3673 nrw.dwScope = RESOURCE_GLOBALNET;
3674 nrw.dwType = RESOURCETYPE_DISK;
3675 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3676 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3677 nrw.lpLocalName = NULL;
3678 filename_to_utf16 (fn, fnw);
3679 nrw.lpRemoteName = fnw;
3680 nrw.lpComment = NULL;
3681 nrw.lpProvider = NULL;
3683 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3684 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3686 else
3688 NETRESOURCEA nra;
3689 char fna[MAX_PATH];
3691 nra.dwScope = RESOURCE_GLOBALNET;
3692 nra.dwType = RESOURCETYPE_DISK;
3693 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3694 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3695 nra.lpLocalName = NULL;
3696 filename_to_ansi (fn, fna);
3697 nra.lpRemoteName = fna;
3698 nra.lpComment = NULL;
3699 nra.lpProvider = NULL;
3701 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3702 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3704 if (result == NO_ERROR)
3705 return henum;
3706 else
3708 /* Make sure directory_files_internal reports a sensible error. */
3709 errno = ENOENT;
3710 return INVALID_HANDLE_VALUE;
3714 static void *
3715 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3717 DWORD count;
3718 int result;
3719 char *buffer;
3720 DWORD bufsize = 512;
3721 void *retval;
3723 count = 1;
3724 if (w32_unicode_filenames)
3726 wchar_t *ptrw;
3728 bufsize *= 2;
3729 buffer = alloca (bufsize);
3730 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3731 if (result != NO_ERROR)
3732 return NULL;
3733 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3734 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3735 ptrw += 2;
3736 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3737 ptrw++;
3738 wcsncpy (fname_w, ptrw, size);
3739 retval = fname_w;
3741 else
3743 int dbcs_p = max_filename_mbslen () > 1;
3744 char *ptra;
3746 buffer = alloca (bufsize);
3747 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3748 if (result != NO_ERROR)
3749 return NULL;
3750 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3751 ptra += 2;
3752 if (!dbcs_p)
3753 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3754 else
3756 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3757 ptra = CharNextExA (file_name_codepage, ptra, 0);
3759 ptra++;
3760 strncpy (fname_a, ptra, size);
3761 retval = fname_a;
3764 return retval;
3767 static void
3768 close_unc_volume (HANDLE henum)
3770 if (henum != INVALID_HANDLE_VALUE)
3771 WNetCloseEnum (henum);
3774 static DWORD
3775 unc_volume_file_attributes (const char *path)
3777 HANDLE henum;
3778 DWORD attrs;
3780 henum = open_unc_volume (path);
3781 if (henum == INVALID_HANDLE_VALUE)
3782 return -1;
3784 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3786 close_unc_volume (henum);
3788 return attrs;
3791 /* Ensure a network connection is authenticated. */
3792 static void
3793 logon_network_drive (const char *path)
3795 char share[MAX_UTF8_PATH];
3796 int n_slashes;
3797 char drive[4];
3798 UINT drvtype;
3799 char *p;
3800 DWORD val;
3802 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3803 drvtype = DRIVE_REMOTE;
3804 else if (path[0] == '\0' || path[1] != ':')
3805 drvtype = GetDriveType (NULL);
3806 else
3808 drive[0] = path[0];
3809 drive[1] = ':';
3810 drive[2] = '\\';
3811 drive[3] = '\0';
3812 drvtype = GetDriveType (drive);
3815 /* Only logon to networked drives. */
3816 if (drvtype != DRIVE_REMOTE)
3817 return;
3819 n_slashes = 2;
3820 strncpy (share, path, MAX_UTF8_PATH);
3821 /* Truncate to just server and share name. */
3822 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3824 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3826 *p = '\0';
3827 break;
3831 if (w32_unicode_filenames)
3833 NETRESOURCEW resourcew;
3834 wchar_t share_w[MAX_PATH];
3836 resourcew.dwScope = RESOURCE_GLOBALNET;
3837 resourcew.dwType = RESOURCETYPE_DISK;
3838 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3839 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3840 resourcew.lpLocalName = NULL;
3841 filename_to_utf16 (share, share_w);
3842 resourcew.lpRemoteName = share_w;
3843 resourcew.lpProvider = NULL;
3845 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3847 else
3849 NETRESOURCEA resourcea;
3850 char share_a[MAX_PATH];
3852 resourcea.dwScope = RESOURCE_GLOBALNET;
3853 resourcea.dwType = RESOURCETYPE_DISK;
3854 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3855 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3856 resourcea.lpLocalName = NULL;
3857 filename_to_ansi (share, share_a);
3858 resourcea.lpRemoteName = share_a;
3859 resourcea.lpProvider = NULL;
3861 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3864 switch (val)
3866 case NO_ERROR:
3867 case ERROR_ALREADY_ASSIGNED:
3868 break;
3869 case ERROR_ACCESS_DENIED:
3870 case ERROR_LOGON_FAILURE:
3871 errno = EACCES;
3872 break;
3873 case ERROR_BUSY:
3874 errno = EAGAIN;
3875 break;
3876 case ERROR_BAD_NET_NAME:
3877 case ERROR_NO_NET_OR_BAD_PATH:
3878 case ERROR_NO_NETWORK:
3879 case ERROR_CANCELLED:
3880 default:
3881 errno = ENOENT;
3882 break;
3886 /* Emulate faccessat(2). */
3888 faccessat (int dirfd, const char * path, int mode, int flags)
3890 DWORD attributes;
3892 if (dirfd != AT_FDCWD
3893 && !(IS_DIRECTORY_SEP (path[0])
3894 || IS_DEVICE_SEP (path[1])))
3896 errno = EBADF;
3897 return -1;
3900 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3901 newer versions blow up when passed D_OK. */
3902 path = map_w32_filename (path, NULL);
3903 /* If the last element of PATH is a symlink, we need to resolve it
3904 to get the attributes of its target file. Note: any symlinks in
3905 PATH elements other than the last one are transparently resolved
3906 by GetFileAttributes below. */
3907 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3908 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3909 path = chase_symlinks (path);
3911 if (w32_unicode_filenames)
3913 wchar_t path_w[MAX_PATH];
3915 filename_to_utf16 (path, path_w);
3916 attributes = GetFileAttributesW (path_w);
3918 else
3920 char path_a[MAX_PATH];
3922 filename_to_ansi (path, path_a);
3923 attributes = GetFileAttributesA (path_a);
3926 if (attributes == -1)
3928 DWORD w32err = GetLastError ();
3930 switch (w32err)
3932 case ERROR_INVALID_NAME:
3933 case ERROR_BAD_PATHNAME:
3934 if (is_unc_volume (path))
3936 attributes = unc_volume_file_attributes (path);
3937 if (attributes == -1)
3939 errno = EACCES;
3940 return -1;
3942 goto check_attrs;
3944 /* FALLTHROUGH */
3945 case ERROR_FILE_NOT_FOUND:
3946 case ERROR_BAD_NETPATH:
3947 errno = ENOENT;
3948 break;
3949 default:
3950 errno = EACCES;
3951 break;
3953 return -1;
3956 check_attrs:
3957 if ((mode & X_OK) != 0
3958 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3960 errno = EACCES;
3961 return -1;
3963 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3965 errno = EACCES;
3966 return -1;
3968 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3970 errno = EACCES;
3971 return -1;
3973 return 0;
3976 /* A special test for DIRNAME being a directory accessible by the
3977 current user. This is needed because the security permissions in
3978 directory's ACLs are not visible in the Posix-style mode bits
3979 returned by 'stat' and in attributes returned by GetFileAttributes.
3980 So a directory would seem like it's readable by the current user,
3981 but will in fact error out with EACCES when they actually try. */
3983 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3985 char pattern[MAX_UTF8_PATH];
3986 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3987 HANDLE dh;
3989 /* Network volumes need a different reading method. */
3990 if (is_unc_volume (dirname))
3992 void *read_result = NULL;
3993 wchar_t fnw[MAX_PATH];
3994 char fna[MAX_PATH];
3996 dh = open_unc_volume (dirname);
3997 if (dh != INVALID_HANDLE_VALUE)
3999 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
4000 close_unc_volume (dh);
4002 /* Treat empty volumes as accessible. */
4003 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
4006 /* Note: map_w32_filename makes sure DIRNAME is not longer than
4007 MAX_UTF8_PATH. */
4008 strcpy (pattern, map_w32_filename (dirname, NULL));
4010 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
4011 opens the directory that is the target of a symlink. */
4012 if (w32_unicode_filenames)
4014 wchar_t pat_w[MAX_PATH + 2];
4015 WIN32_FIND_DATAW dfd_w;
4017 filename_to_utf16 (pattern, pat_w);
4018 if (!last_slash)
4019 wcscat (pat_w, L"\\");
4020 wcscat (pat_w, L"*");
4021 dh = FindFirstFileW (pat_w, &dfd_w);
4023 else
4025 char pat_a[MAX_PATH + 2];
4026 WIN32_FIND_DATAA dfd_a;
4028 filename_to_ansi (pattern, pat_a);
4029 if (!last_slash)
4030 strcpy (pat_a, "\\");
4031 strcat (pat_a, "*");
4032 /* In case DIRNAME cannot be expressed in characters from the
4033 current ANSI codepage. */
4034 if (_mbspbrk (pat_a, "?"))
4035 dh = INVALID_HANDLE_VALUE;
4036 else
4037 dh = FindFirstFileA (pat_a, &dfd_a);
4040 if (dh == INVALID_HANDLE_VALUE)
4041 return 0;
4042 FindClose (dh);
4043 return 1;
4046 /* A version of 'access' to be used locally with file names in
4047 locale-specific encoding. Does not resolve symlinks and does not
4048 support file names on FAT12 and FAT16 volumes, but that's OK, since
4049 we only invoke this function for files inside the Emacs source or
4050 installation tree, on directories (so any symlinks should have the
4051 directory bit set), and on short file names such as "C:/.emacs". */
4052 static int
4053 sys_access (const char *fname, int mode)
4055 char fname_copy[MAX_PATH], *p;
4056 DWORD attributes;
4058 strcpy (fname_copy, fname);
4059 /* Do the equivalent of unixtodos_filename. */
4060 for (p = fname_copy; *p; p = CharNext (p))
4061 if (*p == '/')
4062 *p = '\\';
4064 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4066 DWORD w32err = GetLastError ();
4068 switch (w32err)
4070 case ERROR_INVALID_NAME:
4071 case ERROR_BAD_PATHNAME:
4072 case ERROR_FILE_NOT_FOUND:
4073 case ERROR_BAD_NETPATH:
4074 errno = ENOENT;
4075 break;
4076 default:
4077 errno = EACCES;
4078 break;
4080 return -1;
4082 if ((mode & X_OK) != 0
4083 && !(is_exec (fname_copy)
4084 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4086 errno = EACCES;
4087 return -1;
4089 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4091 errno = EACCES;
4092 return -1;
4094 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4096 errno = EACCES;
4097 return -1;
4099 return 0;
4102 /* Shadow some MSVC runtime functions to map requests for long filenames
4103 to reasonable short names if necessary. This was originally added to
4104 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4105 long file names. */
4108 sys_chdir (const char * path)
4110 path = map_w32_filename (path, NULL);
4111 if (w32_unicode_filenames)
4113 wchar_t newdir_w[MAX_PATH];
4115 if (filename_to_utf16 (path, newdir_w) == 0)
4116 return _wchdir (newdir_w);
4117 return -1;
4119 else
4121 char newdir_a[MAX_PATH];
4123 if (filename_to_ansi (path, newdir_a) == 0)
4124 return _chdir (newdir_a);
4125 return -1;
4130 sys_chmod (const char * path, int mode)
4132 path = chase_symlinks (map_w32_filename (path, NULL));
4133 if (w32_unicode_filenames)
4135 wchar_t path_w[MAX_PATH];
4137 filename_to_utf16 (path, path_w);
4138 return _wchmod (path_w, mode);
4140 else
4142 char path_a[MAX_PATH];
4144 filename_to_ansi (path, path_a);
4145 return _chmod (path_a, mode);
4150 sys_creat (const char * path, int mode)
4152 path = map_w32_filename (path, NULL);
4153 if (w32_unicode_filenames)
4155 wchar_t path_w[MAX_PATH];
4157 filename_to_utf16 (path, path_w);
4158 return _wcreat (path_w, mode);
4160 else
4162 char path_a[MAX_PATH];
4164 filename_to_ansi (path, path_a);
4165 return _creat (path_a, mode);
4169 FILE *
4170 sys_fopen (const char * path, const char * mode)
4172 int fd;
4173 int oflag;
4174 const char * mode_save = mode;
4176 /* Force all file handles to be non-inheritable. This is necessary to
4177 ensure child processes don't unwittingly inherit handles that might
4178 prevent future file access. */
4180 if (mode[0] == 'r')
4181 oflag = O_RDONLY;
4182 else if (mode[0] == 'w' || mode[0] == 'a')
4183 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4184 else
4185 return NULL;
4187 /* Only do simplistic option parsing. */
4188 while (*++mode)
4189 if (mode[0] == '+')
4191 oflag &= ~(O_RDONLY | O_WRONLY);
4192 oflag |= O_RDWR;
4194 else if (mode[0] == 'b')
4196 oflag &= ~O_TEXT;
4197 oflag |= O_BINARY;
4199 else if (mode[0] == 't')
4201 oflag &= ~O_BINARY;
4202 oflag |= O_TEXT;
4204 else break;
4206 path = map_w32_filename (path, NULL);
4207 if (w32_unicode_filenames)
4209 wchar_t path_w[MAX_PATH];
4211 filename_to_utf16 (path, path_w);
4212 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4214 else
4216 char path_a[MAX_PATH];
4218 filename_to_ansi (path, path_a);
4219 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4221 if (fd < 0)
4222 return NULL;
4224 return _fdopen (fd, mode_save);
4227 /* This only works on NTFS volumes, but is useful to have. */
4229 sys_link (const char * old, const char * new)
4231 HANDLE fileh;
4232 int result = -1;
4233 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4234 wchar_t oldname_w[MAX_PATH];
4235 char oldname_a[MAX_PATH];
4237 if (old == NULL || new == NULL)
4239 errno = ENOENT;
4240 return -1;
4243 strcpy (oldname, map_w32_filename (old, NULL));
4244 strcpy (newname, map_w32_filename (new, NULL));
4246 if (w32_unicode_filenames)
4248 filename_to_utf16 (oldname, oldname_w);
4249 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4250 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4252 else
4254 filename_to_ansi (oldname, oldname_a);
4255 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4256 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4258 if (fileh != INVALID_HANDLE_VALUE)
4260 int wlen;
4262 /* Confusingly, the "alternate" stream name field does not apply
4263 when restoring a hard link, and instead contains the actual
4264 stream data for the link (ie. the name of the link to create).
4265 The WIN32_STREAM_ID structure before the cStreamName field is
4266 the stream header, which is then immediately followed by the
4267 stream data. */
4269 struct {
4270 WIN32_STREAM_ID wid;
4271 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4272 } data;
4274 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4275 indicates that flag is unsupported for CP_UTF8, and OTOH says
4276 it is the default anyway. */
4277 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4278 data.wid.cStreamName, MAX_PATH);
4279 if (wlen > 0)
4281 LPVOID context = NULL;
4282 DWORD wbytes = 0;
4284 data.wid.dwStreamId = BACKUP_LINK;
4285 data.wid.dwStreamAttributes = 0;
4286 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4287 data.wid.Size.HighPart = 0;
4288 data.wid.dwStreamNameSize = 0;
4290 if (BackupWrite (fileh, (LPBYTE)&data,
4291 offsetof (WIN32_STREAM_ID, cStreamName)
4292 + data.wid.Size.LowPart,
4293 &wbytes, FALSE, FALSE, &context)
4294 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4296 /* succeeded */
4297 result = 0;
4299 else
4301 DWORD err = GetLastError ();
4302 DWORD attributes;
4304 switch (err)
4306 case ERROR_ACCESS_DENIED:
4307 /* This is what happens when OLDNAME is a directory,
4308 since Windows doesn't support hard links to
4309 directories. Posix says to set errno to EPERM in
4310 that case. */
4311 if (w32_unicode_filenames)
4312 attributes = GetFileAttributesW (oldname_w);
4313 else
4314 attributes = GetFileAttributesA (oldname_a);
4315 if (attributes != -1
4316 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4317 errno = EPERM;
4318 else if (attributes == -1
4319 && is_unc_volume (oldname)
4320 && unc_volume_file_attributes (oldname) != -1)
4321 errno = EPERM;
4322 else
4323 errno = EACCES;
4324 break;
4325 case ERROR_TOO_MANY_LINKS:
4326 errno = EMLINK;
4327 break;
4328 case ERROR_NOT_SAME_DEVICE:
4329 errno = EXDEV;
4330 break;
4331 default:
4332 errno = EINVAL;
4333 break;
4338 CloseHandle (fileh);
4340 else
4341 errno = ENOENT;
4343 return result;
4347 sys_mkdir (const char * path)
4349 path = map_w32_filename (path, NULL);
4351 if (w32_unicode_filenames)
4353 wchar_t path_w[MAX_PATH];
4355 filename_to_utf16 (path, path_w);
4356 return _wmkdir (path_w);
4358 else
4360 char path_a[MAX_PATH];
4362 filename_to_ansi (path, path_a);
4363 return _mkdir (path_a);
4368 sys_open (const char * path, int oflag, int mode)
4370 const char* mpath = map_w32_filename (path, NULL);
4371 int res = -1;
4373 if (w32_unicode_filenames)
4375 wchar_t mpath_w[MAX_PATH];
4377 filename_to_utf16 (mpath, mpath_w);
4378 /* If possible, try to open file without _O_CREAT, to be able to
4379 write to existing hidden and system files. Force all file
4380 handles to be non-inheritable. */
4381 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4382 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4383 if (res < 0)
4384 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4386 else
4388 char mpath_a[MAX_PATH];
4390 filename_to_ansi (mpath, mpath_a);
4391 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4392 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4393 if (res < 0)
4394 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4397 return res;
4400 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4401 when using mktemp.
4403 Standard algorithm for generating a temporary file name seems to be
4404 use pid or tid with a letter on the front (in place of the 6 X's)
4405 and cycle through the letters to find a unique name. We extend
4406 that to allow any reasonable character as the first of the 6 X's,
4407 so that the number of simultaneously used temporary files will be
4408 greater. */
4411 mkostemp (char * template, int flags)
4413 char * p;
4414 int i, fd = -1;
4415 unsigned uid = GetCurrentThreadId ();
4416 int save_errno = errno;
4417 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4419 errno = EINVAL;
4420 if (template == NULL)
4421 return -1;
4423 p = template + strlen (template);
4424 i = 5;
4425 /* replace up to the last 5 X's with uid in decimal */
4426 while (--p >= template && p[0] == 'X' && --i >= 0)
4428 p[0] = '0' + uid % 10;
4429 uid /= 10;
4432 if (i < 0 && p[0] == 'X')
4434 i = 0;
4437 p[0] = first_char[i];
4438 if ((fd = sys_open (template,
4439 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4440 S_IRUSR | S_IWUSR)) >= 0
4441 || errno != EEXIST)
4443 if (fd >= 0)
4444 errno = save_errno;
4445 return fd;
4448 while (++i < sizeof (first_char));
4451 /* Template is badly formed or else we can't generate a unique name. */
4452 return -1;
4456 fchmod (int fd, mode_t mode)
4458 return 0;
4462 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4464 BOOL result;
4465 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4466 int newname_dev;
4467 int oldname_dev;
4468 bool have_temp_a = false;
4470 /* MoveFile on Windows 95 doesn't correctly change the short file name
4471 alias in a number of circumstances (it is not easy to predict when
4472 just by looking at oldname and newname, unfortunately). In these
4473 cases, renaming through a temporary name avoids the problem.
4475 A second problem on Windows 95 is that renaming through a temp name when
4476 newname is uppercase fails (the final long name ends up in
4477 lowercase, although the short alias might be uppercase) UNLESS the
4478 long temp name is not 8.3.
4480 So, on Windows 95 we always rename through a temp name, and we make sure
4481 the temp name has a long extension to ensure correct renaming. */
4483 strcpy (temp, map_w32_filename (oldname, NULL));
4485 /* volume_info is set indirectly by map_w32_filename. */
4486 oldname_dev = volume_info.serialnum;
4488 if (os_subtype == OS_9X)
4490 char * o;
4491 char * p;
4492 int i = 0;
4493 char oldname_a[MAX_PATH];
4495 oldname = map_w32_filename (oldname, NULL);
4496 filename_to_ansi (oldname, oldname_a);
4497 filename_to_ansi (temp, temp_a);
4498 if ((o = strrchr (oldname_a, '\\')))
4499 o++;
4500 else
4501 o = (char *) oldname_a;
4503 if ((p = strrchr (temp_a, '\\')))
4504 p++;
4505 else
4506 p = temp_a;
4510 /* Force temp name to require a manufactured 8.3 alias - this
4511 seems to make the second rename work properly. */
4512 sprintf (p, "_.%s.%d", o, i);
4513 i++;
4514 result = rename (oldname_a, temp_a);
4516 /* This loop must surely terminate! */
4517 while (result < 0 && errno == EEXIST);
4518 if (result < 0)
4519 return -1;
4520 have_temp_a = true;
4523 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4524 (at least if it is a file; don't do this for directories).
4526 Since we mustn't do this if we are just changing the case of the
4527 file name (we would end up deleting the file we are trying to
4528 rename!), we let rename detect if the destination file already
4529 exists - that way we avoid the possible pitfalls of trying to
4530 determine ourselves whether two names really refer to the same
4531 file, which is not always possible in the general case. (Consider
4532 all the permutations of shared or subst'd drives, etc.) */
4534 newname = map_w32_filename (newname, NULL);
4536 /* volume_info is set indirectly by map_w32_filename. */
4537 newname_dev = volume_info.serialnum;
4539 if (w32_unicode_filenames)
4541 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4543 filename_to_utf16 (temp, temp_w);
4544 filename_to_utf16 (newname, newname_w);
4545 result = _wrename (temp_w, newname_w);
4546 if (result < 0 && force)
4548 DWORD w32err = GetLastError ();
4550 if (errno == EACCES
4551 && newname_dev != oldname_dev)
4553 /* The implementation of `rename' on Windows does not return
4554 errno = EXDEV when you are moving a directory to a
4555 different storage device (ex. logical disk). It returns
4556 EACCES instead. So here we handle such situations and
4557 return EXDEV. */
4558 DWORD attributes;
4560 if ((attributes = GetFileAttributesW (temp_w)) != -1
4561 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4562 errno = EXDEV;
4564 else if (errno == EEXIST)
4566 if (_wchmod (newname_w, 0666) != 0)
4567 return result;
4568 if (_wunlink (newname_w) != 0)
4569 return result;
4570 result = _wrename (temp_w, newname_w);
4572 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4573 && is_symlink (temp))
4575 /* This is Windows prohibiting the user from creating a
4576 symlink in another place, since that requires
4577 privileges. */
4578 errno = EPERM;
4582 else
4584 char newname_a[MAX_PATH];
4586 if (!have_temp_a)
4587 filename_to_ansi (temp, temp_a);
4588 filename_to_ansi (newname, newname_a);
4589 result = rename (temp_a, newname_a);
4590 if (result < 0 && force)
4592 DWORD w32err = GetLastError ();
4594 if (errno == EACCES
4595 && newname_dev != oldname_dev)
4597 DWORD attributes;
4599 if ((attributes = GetFileAttributesA (temp_a)) != -1
4600 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4601 errno = EXDEV;
4603 else if (errno == EEXIST)
4605 if (_chmod (newname_a, 0666) != 0)
4606 return result;
4607 if (_unlink (newname_a) != 0)
4608 return result;
4609 result = rename (temp_a, newname_a);
4611 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4612 && is_symlink (temp))
4613 errno = EPERM;
4617 return result;
4621 sys_rename (char const *old, char const *new)
4623 return sys_rename_replace (old, new, TRUE);
4627 sys_rmdir (const char * path)
4629 path = map_w32_filename (path, NULL);
4631 if (w32_unicode_filenames)
4633 wchar_t path_w[MAX_PATH];
4635 filename_to_utf16 (path, path_w);
4636 return _wrmdir (path_w);
4638 else
4640 char path_a[MAX_PATH];
4642 filename_to_ansi (path, path_a);
4643 return _rmdir (path_a);
4648 sys_unlink (const char * path)
4650 int rmstatus, e;
4652 path = map_w32_filename (path, NULL);
4654 if (w32_unicode_filenames)
4656 wchar_t path_w[MAX_PATH];
4658 filename_to_utf16 (path, path_w);
4659 /* On Unix, unlink works without write permission. */
4660 _wchmod (path_w, 0666);
4661 rmstatus = _wunlink (path_w);
4662 e = errno;
4663 /* Symlinks to directories can only be deleted by _rmdir;
4664 _unlink returns EACCES. */
4665 if (rmstatus != 0
4666 && errno == EACCES
4667 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4668 rmstatus = _wrmdir (path_w);
4669 else
4670 errno = e;
4672 else
4674 char path_a[MAX_PATH];
4676 filename_to_ansi (path, path_a);
4677 _chmod (path_a, 0666);
4678 rmstatus = _unlink (path_a);
4679 e = errno;
4680 if (rmstatus != 0
4681 && errno == EACCES
4682 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4683 rmstatus = _rmdir (path_a);
4684 else
4685 errno = e;
4688 return rmstatus;
4691 static FILETIME utc_base_ft;
4692 static ULONGLONG utc_base; /* In 100ns units */
4693 static int init = 0;
4695 #define FILETIME_TO_U64(result, ft) \
4696 do { \
4697 ULARGE_INTEGER uiTemp; \
4698 uiTemp.LowPart = (ft).dwLowDateTime; \
4699 uiTemp.HighPart = (ft).dwHighDateTime; \
4700 result = uiTemp.QuadPart; \
4701 } while (0)
4703 static void
4704 initialize_utc_base (void)
4706 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4707 SYSTEMTIME st;
4709 st.wYear = 1970;
4710 st.wMonth = 1;
4711 st.wDay = 1;
4712 st.wHour = 0;
4713 st.wMinute = 0;
4714 st.wSecond = 0;
4715 st.wMilliseconds = 0;
4717 SystemTimeToFileTime (&st, &utc_base_ft);
4718 FILETIME_TO_U64 (utc_base, utc_base_ft);
4721 static time_t
4722 convert_time (FILETIME ft)
4724 ULONGLONG tmp;
4726 if (!init)
4728 initialize_utc_base ();
4729 init = 1;
4732 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4733 return 0;
4735 FILETIME_TO_U64 (tmp, ft);
4736 return (time_t) ((tmp - utc_base) / 10000000L);
4739 static void
4740 convert_from_time_t (time_t time, FILETIME * pft)
4742 ULARGE_INTEGER tmp;
4744 if (!init)
4746 initialize_utc_base ();
4747 init = 1;
4750 /* time in 100ns units since 1-Jan-1601 */
4751 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4752 pft->dwHighDateTime = tmp.HighPart;
4753 pft->dwLowDateTime = tmp.LowPart;
4756 static PSECURITY_DESCRIPTOR
4757 get_file_security_desc_by_handle (HANDLE h)
4759 PSECURITY_DESCRIPTOR psd = NULL;
4760 DWORD err;
4761 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4762 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4764 err = get_security_info (h, SE_FILE_OBJECT, si,
4765 NULL, NULL, NULL, NULL, &psd);
4766 if (err != ERROR_SUCCESS)
4767 return NULL;
4769 return psd;
4772 static PSECURITY_DESCRIPTOR
4773 get_file_security_desc_by_name (const char *fname)
4775 PSECURITY_DESCRIPTOR psd = NULL;
4776 DWORD sd_len, err;
4777 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4778 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4780 if (!get_file_security (fname, si, psd, 0, &sd_len))
4782 err = GetLastError ();
4783 if (err != ERROR_INSUFFICIENT_BUFFER)
4784 return NULL;
4787 psd = xmalloc (sd_len);
4788 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4790 xfree (psd);
4791 return NULL;
4794 return psd;
4797 static DWORD
4798 get_rid (PSID sid)
4800 unsigned n_subauthorities;
4802 /* Use the last sub-authority value of the RID, the relative
4803 portion of the SID, as user/group ID. */
4804 n_subauthorities = *get_sid_sub_authority_count (sid);
4805 if (n_subauthorities < 1)
4806 return 0; /* the "World" RID */
4807 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4810 /* Caching SID and account values for faster lokup. */
4812 struct w32_id {
4813 unsigned rid;
4814 struct w32_id *next;
4815 char name[GNLEN+1];
4816 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4819 static struct w32_id *w32_idlist;
4821 static int
4822 w32_cached_id (PSID sid, unsigned *id, char *name)
4824 struct w32_id *tail, *found;
4826 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4828 if (equal_sid ((PSID)tail->sid, sid))
4830 found = tail;
4831 break;
4834 if (found)
4836 *id = found->rid;
4837 strcpy (name, found->name);
4838 return 1;
4840 else
4841 return 0;
4844 static void
4845 w32_add_to_cache (PSID sid, unsigned id, char *name)
4847 DWORD sid_len;
4848 struct w32_id *new_entry;
4850 /* We don't want to leave behind stale cache from when Emacs was
4851 dumped. */
4852 if (initialized)
4854 sid_len = get_length_sid (sid);
4855 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4856 if (new_entry)
4858 new_entry->rid = id;
4859 strcpy (new_entry->name, name);
4860 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4861 new_entry->next = w32_idlist;
4862 w32_idlist = new_entry;
4867 #define UID 1
4868 #define GID 2
4870 static int
4871 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4873 PSID sid = NULL;
4874 BOOL dflt;
4875 SID_NAME_USE ignore;
4876 char name[UNLEN+1];
4877 DWORD name_len = sizeof (name);
4878 char domain[1024];
4879 DWORD domain_len = sizeof (domain);
4880 int use_dflt = 0;
4881 int result;
4883 if (what == UID)
4884 result = get_security_descriptor_owner (psd, &sid, &dflt);
4885 else if (what == GID)
4886 result = get_security_descriptor_group (psd, &sid, &dflt);
4887 else
4888 result = 0;
4890 if (!result || !is_valid_sid (sid))
4891 use_dflt = 1;
4892 else if (!w32_cached_id (sid, id, nm))
4894 if (!lookup_account_sid (NULL, sid, name, &name_len,
4895 domain, &domain_len, &ignore)
4896 || name_len > UNLEN+1)
4897 use_dflt = 1;
4898 else
4900 *id = get_rid (sid);
4901 strcpy (nm, name);
4902 w32_add_to_cache (sid, *id, name);
4905 return use_dflt;
4908 static void
4909 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4911 int dflt_usr = 0, dflt_grp = 0;
4913 if (!psd)
4915 dflt_usr = 1;
4916 dflt_grp = 1;
4918 else
4920 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4921 dflt_usr = 1;
4922 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4923 dflt_grp = 1;
4925 /* Consider files to belong to current user/group, if we cannot get
4926 more accurate information. */
4927 if (dflt_usr)
4929 st->st_uid = dflt_passwd.pw_uid;
4930 strcpy (st->st_uname, dflt_passwd.pw_name);
4932 if (dflt_grp)
4934 st->st_gid = dflt_passwd.pw_gid;
4935 strcpy (st->st_gname, dflt_group.gr_name);
4939 /* Return non-zero if NAME is a potentially slow filesystem. */
4940 int is_slow_fs (const char *);
4943 is_slow_fs (const char *name)
4945 char drive_root[4];
4946 UINT devtype;
4948 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4949 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4950 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4951 devtype = GetDriveType (NULL); /* use root of current drive */
4952 else
4954 /* GetDriveType needs the root directory of the drive. */
4955 strncpy (drive_root, name, 2);
4956 drive_root[2] = '\\';
4957 drive_root[3] = '\0';
4958 devtype = GetDriveType (drive_root);
4960 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4963 /* If this is non-zero, the caller wants accurate information about
4964 file's owner and group, which could be expensive to get. dired.c
4965 uses this flag when needed for the job at hand. */
4966 int w32_stat_get_owner_group;
4968 /* MSVC stat function can't cope with UNC names and has other bugs, so
4969 replace it with our own. This also allows us to calculate consistent
4970 inode values and owner/group without hacks in the main Emacs code,
4971 and support file names encoded in UTF-8. */
4973 static int
4974 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4976 char *name, *save_name, *r;
4977 WIN32_FIND_DATAW wfd_w;
4978 WIN32_FIND_DATAA wfd_a;
4979 HANDLE fh;
4980 unsigned __int64 fake_inode = 0;
4981 int permission;
4982 int len;
4983 int rootdir = FALSE;
4984 PSECURITY_DESCRIPTOR psd = NULL;
4985 int is_a_symlink = 0;
4986 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4987 DWORD access_rights = 0;
4988 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4989 FILETIME ctime, atime, wtime;
4990 wchar_t name_w[MAX_PATH];
4991 char name_a[MAX_PATH];
4993 if (path == NULL || buf == NULL)
4995 errno = EFAULT;
4996 return -1;
4999 save_name = name = (char *) map_w32_filename (path, &path);
5000 /* Must be valid filename, no wild cards or other invalid
5001 characters. */
5002 if (strpbrk (name, "*?|<>\""))
5004 errno = ENOENT;
5005 return -1;
5008 len = strlen (name);
5009 /* Allocate 1 extra byte so that we could append a slash to a root
5010 directory, down below. */
5011 name = strcpy (alloca (len + 2), name);
5013 /* Avoid a somewhat costly call to is_symlink if the filesystem
5014 doesn't support symlinks. */
5015 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5016 is_a_symlink = is_symlink (name);
5018 /* Plan A: Open the file and get all the necessary information via
5019 the resulting handle. This solves several issues in one blow:
5021 . retrieves attributes for the target of a symlink, if needed
5022 . gets attributes of root directories and symlinks pointing to
5023 root directories, thus avoiding the need for special-casing
5024 these and detecting them by examining the file-name format
5025 . retrieves more accurate attributes (e.g., non-zero size for
5026 some directories, esp. directories that are junction points)
5027 . correctly resolves "c:/..", "/.." and similar file names
5028 . avoids run-time penalties for 99% of use cases
5030 Plan A is always tried first, unless the user asked not to (but
5031 if the file is a symlink and we need to follow links, we try Plan
5032 A even if the user asked not to).
5034 If Plan A fails, we go to Plan B (below), where various
5035 potentially expensive techniques must be used to handle "special"
5036 files such as UNC volumes etc. */
5037 if (!(NILP (Vw32_get_true_file_attributes)
5038 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
5039 /* Following symlinks requires getting the info by handle. */
5040 || (is_a_symlink && follow_symlinks))
5042 BY_HANDLE_FILE_INFORMATION info;
5044 if (is_a_symlink && !follow_symlinks)
5045 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5046 /* READ_CONTROL access rights are required to get security info
5047 by handle. But if the OS doesn't support security in the
5048 first place, we don't need to try. */
5049 if (is_windows_9x () != TRUE)
5050 access_rights |= READ_CONTROL;
5052 if (w32_unicode_filenames)
5054 filename_to_utf16 (name, name_w);
5055 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
5056 file_flags, NULL);
5057 /* If CreateFile fails with READ_CONTROL, try again with
5058 zero as access rights. */
5059 if (fh == INVALID_HANDLE_VALUE && access_rights)
5060 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
5061 file_flags, NULL);
5063 else
5065 filename_to_ansi (name, name_a);
5066 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5067 file_flags, NULL);
5068 if (fh == INVALID_HANDLE_VALUE && access_rights)
5069 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5070 file_flags, NULL);
5072 if (fh == INVALID_HANDLE_VALUE)
5073 goto no_true_file_attributes;
5075 /* This is more accurate in terms of getting the correct number
5076 of links, but is quite slow (it is noticeable when Emacs is
5077 making a list of file name completions). */
5078 if (GetFileInformationByHandle (fh, &info))
5080 nlinks = info.nNumberOfLinks;
5081 /* Might as well use file index to fake inode values, but this
5082 is not guaranteed to be unique unless we keep a handle open
5083 all the time (even then there are situations where it is
5084 not unique). Reputedly, there are at most 48 bits of info
5085 (on NTFS, presumably less on FAT). */
5086 fake_inode = info.nFileIndexHigh;
5087 fake_inode <<= 32;
5088 fake_inode += info.nFileIndexLow;
5089 serialnum = info.dwVolumeSerialNumber;
5090 fs_high = info.nFileSizeHigh;
5091 fs_low = info.nFileSizeLow;
5092 ctime = info.ftCreationTime;
5093 atime = info.ftLastAccessTime;
5094 wtime = info.ftLastWriteTime;
5095 fattrs = info.dwFileAttributes;
5097 else
5099 /* We don't go to Plan B here, because it's not clear that
5100 it's a good idea. The only known use case where
5101 CreateFile succeeds, but GetFileInformationByHandle fails
5102 (with ERROR_INVALID_FUNCTION) is for character devices
5103 such as NUL, PRN, etc. For these, switching to Plan B is
5104 a net loss, because we lose the character device
5105 attribute returned by GetFileType below (FindFirstFile
5106 doesn't set that bit in the attributes), and the other
5107 fields don't make sense for character devices anyway.
5108 Emacs doesn't really care for non-file entities in the
5109 context of l?stat, so neither do we. */
5111 /* w32err is assigned so one could put a breakpoint here and
5112 examine its value, when GetFileInformationByHandle
5113 fails. */
5114 DWORD w32err = GetLastError ();
5116 switch (w32err)
5118 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5119 errno = ENOENT;
5120 return -1;
5124 /* Test for a symlink before testing for a directory, since
5125 symlinks to directories have the directory bit set, but we
5126 don't want them to appear as directories. */
5127 if (is_a_symlink && !follow_symlinks)
5128 buf->st_mode = S_IFLNK;
5129 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5130 buf->st_mode = S_IFDIR;
5131 else
5133 DWORD ftype = GetFileType (fh);
5135 switch (ftype)
5137 case FILE_TYPE_DISK:
5138 buf->st_mode = S_IFREG;
5139 break;
5140 case FILE_TYPE_PIPE:
5141 buf->st_mode = S_IFIFO;
5142 break;
5143 case FILE_TYPE_CHAR:
5144 case FILE_TYPE_UNKNOWN:
5145 default:
5146 buf->st_mode = S_IFCHR;
5149 /* We produce the fallback owner and group data, based on the
5150 current user that runs Emacs, in the following cases:
5152 . caller didn't request owner and group info
5153 . this is Windows 9X
5154 . getting security by handle failed, and we need to produce
5155 information for the target of a symlink (this is better
5156 than producing a potentially misleading info about the
5157 symlink itself)
5159 If getting security by handle fails, and we don't need to
5160 resolve symlinks, we try getting security by name. */
5161 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5162 get_file_owner_and_group (NULL, buf);
5163 else
5165 psd = get_file_security_desc_by_handle (fh);
5166 if (psd)
5168 get_file_owner_and_group (psd, buf);
5169 LocalFree (psd);
5171 else if (!(is_a_symlink && follow_symlinks))
5173 psd = get_file_security_desc_by_name (name);
5174 get_file_owner_and_group (psd, buf);
5175 xfree (psd);
5177 else
5178 get_file_owner_and_group (NULL, buf);
5180 CloseHandle (fh);
5182 else
5184 no_true_file_attributes:
5185 /* Plan B: Either getting a handle on the file failed, or the
5186 caller explicitly asked us to not bother making this
5187 information more accurate.
5189 Implementation note: In Plan B, we never bother to resolve
5190 symlinks, even if we got here because we tried Plan A and
5191 failed. That's because, even if the caller asked for extra
5192 precision by setting Vw32_get_true_file_attributes to t,
5193 resolving symlinks requires acquiring a file handle to the
5194 symlink, which we already know will fail. And if the user
5195 did not ask for extra precision, resolving symlinks will fly
5196 in the face of that request, since the user then wants the
5197 lightweight version of the code. */
5198 rootdir = (path >= save_name + len - 1
5199 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5201 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5202 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5203 if (IS_DIRECTORY_SEP (r[0])
5204 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5205 r[1] = r[2] = '\0';
5207 /* Note: If NAME is a symlink to the root of a UNC volume
5208 (i.e. "\\SERVER"), we will not detect that here, and we will
5209 return data about the symlink as result of FindFirst below.
5210 This is unfortunate, but that marginal use case does not
5211 justify a call to chase_symlinks which would impose a penalty
5212 on all the other use cases. (We get here for symlinks to
5213 roots of UNC volumes because CreateFile above fails for them,
5214 unlike with symlinks to root directories X:\ of drives.) */
5215 if (is_unc_volume (name))
5217 fattrs = unc_volume_file_attributes (name);
5218 if (fattrs == -1)
5219 return -1;
5221 ctime = atime = wtime = utc_base_ft;
5223 else if (rootdir)
5225 /* Make sure root directories end in a slash. */
5226 if (!IS_DIRECTORY_SEP (name[len-1]))
5227 strcpy (name + len, "\\");
5228 if (GetDriveType (name) < 2)
5230 errno = ENOENT;
5231 return -1;
5234 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5235 ctime = atime = wtime = utc_base_ft;
5237 else
5239 int have_wfd = -1;
5241 /* Make sure non-root directories do NOT end in a slash,
5242 otherwise FindFirstFile might fail. */
5243 if (IS_DIRECTORY_SEP (name[len-1]))
5244 name[len - 1] = 0;
5246 /* (This is hacky, but helps when doing file completions on
5247 network drives.) Optimize by using information available from
5248 active readdir if possible. */
5249 len = strlen (dir_pathname);
5250 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5251 len--;
5252 if (dir_find_handle != INVALID_HANDLE_VALUE
5253 && last_dir_find_data != -1
5254 && !(is_a_symlink && follow_symlinks)
5255 /* The 2 file-name comparisons below support only ASCII
5256 characters, and will lose (compare not equal) when
5257 the file names include non-ASCII characters that are
5258 the same but for the case. However, doing this
5259 properly involves: (a) converting both file names to
5260 UTF-16, (b) lower-casing both names using CharLowerW,
5261 and (c) comparing the results; this would be quite a
5262 bit slower, whereas Plan B is for users who want
5263 lightweight albeit inaccurate version of 'stat'. */
5264 && c_strncasecmp (save_name, dir_pathname, len) == 0
5265 && IS_DIRECTORY_SEP (name[len])
5266 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5268 have_wfd = last_dir_find_data;
5269 /* This was the last entry returned by readdir. */
5270 if (last_dir_find_data == DIR_FIND_DATA_W)
5271 wfd_w = dir_find_data_w;
5272 else
5273 wfd_a = dir_find_data_a;
5275 else
5277 logon_network_drive (name);
5279 if (w32_unicode_filenames)
5281 filename_to_utf16 (name, name_w);
5282 fh = FindFirstFileW (name_w, &wfd_w);
5283 have_wfd = DIR_FIND_DATA_W;
5285 else
5287 filename_to_ansi (name, name_a);
5288 /* If NAME includes characters not representable by
5289 the current ANSI codepage, filename_to_ansi
5290 usually replaces them with a '?'. We don't want
5291 to let FindFirstFileA interpret those as wildcards,
5292 and "succeed", returning us data from some random
5293 file in the same directory. */
5294 if (_mbspbrk (name_a, "?"))
5295 fh = INVALID_HANDLE_VALUE;
5296 else
5297 fh = FindFirstFileA (name_a, &wfd_a);
5298 have_wfd = DIR_FIND_DATA_A;
5300 if (fh == INVALID_HANDLE_VALUE)
5302 errno = ENOENT;
5303 return -1;
5305 FindClose (fh);
5307 /* Note: if NAME is a symlink, the information we get from
5308 FindFirstFile is for the symlink, not its target. */
5309 if (have_wfd == DIR_FIND_DATA_W)
5311 fattrs = wfd_w.dwFileAttributes;
5312 ctime = wfd_w.ftCreationTime;
5313 atime = wfd_w.ftLastAccessTime;
5314 wtime = wfd_w.ftLastWriteTime;
5315 fs_high = wfd_w.nFileSizeHigh;
5316 fs_low = wfd_w.nFileSizeLow;
5318 else
5320 fattrs = wfd_a.dwFileAttributes;
5321 ctime = wfd_a.ftCreationTime;
5322 atime = wfd_a.ftLastAccessTime;
5323 wtime = wfd_a.ftLastWriteTime;
5324 fs_high = wfd_a.nFileSizeHigh;
5325 fs_low = wfd_a.nFileSizeLow;
5327 fake_inode = 0;
5328 nlinks = 1;
5329 serialnum = volume_info.serialnum;
5331 if (is_a_symlink && !follow_symlinks)
5332 buf->st_mode = S_IFLNK;
5333 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5334 buf->st_mode = S_IFDIR;
5335 else
5336 buf->st_mode = S_IFREG;
5338 get_file_owner_and_group (NULL, buf);
5341 buf->st_ino = fake_inode;
5343 buf->st_dev = serialnum;
5344 buf->st_rdev = serialnum;
5346 buf->st_size = fs_high;
5347 buf->st_size <<= 32;
5348 buf->st_size += fs_low;
5349 buf->st_nlink = nlinks;
5351 /* Convert timestamps to Unix format. */
5352 buf->st_mtime = convert_time (wtime);
5353 buf->st_atime = convert_time (atime);
5354 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5355 buf->st_ctime = convert_time (ctime);
5356 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5358 /* determine rwx permissions */
5359 if (is_a_symlink && !follow_symlinks)
5360 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5361 else
5363 if (fattrs & FILE_ATTRIBUTE_READONLY)
5364 permission = S_IREAD;
5365 else
5366 permission = S_IREAD | S_IWRITE;
5368 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5369 permission |= S_IEXEC;
5370 else if (is_exec (name))
5371 permission |= S_IEXEC;
5374 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5376 return 0;
5380 stat (const char * path, struct stat * buf)
5382 return stat_worker (path, buf, 1);
5386 lstat (const char * path, struct stat * buf)
5388 return stat_worker (path, buf, 0);
5392 fstatat (int fd, char const *name, struct stat *st, int flags)
5394 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5395 This is good enough for the current usage in Emacs, but is fragile.
5397 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5398 Gnulib does this and can serve as a model. */
5399 char fullname[MAX_UTF8_PATH];
5401 if (fd != AT_FDCWD)
5403 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5405 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5406 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5407 < 0)
5409 errno = ENAMETOOLONG;
5410 return -1;
5412 name = fullname;
5415 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5418 /* Provide fstat and utime as well as stat for consistent handling of
5419 file timestamps. */
5421 fstat (int desc, struct stat * buf)
5423 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5424 BY_HANDLE_FILE_INFORMATION info;
5425 unsigned __int64 fake_inode;
5426 int permission;
5428 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5430 case FILE_TYPE_DISK:
5431 buf->st_mode = S_IFREG;
5432 if (!GetFileInformationByHandle (fh, &info))
5434 errno = EACCES;
5435 return -1;
5437 break;
5438 case FILE_TYPE_PIPE:
5439 buf->st_mode = S_IFIFO;
5440 goto non_disk;
5441 case FILE_TYPE_CHAR:
5442 case FILE_TYPE_UNKNOWN:
5443 default:
5444 buf->st_mode = S_IFCHR;
5445 non_disk:
5446 memset (&info, 0, sizeof (info));
5447 info.dwFileAttributes = 0;
5448 info.ftCreationTime = utc_base_ft;
5449 info.ftLastAccessTime = utc_base_ft;
5450 info.ftLastWriteTime = utc_base_ft;
5453 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5454 buf->st_mode = S_IFDIR;
5456 buf->st_nlink = info.nNumberOfLinks;
5457 /* Might as well use file index to fake inode values, but this
5458 is not guaranteed to be unique unless we keep a handle open
5459 all the time (even then there are situations where it is
5460 not unique). Reputedly, there are at most 48 bits of info
5461 (on NTFS, presumably less on FAT). */
5462 fake_inode = info.nFileIndexHigh;
5463 fake_inode <<= 32;
5464 fake_inode += info.nFileIndexLow;
5466 /* MSVC defines _ino_t to be short; other libc's might not. */
5467 if (sizeof (buf->st_ino) == 2)
5468 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5469 else
5470 buf->st_ino = fake_inode;
5472 /* If the caller so requested, get the true file owner and group.
5473 Otherwise, consider the file to belong to the current user. */
5474 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5475 get_file_owner_and_group (NULL, buf);
5476 else
5478 PSECURITY_DESCRIPTOR psd = NULL;
5480 psd = get_file_security_desc_by_handle (fh);
5481 if (psd)
5483 get_file_owner_and_group (psd, buf);
5484 LocalFree (psd);
5486 else
5487 get_file_owner_and_group (NULL, buf);
5490 buf->st_dev = info.dwVolumeSerialNumber;
5491 buf->st_rdev = info.dwVolumeSerialNumber;
5493 buf->st_size = info.nFileSizeHigh;
5494 buf->st_size <<= 32;
5495 buf->st_size += info.nFileSizeLow;
5497 /* Convert timestamps to Unix format. */
5498 buf->st_mtime = convert_time (info.ftLastWriteTime);
5499 buf->st_atime = convert_time (info.ftLastAccessTime);
5500 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5501 buf->st_ctime = convert_time (info.ftCreationTime);
5502 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5504 /* determine rwx permissions */
5505 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5506 permission = S_IREAD;
5507 else
5508 permission = S_IREAD | S_IWRITE;
5510 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5511 permission |= S_IEXEC;
5512 else
5514 #if 0 /* no way of knowing the filename */
5515 char * p = strrchr (name, '.');
5516 if (p != NULL &&
5517 (xstrcasecmp (p, ".exe") == 0 ||
5518 xstrcasecmp (p, ".com") == 0 ||
5519 xstrcasecmp (p, ".bat") == 0 ||
5520 xstrcasecmp (p, ".cmd") == 0))
5521 permission |= S_IEXEC;
5522 #endif
5525 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5527 return 0;
5530 /* A version of 'utime' which handles directories as well as
5531 files. */
5534 utime (const char *name, struct utimbuf *times)
5536 struct utimbuf deftime;
5537 HANDLE fh;
5538 FILETIME mtime;
5539 FILETIME atime;
5541 if (times == NULL)
5543 deftime.modtime = deftime.actime = time (NULL);
5544 times = &deftime;
5547 if (w32_unicode_filenames)
5549 wchar_t name_utf16[MAX_PATH];
5551 if (filename_to_utf16 (name, name_utf16) != 0)
5552 return -1; /* errno set by filename_to_utf16 */
5554 /* Need write access to set times. */
5555 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5556 /* If NAME specifies a directory, FILE_SHARE_DELETE
5557 allows other processes to delete files inside it,
5558 while we have the directory open. */
5559 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5560 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5562 else
5564 char name_ansi[MAX_PATH];
5566 if (filename_to_ansi (name, name_ansi) != 0)
5567 return -1; /* errno set by filename_to_ansi */
5569 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5570 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5571 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5573 if (fh != INVALID_HANDLE_VALUE)
5575 convert_from_time_t (times->actime, &atime);
5576 convert_from_time_t (times->modtime, &mtime);
5577 if (!SetFileTime (fh, NULL, &atime, &mtime))
5579 CloseHandle (fh);
5580 errno = EACCES;
5581 return -1;
5583 CloseHandle (fh);
5585 else
5587 DWORD err = GetLastError ();
5589 switch (err)
5591 case ERROR_FILE_NOT_FOUND:
5592 case ERROR_PATH_NOT_FOUND:
5593 case ERROR_INVALID_DRIVE:
5594 case ERROR_BAD_NETPATH:
5595 case ERROR_DEV_NOT_EXIST:
5596 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5597 file name includes ?s, i.e. translation to ANSI failed. */
5598 case ERROR_INVALID_NAME:
5599 errno = ENOENT;
5600 break;
5601 case ERROR_TOO_MANY_OPEN_FILES:
5602 errno = ENFILE;
5603 break;
5604 case ERROR_ACCESS_DENIED:
5605 case ERROR_SHARING_VIOLATION:
5606 errno = EACCES;
5607 break;
5608 default:
5609 errno = EINVAL;
5610 break;
5612 return -1;
5614 return 0;
5618 sys_umask (int mode)
5620 static int current_mask;
5621 int retval, arg = 0;
5623 /* The only bit we really support is the write bit. Files are
5624 always readable on MS-Windows, and the execute bit does not exist
5625 at all. */
5626 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5627 to prevent access by other users on NTFS. */
5628 if ((mode & S_IWRITE) != 0)
5629 arg |= S_IWRITE;
5631 retval = _umask (arg);
5632 /* Merge into the return value the bits they've set the last time,
5633 which msvcrt.dll ignores and never returns. Emacs insists on its
5634 notion of mask being identical to what we return. */
5635 retval |= (current_mask & ~S_IWRITE);
5636 current_mask = mode;
5638 return retval;
5642 /* Symlink-related functions. */
5643 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5644 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5645 #endif
5648 symlink (char const *filename, char const *linkname)
5650 char linkfn[MAX_UTF8_PATH], *tgtfn;
5651 DWORD flags = 0;
5652 int dir_access, filename_ends_in_slash;
5654 /* Diagnostics follows Posix as much as possible. */
5655 if (filename == NULL || linkname == NULL)
5657 errno = EFAULT;
5658 return -1;
5660 if (!*filename)
5662 errno = ENOENT;
5663 return -1;
5665 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5667 errno = ENAMETOOLONG;
5668 return -1;
5671 strcpy (linkfn, map_w32_filename (linkname, NULL));
5672 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5674 errno = EPERM;
5675 return -1;
5678 /* Note: since empty FILENAME was already rejected, we can safely
5679 refer to FILENAME[1]. */
5680 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5682 /* Non-absolute FILENAME is understood as being relative to
5683 LINKNAME's directory. We need to prepend that directory to
5684 FILENAME to get correct results from faccessat below, since
5685 otherwise it will interpret FILENAME relative to the
5686 directory where the Emacs process runs. Note that
5687 make-symbolic-link always makes sure LINKNAME is a fully
5688 expanded file name. */
5689 char tem[MAX_UTF8_PATH];
5690 char *p = linkfn + strlen (linkfn);
5692 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5693 p--;
5694 if (p > linkfn)
5695 strncpy (tem, linkfn, p - linkfn);
5696 strcpy (tem + (p - linkfn), filename);
5697 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5699 else
5700 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5702 /* Since Windows distinguishes between symlinks to directories and
5703 to files, we provide a kludgy feature: if FILENAME doesn't
5704 exist, but ends in a slash, we create a symlink to directory. If
5705 FILENAME exists and is a directory, we always create a symlink to
5706 directory. */
5707 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5708 if (dir_access == 0 || filename_ends_in_slash)
5709 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5711 tgtfn = (char *)map_w32_filename (filename, NULL);
5712 if (filename_ends_in_slash)
5713 tgtfn[strlen (tgtfn) - 1] = '\0';
5715 errno = 0;
5716 if (!create_symbolic_link (linkfn, tgtfn, flags))
5718 /* ENOSYS is set by create_symbolic_link, when it detects that
5719 the OS doesn't support the CreateSymbolicLink API. */
5720 if (errno != ENOSYS)
5722 DWORD w32err = GetLastError ();
5724 switch (w32err)
5726 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5727 TGTFN point to the same file name, go figure. */
5728 case ERROR_SUCCESS:
5729 case ERROR_FILE_EXISTS:
5730 errno = EEXIST;
5731 break;
5732 case ERROR_ACCESS_DENIED:
5733 errno = EACCES;
5734 break;
5735 case ERROR_FILE_NOT_FOUND:
5736 case ERROR_PATH_NOT_FOUND:
5737 case ERROR_BAD_NETPATH:
5738 case ERROR_INVALID_REPARSE_DATA:
5739 errno = ENOENT;
5740 break;
5741 case ERROR_DIRECTORY:
5742 errno = EISDIR;
5743 break;
5744 case ERROR_PRIVILEGE_NOT_HELD:
5745 case ERROR_NOT_ALL_ASSIGNED:
5746 errno = EPERM;
5747 break;
5748 case ERROR_DISK_FULL:
5749 errno = ENOSPC;
5750 break;
5751 default:
5752 errno = EINVAL;
5753 break;
5756 return -1;
5758 return 0;
5761 /* A quick inexpensive test of whether FILENAME identifies a file that
5762 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5763 must already be in the normalized form returned by
5764 map_w32_filename. If the symlink is to a directory, the
5765 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5767 Note: for repeated operations on many files, it is best to test
5768 whether the underlying volume actually supports symlinks, by
5769 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5770 avoid the call to this function if it doesn't. That's because the
5771 call to GetFileAttributes takes a non-negligible time, especially
5772 on non-local or removable filesystems. See stat_worker for an
5773 example of how to do that. */
5774 static int
5775 is_symlink (const char *filename)
5777 DWORD attrs;
5778 wchar_t filename_w[MAX_PATH];
5779 char filename_a[MAX_PATH];
5780 WIN32_FIND_DATAW wfdw;
5781 WIN32_FIND_DATAA wfda;
5782 HANDLE fh;
5783 int attrs_mean_symlink;
5785 if (w32_unicode_filenames)
5787 filename_to_utf16 (filename, filename_w);
5788 attrs = GetFileAttributesW (filename_w);
5790 else
5792 filename_to_ansi (filename, filename_a);
5793 attrs = GetFileAttributesA (filename_a);
5795 if (attrs == -1)
5797 DWORD w32err = GetLastError ();
5799 switch (w32err)
5801 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5802 break;
5803 case ERROR_ACCESS_DENIED:
5804 errno = EACCES;
5805 break;
5806 case ERROR_FILE_NOT_FOUND:
5807 case ERROR_PATH_NOT_FOUND:
5808 default:
5809 errno = ENOENT;
5810 break;
5812 return 0;
5814 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5815 return 0;
5816 logon_network_drive (filename);
5817 if (w32_unicode_filenames)
5819 fh = FindFirstFileW (filename_w, &wfdw);
5820 attrs_mean_symlink =
5821 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5822 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5823 if (attrs_mean_symlink)
5824 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5826 else if (_mbspbrk (filename_a, "?"))
5828 /* filename_to_ansi failed to convert the file name. */
5829 errno = ENOENT;
5830 return 0;
5832 else
5834 fh = FindFirstFileA (filename_a, &wfda);
5835 attrs_mean_symlink =
5836 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5837 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5838 if (attrs_mean_symlink)
5839 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5841 if (fh == INVALID_HANDLE_VALUE)
5842 return 0;
5843 FindClose (fh);
5844 return attrs_mean_symlink;
5847 /* If NAME identifies a symbolic link, copy into BUF the file name of
5848 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5849 null-terminate the target name, even if it fits. Return the number
5850 of bytes copied, or -1 if NAME is not a symlink or any error was
5851 encountered while resolving it. The file name copied into BUF is
5852 encoded in the current ANSI codepage. */
5853 ssize_t
5854 readlink (const char *name, char *buf, size_t buf_size)
5856 const char *path;
5857 TOKEN_PRIVILEGES privs;
5858 int restore_privs = 0;
5859 HANDLE sh;
5860 ssize_t retval;
5861 char resolved[MAX_UTF8_PATH];
5863 if (name == NULL)
5865 errno = EFAULT;
5866 return -1;
5868 if (!*name)
5870 errno = ENOENT;
5871 return -1;
5874 path = map_w32_filename (name, NULL);
5876 if (strlen (path) > MAX_UTF8_PATH)
5878 errno = ENAMETOOLONG;
5879 return -1;
5882 errno = 0;
5883 if (is_windows_9x () == TRUE
5884 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5885 || !is_symlink (path))
5887 if (!errno)
5888 errno = EINVAL; /* not a symlink */
5889 return -1;
5892 /* Done with simple tests, now we're in for some _real_ work. */
5893 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5894 restore_privs = 1;
5895 /* Implementation note: From here and onward, don't return early,
5896 since that will fail to restore the original set of privileges of
5897 the calling thread. */
5899 retval = -1; /* not too optimistic, are we? */
5901 /* Note: In the next call to CreateFile, we use zero as the 2nd
5902 argument because, when the symlink is a hidden/system file,
5903 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5904 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5905 and directory symlinks. */
5906 if (w32_unicode_filenames)
5908 wchar_t path_w[MAX_PATH];
5910 filename_to_utf16 (path, path_w);
5911 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5912 FILE_FLAG_OPEN_REPARSE_POINT
5913 | FILE_FLAG_BACKUP_SEMANTICS,
5914 NULL);
5916 else
5918 char path_a[MAX_PATH];
5920 filename_to_ansi (path, path_a);
5921 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5922 FILE_FLAG_OPEN_REPARSE_POINT
5923 | FILE_FLAG_BACKUP_SEMANTICS,
5924 NULL);
5926 if (sh != INVALID_HANDLE_VALUE)
5928 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5929 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5930 DWORD retbytes;
5932 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5933 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5934 &retbytes, NULL))
5935 errno = EIO;
5936 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5937 errno = EINVAL;
5938 else
5940 /* Copy the link target name, in wide characters, from
5941 reparse_data, then convert it to multibyte encoding in
5942 the current locale's codepage. */
5943 WCHAR *lwname;
5944 size_t lname_size;
5945 USHORT lwname_len =
5946 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5947 WCHAR *lwname_src =
5948 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5949 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5950 size_t size_to_copy = buf_size;
5952 /* According to MSDN, PrintNameLength does not include the
5953 terminating null character. */
5954 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5955 memcpy (lwname, lwname_src, lwname_len);
5956 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5957 filename_from_utf16 (lwname, resolved);
5958 dostounix_filename (resolved);
5959 lname_size = strlen (resolved) + 1;
5960 if (lname_size <= buf_size)
5961 size_to_copy = lname_size;
5962 strncpy (buf, resolved, size_to_copy);
5963 /* Success! */
5964 retval = size_to_copy;
5966 CloseHandle (sh);
5968 else
5970 /* CreateFile failed. */
5971 DWORD w32err2 = GetLastError ();
5973 switch (w32err2)
5975 case ERROR_FILE_NOT_FOUND:
5976 case ERROR_PATH_NOT_FOUND:
5977 errno = ENOENT;
5978 break;
5979 case ERROR_ACCESS_DENIED:
5980 case ERROR_TOO_MANY_OPEN_FILES:
5981 errno = EACCES;
5982 break;
5983 default:
5984 errno = EPERM;
5985 break;
5988 if (restore_privs)
5990 restore_privilege (&privs);
5991 revert_to_self ();
5994 return retval;
5997 ssize_t
5998 readlinkat (int fd, char const *name, char *buffer,
5999 size_t buffer_size)
6001 /* Rely on a hack: an open directory is modeled as file descriptor 0,
6002 as in fstatat. FIXME: Add proper support for readlinkat. */
6003 char fullname[MAX_UTF8_PATH];
6005 if (fd != AT_FDCWD)
6007 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
6008 < 0)
6010 errno = ENAMETOOLONG;
6011 return -1;
6013 name = fullname;
6016 return readlink (name, buffer, buffer_size);
6019 /* If FILE is a symlink, return its target (stored in a static
6020 buffer); otherwise return FILE.
6022 This function repeatedly resolves symlinks in the last component of
6023 a chain of symlink file names, as in foo -> bar -> baz -> ...,
6024 until it arrives at a file whose last component is not a symlink,
6025 or some error occurs. It returns the target of the last
6026 successfully resolved symlink in the chain. If it succeeds to
6027 resolve even a single symlink, the value returned is an absolute
6028 file name with backslashes (result of GetFullPathName). By
6029 contrast, if the original FILE is returned, it is unaltered.
6031 Note: This function can set errno even if it succeeds.
6033 Implementation note: we only resolve the last portion ("basename")
6034 of the argument FILE and of each following file in the chain,
6035 disregarding any possible symlinks in its leading directories.
6036 This is because Windows system calls and library functions
6037 transparently resolve symlinks in leading directories and return
6038 correct information, as long as the basename is not a symlink. */
6039 static char *
6040 chase_symlinks (const char *file)
6042 static char target[MAX_UTF8_PATH];
6043 char link[MAX_UTF8_PATH];
6044 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
6045 char target_a[MAX_PATH], link_a[MAX_PATH];
6046 ssize_t res, link_len;
6047 int loop_count = 0;
6049 if (is_windows_9x () == TRUE || !is_symlink (file))
6050 return (char *)file;
6052 if (w32_unicode_filenames)
6054 wchar_t file_w[MAX_PATH];
6056 filename_to_utf16 (file, file_w);
6057 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
6058 return (char *)file;
6059 filename_from_utf16 (link_w, link);
6061 else
6063 char file_a[MAX_PATH];
6065 filename_to_ansi (file, file_a);
6066 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6067 return (char *)file;
6068 filename_from_ansi (link_a, link);
6070 link_len = strlen (link);
6072 target[0] = '\0';
6073 do {
6075 /* Remove trailing slashes, as we want to resolve the last
6076 non-trivial part of the link name. */
6077 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6078 link[link_len--] = '\0';
6080 res = readlink (link, target, MAX_UTF8_PATH);
6081 if (res > 0)
6083 target[res] = '\0';
6084 if (!(IS_DEVICE_SEP (target[1])
6085 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6087 /* Target is relative. Append it to the directory part of
6088 the symlink, then copy the result back to target. */
6089 char *p = link + link_len;
6091 while (p > link && !IS_ANY_SEP (p[-1]))
6092 p--;
6093 strcpy (p, target);
6094 strcpy (target, link);
6096 /* Resolve any "." and ".." to get a fully-qualified file name
6097 in link[] again. */
6098 if (w32_unicode_filenames)
6100 filename_to_utf16 (target, target_w);
6101 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6102 if (link_len > 0)
6103 filename_from_utf16 (link_w, link);
6105 else
6107 filename_to_ansi (target, target_a);
6108 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6109 if (link_len > 0)
6110 filename_from_ansi (link_a, link);
6112 link_len = strlen (link);
6114 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6116 if (loop_count > 100)
6117 errno = ELOOP;
6119 if (target[0] == '\0') /* not a single call to readlink succeeded */
6120 return (char *)file;
6121 return target;
6125 /* Posix ACL emulation. */
6128 acl_valid (acl_t acl)
6130 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6133 char *
6134 acl_to_text (acl_t acl, ssize_t *size)
6136 LPTSTR str_acl;
6137 SECURITY_INFORMATION flags =
6138 OWNER_SECURITY_INFORMATION |
6139 GROUP_SECURITY_INFORMATION |
6140 DACL_SECURITY_INFORMATION;
6141 char *retval = NULL;
6142 ULONG local_size;
6143 int e = errno;
6145 errno = 0;
6147 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6149 errno = e;
6150 /* We don't want to mix heaps, so we duplicate the string in our
6151 heap and free the one allocated by the API. */
6152 retval = xstrdup (str_acl);
6153 if (size)
6154 *size = local_size;
6155 LocalFree (str_acl);
6157 else if (errno != ENOTSUP)
6158 errno = EINVAL;
6160 return retval;
6163 acl_t
6164 acl_from_text (const char *acl_str)
6166 PSECURITY_DESCRIPTOR psd, retval = NULL;
6167 ULONG sd_size;
6168 int e = errno;
6170 errno = 0;
6172 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6174 errno = e;
6175 retval = xmalloc (sd_size);
6176 memcpy (retval, psd, sd_size);
6177 LocalFree (psd);
6179 else if (errno != ENOTSUP)
6180 errno = EINVAL;
6182 return retval;
6186 acl_free (void *ptr)
6188 xfree (ptr);
6189 return 0;
6192 acl_t
6193 acl_get_file (const char *fname, acl_type_t type)
6195 PSECURITY_DESCRIPTOR psd = NULL;
6196 const char *filename;
6198 if (type == ACL_TYPE_ACCESS)
6200 DWORD sd_len, err;
6201 SECURITY_INFORMATION si =
6202 OWNER_SECURITY_INFORMATION |
6203 GROUP_SECURITY_INFORMATION |
6204 DACL_SECURITY_INFORMATION ;
6205 int e = errno;
6207 filename = map_w32_filename (fname, NULL);
6208 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6209 fname = chase_symlinks (filename);
6210 else
6211 fname = filename;
6213 errno = 0;
6214 if (!get_file_security (fname, si, psd, 0, &sd_len)
6215 && errno != ENOTSUP)
6217 err = GetLastError ();
6218 if (err == ERROR_INSUFFICIENT_BUFFER)
6220 psd = xmalloc (sd_len);
6221 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6223 xfree (psd);
6224 errno = EIO;
6225 psd = NULL;
6228 else if (err == ERROR_FILE_NOT_FOUND
6229 || err == ERROR_PATH_NOT_FOUND
6230 /* ERROR_INVALID_NAME is what we get if
6231 w32-unicode-filenames is nil and the file cannot
6232 be encoded in the current ANSI codepage. */
6233 || err == ERROR_INVALID_NAME)
6234 errno = ENOENT;
6235 else
6236 errno = EIO;
6238 else if (!errno)
6239 errno = e;
6241 else if (type != ACL_TYPE_DEFAULT)
6242 errno = EINVAL;
6244 return psd;
6248 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6250 TOKEN_PRIVILEGES old1, old2;
6251 DWORD err;
6252 int st = 0, retval = -1;
6253 SECURITY_INFORMATION flags = 0;
6254 PSID psidOwner, psidGroup;
6255 PACL pacl;
6256 BOOL dflt;
6257 BOOL dacl_present;
6258 int e;
6259 const char *filename;
6261 if (acl_valid (acl) != 0
6262 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6264 errno = EINVAL;
6265 return -1;
6268 if (type == ACL_TYPE_DEFAULT)
6270 errno = ENOSYS;
6271 return -1;
6274 filename = map_w32_filename (fname, NULL);
6275 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6276 fname = chase_symlinks (filename);
6277 else
6278 fname = filename;
6280 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6281 &dflt)
6282 && psidOwner)
6283 flags |= OWNER_SECURITY_INFORMATION;
6284 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6285 &dflt)
6286 && psidGroup)
6287 flags |= GROUP_SECURITY_INFORMATION;
6288 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6289 &pacl, &dflt)
6290 && dacl_present)
6291 flags |= DACL_SECURITY_INFORMATION;
6292 if (!flags)
6293 return 0;
6295 /* According to KB-245153, setting the owner will succeed if either:
6296 (1) the caller is the user who will be the new owner, and has the
6297 SE_TAKE_OWNERSHIP privilege, or
6298 (2) the caller has the SE_RESTORE privilege, in which case she can
6299 set any valid user or group as the owner
6301 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6302 privileges, and disregard any failures in obtaining them. If
6303 these privileges cannot be obtained, and do not already exist in
6304 the calling thread's security token, this function could fail
6305 with EPERM. */
6306 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6307 st++;
6308 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6309 st++;
6311 e = errno;
6312 errno = 0;
6313 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6314 DACL inheritance is involved, but it seems to preserve ownership
6315 better than SetNamedSecurityInfo, which is important e.g., in
6316 copy-file. */
6317 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6319 err = GetLastError ();
6321 if (errno != ENOTSUP)
6322 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6323 psidOwner, psidGroup, pacl, NULL);
6325 else
6326 err = ERROR_SUCCESS;
6327 if (err != ERROR_SUCCESS)
6329 if (errno == ENOTSUP)
6331 else if (err == ERROR_INVALID_OWNER
6332 || err == ERROR_NOT_ALL_ASSIGNED
6333 || err == ERROR_ACCESS_DENIED)
6335 /* Maybe the requested ACL and the one the file already has
6336 are identical, in which case we can silently ignore the
6337 failure. (And no, Windows doesn't.) */
6338 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6340 errno = EPERM;
6341 if (current_acl)
6343 char *acl_from = acl_to_text (current_acl, NULL);
6344 char *acl_to = acl_to_text (acl, NULL);
6346 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6348 retval = 0;
6349 errno = e;
6351 if (acl_from)
6352 acl_free (acl_from);
6353 if (acl_to)
6354 acl_free (acl_to);
6355 acl_free (current_acl);
6358 else if (err == ERROR_FILE_NOT_FOUND
6359 || err == ERROR_PATH_NOT_FOUND
6360 /* ERROR_INVALID_NAME is what we get if
6361 w32-unicode-filenames is nil and the file cannot be
6362 encoded in the current ANSI codepage. */
6363 || err == ERROR_INVALID_NAME)
6364 errno = ENOENT;
6365 else
6366 errno = EACCES;
6368 else
6370 retval = 0;
6371 errno = e;
6374 if (st)
6376 if (st >= 2)
6377 restore_privilege (&old2);
6378 restore_privilege (&old1);
6379 revert_to_self ();
6382 return retval;
6385 /* Return true if errno value ERRNUM indicates that ACLs are well
6386 supported on this system. ERRNUM should be an errno value obtained
6387 after an ACL-related system call fails. */
6388 bool
6389 acl_errno_valid (int errnum)
6391 switch (errnum)
6393 case EBUSY:
6394 case EINVAL:
6395 case ENOTSUP:
6396 return false;
6397 default:
6398 return true;
6403 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6404 have a fixed max size for file names, so we don't need the kind of
6405 alloc/malloc/realloc dance the gnulib version does. We also don't
6406 support FD-relative symlinks. */
6407 char *
6408 careadlinkat (int fd, char const *filename,
6409 char *buffer, size_t buffer_size,
6410 struct allocator const *alloc,
6411 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6413 char linkname[MAX_UTF8_PATH];
6414 ssize_t link_size;
6416 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6418 if (link_size > 0)
6420 char *retval = buffer;
6422 linkname[link_size++] = '\0';
6423 if (link_size > buffer_size)
6424 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6425 if (retval)
6426 memcpy (retval, linkname, link_size);
6428 return retval;
6430 return NULL;
6434 w32_copy_file (const char *from, const char *to,
6435 int keep_time, int preserve_ownership, int copy_acls)
6437 acl_t acl = NULL;
6438 BOOL copy_result;
6439 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6440 char from_a[MAX_PATH], to_a[MAX_PATH];
6442 /* We ignore preserve_ownership for now. */
6443 preserve_ownership = preserve_ownership;
6445 if (copy_acls)
6447 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6448 if (acl == NULL && acl_errno_valid (errno))
6449 return -2;
6451 if (w32_unicode_filenames)
6453 filename_to_utf16 (from, from_w);
6454 filename_to_utf16 (to, to_w);
6455 copy_result = CopyFileW (from_w, to_w, FALSE);
6457 else
6459 filename_to_ansi (from, from_a);
6460 filename_to_ansi (to, to_a);
6461 copy_result = CopyFileA (from_a, to_a, FALSE);
6463 if (!copy_result)
6465 /* CopyFile doesn't set errno when it fails. By far the most
6466 "popular" reason is that the target is read-only. */
6467 DWORD err = GetLastError ();
6469 switch (err)
6471 case ERROR_FILE_NOT_FOUND:
6472 errno = ENOENT;
6473 break;
6474 case ERROR_ACCESS_DENIED:
6475 errno = EACCES;
6476 break;
6477 case ERROR_ENCRYPTION_FAILED:
6478 errno = EIO;
6479 break;
6480 default:
6481 errno = EPERM;
6482 break;
6485 if (acl)
6486 acl_free (acl);
6487 return -1;
6489 /* CopyFile retains the timestamp by default. However, see
6490 "Community Additions" for CopyFile: it sounds like that is not
6491 entirely true. Testing on Windows XP confirms that modified time
6492 is copied, but creation and last-access times are not.
6493 FIXME? */
6494 else if (!keep_time)
6496 struct timespec now;
6497 DWORD attributes;
6499 if (w32_unicode_filenames)
6501 /* Ensure file is writable while its times are set. */
6502 attributes = GetFileAttributesW (to_w);
6503 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6504 now = current_timespec ();
6505 if (set_file_times (-1, to, now, now))
6507 /* Restore original attributes. */
6508 SetFileAttributesW (to_w, attributes);
6509 if (acl)
6510 acl_free (acl);
6511 return -3;
6513 /* Restore original attributes. */
6514 SetFileAttributesW (to_w, attributes);
6516 else
6518 attributes = GetFileAttributesA (to_a);
6519 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6520 now = current_timespec ();
6521 if (set_file_times (-1, to, now, now))
6523 SetFileAttributesA (to_a, attributes);
6524 if (acl)
6525 acl_free (acl);
6526 return -3;
6528 SetFileAttributesA (to_a, attributes);
6531 if (acl != NULL)
6533 bool fail =
6534 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6535 acl_free (acl);
6536 if (fail && acl_errno_valid (errno))
6537 return -4;
6540 return 0;
6544 /* Support for browsing other processes and their attributes. See
6545 process.c for the Lisp bindings. */
6547 /* Helper wrapper functions. */
6549 static HANDLE WINAPI
6550 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6552 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6554 if (g_b_init_create_toolhelp32_snapshot == 0)
6556 g_b_init_create_toolhelp32_snapshot = 1;
6557 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6558 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6559 "CreateToolhelp32Snapshot");
6561 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6563 return INVALID_HANDLE_VALUE;
6565 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6568 static BOOL WINAPI
6569 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6571 static Process32First_Proc s_pfn_Process32_First = NULL;
6573 if (g_b_init_process32_first == 0)
6575 g_b_init_process32_first = 1;
6576 s_pfn_Process32_First = (Process32First_Proc)
6577 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6578 "Process32First");
6580 if (s_pfn_Process32_First == NULL)
6582 return FALSE;
6584 return (s_pfn_Process32_First (hSnapshot, lppe));
6587 static BOOL WINAPI
6588 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6590 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6592 if (g_b_init_process32_next == 0)
6594 g_b_init_process32_next = 1;
6595 s_pfn_Process32_Next = (Process32Next_Proc)
6596 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6597 "Process32Next");
6599 if (s_pfn_Process32_Next == NULL)
6601 return FALSE;
6603 return (s_pfn_Process32_Next (hSnapshot, lppe));
6606 static BOOL WINAPI
6607 open_thread_token (HANDLE ThreadHandle,
6608 DWORD DesiredAccess,
6609 BOOL OpenAsSelf,
6610 PHANDLE TokenHandle)
6612 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6613 HMODULE hm_advapi32 = NULL;
6614 if (is_windows_9x () == TRUE)
6616 SetLastError (ERROR_NOT_SUPPORTED);
6617 return FALSE;
6619 if (g_b_init_open_thread_token == 0)
6621 g_b_init_open_thread_token = 1;
6622 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6623 s_pfn_Open_Thread_Token =
6624 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6626 if (s_pfn_Open_Thread_Token == NULL)
6628 SetLastError (ERROR_NOT_SUPPORTED);
6629 return FALSE;
6631 return (
6632 s_pfn_Open_Thread_Token (
6633 ThreadHandle,
6634 DesiredAccess,
6635 OpenAsSelf,
6636 TokenHandle)
6640 static BOOL WINAPI
6641 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6643 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6644 HMODULE hm_advapi32 = NULL;
6645 if (is_windows_9x () == TRUE)
6647 return FALSE;
6649 if (g_b_init_impersonate_self == 0)
6651 g_b_init_impersonate_self = 1;
6652 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6653 s_pfn_Impersonate_Self =
6654 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6656 if (s_pfn_Impersonate_Self == NULL)
6658 return FALSE;
6660 return s_pfn_Impersonate_Self (ImpersonationLevel);
6663 static BOOL WINAPI
6664 revert_to_self (void)
6666 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6667 HMODULE hm_advapi32 = NULL;
6668 if (is_windows_9x () == TRUE)
6670 return FALSE;
6672 if (g_b_init_revert_to_self == 0)
6674 g_b_init_revert_to_self = 1;
6675 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6676 s_pfn_Revert_To_Self =
6677 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6679 if (s_pfn_Revert_To_Self == NULL)
6681 return FALSE;
6683 return s_pfn_Revert_To_Self ();
6686 static BOOL WINAPI
6687 get_process_memory_info (HANDLE h_proc,
6688 PPROCESS_MEMORY_COUNTERS mem_counters,
6689 DWORD bufsize)
6691 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6692 HMODULE hm_psapi = NULL;
6693 if (is_windows_9x () == TRUE)
6695 return FALSE;
6697 if (g_b_init_get_process_memory_info == 0)
6699 g_b_init_get_process_memory_info = 1;
6700 hm_psapi = LoadLibrary ("Psapi.dll");
6701 if (hm_psapi)
6702 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6703 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6705 if (s_pfn_Get_Process_Memory_Info == NULL)
6707 return FALSE;
6709 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6712 static BOOL WINAPI
6713 get_process_working_set_size (HANDLE h_proc,
6714 PSIZE_T minrss,
6715 PSIZE_T maxrss)
6717 static GetProcessWorkingSetSize_Proc
6718 s_pfn_Get_Process_Working_Set_Size = NULL;
6720 if (is_windows_9x () == TRUE)
6722 return FALSE;
6724 if (g_b_init_get_process_working_set_size == 0)
6726 g_b_init_get_process_working_set_size = 1;
6727 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6728 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6729 "GetProcessWorkingSetSize");
6731 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6733 return FALSE;
6735 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6738 static BOOL WINAPI
6739 global_memory_status (MEMORYSTATUS *buf)
6741 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6743 if (is_windows_9x () == TRUE)
6745 return FALSE;
6747 if (g_b_init_global_memory_status == 0)
6749 g_b_init_global_memory_status = 1;
6750 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6751 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6752 "GlobalMemoryStatus");
6754 if (s_pfn_Global_Memory_Status == NULL)
6756 return FALSE;
6758 return s_pfn_Global_Memory_Status (buf);
6761 static BOOL WINAPI
6762 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6764 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6766 if (is_windows_9x () == TRUE)
6768 return FALSE;
6770 if (g_b_init_global_memory_status_ex == 0)
6772 g_b_init_global_memory_status_ex = 1;
6773 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6774 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6775 "GlobalMemoryStatusEx");
6777 if (s_pfn_Global_Memory_Status_Ex == NULL)
6779 return FALSE;
6781 return s_pfn_Global_Memory_Status_Ex (buf);
6784 Lisp_Object
6785 list_system_processes (void)
6787 Lisp_Object proclist = Qnil;
6788 HANDLE h_snapshot;
6790 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6792 if (h_snapshot != INVALID_HANDLE_VALUE)
6794 PROCESSENTRY32 proc_entry;
6795 DWORD proc_id;
6796 BOOL res;
6798 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6799 for (res = process32_first (h_snapshot, &proc_entry); res;
6800 res = process32_next (h_snapshot, &proc_entry))
6802 proc_id = proc_entry.th32ProcessID;
6803 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6806 CloseHandle (h_snapshot);
6807 proclist = Fnreverse (proclist);
6810 return proclist;
6813 static int
6814 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6816 TOKEN_PRIVILEGES priv;
6817 DWORD priv_size = sizeof (priv);
6818 DWORD opriv_size = sizeof (*old_priv);
6819 HANDLE h_token = NULL;
6820 HANDLE h_thread = GetCurrentThread ();
6821 int ret_val = 0;
6822 BOOL res;
6824 res = open_thread_token (h_thread,
6825 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6826 FALSE, &h_token);
6827 if (!res && GetLastError () == ERROR_NO_TOKEN)
6829 if (impersonate_self (SecurityImpersonation))
6830 res = open_thread_token (h_thread,
6831 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6832 FALSE, &h_token);
6834 if (res)
6836 priv.PrivilegeCount = 1;
6837 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6838 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6839 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6840 old_priv, &opriv_size)
6841 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6842 ret_val = 1;
6844 if (h_token)
6845 CloseHandle (h_token);
6847 return ret_val;
6850 static int
6851 restore_privilege (TOKEN_PRIVILEGES *priv)
6853 DWORD priv_size = sizeof (*priv);
6854 HANDLE h_token = NULL;
6855 int ret_val = 0;
6857 if (open_thread_token (GetCurrentThread (),
6858 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6859 FALSE, &h_token))
6861 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6862 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6863 ret_val = 1;
6865 if (h_token)
6866 CloseHandle (h_token);
6868 return ret_val;
6871 static Lisp_Object
6872 ltime (ULONGLONG time_100ns)
6874 ULONGLONG time_sec = time_100ns / 10000000;
6875 int subsec = time_100ns % 10000000;
6876 return list4i (time_sec >> 16, time_sec & 0xffff,
6877 subsec / 10, subsec % 10 * 100000);
6880 #define U64_TO_LISP_TIME(time) ltime (time)
6882 static int
6883 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6884 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6885 double *pcpu)
6887 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6888 ULONGLONG tem1, tem2, tem3, tem;
6890 if (!h_proc
6891 || !get_process_times_fn
6892 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6893 &ft_kernel, &ft_user))
6894 return 0;
6896 GetSystemTimeAsFileTime (&ft_current);
6898 FILETIME_TO_U64 (tem1, ft_kernel);
6899 *stime = U64_TO_LISP_TIME (tem1);
6901 FILETIME_TO_U64 (tem2, ft_user);
6902 *utime = U64_TO_LISP_TIME (tem2);
6904 tem3 = tem1 + tem2;
6905 *ttime = U64_TO_LISP_TIME (tem3);
6907 FILETIME_TO_U64 (tem, ft_creation);
6908 /* Process no 4 (System) returns zero creation time. */
6909 if (tem)
6910 tem -= utc_base;
6911 *ctime = U64_TO_LISP_TIME (tem);
6913 if (tem)
6915 FILETIME_TO_U64 (tem3, ft_current);
6916 tem = (tem3 - utc_base) - tem;
6918 *etime = U64_TO_LISP_TIME (tem);
6920 if (tem)
6922 *pcpu = 100.0 * (tem1 + tem2) / tem;
6923 if (*pcpu > 100)
6924 *pcpu = 100.0;
6926 else
6927 *pcpu = 0;
6929 return 1;
6932 Lisp_Object
6933 system_process_attributes (Lisp_Object pid)
6935 Lisp_Object attrs = Qnil;
6936 Lisp_Object cmd_str, decoded_cmd, tem;
6937 HANDLE h_snapshot, h_proc;
6938 DWORD proc_id;
6939 int found_proc = 0;
6940 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6941 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6942 DWORD glength = sizeof (gname);
6943 HANDLE token = NULL;
6944 SID_NAME_USE user_type;
6945 unsigned char *buf = NULL;
6946 DWORD blen = 0;
6947 TOKEN_USER user_token;
6948 TOKEN_PRIMARY_GROUP group_token;
6949 unsigned euid;
6950 unsigned egid;
6951 PROCESS_MEMORY_COUNTERS mem;
6952 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6953 SIZE_T minrss, maxrss;
6954 MEMORYSTATUS memst;
6955 MEMORY_STATUS_EX memstex;
6956 double totphys = 0.0;
6957 Lisp_Object ctime, stime, utime, etime, ttime;
6958 double pcpu;
6959 BOOL result = FALSE;
6961 CHECK_NUMBER_OR_FLOAT (pid);
6962 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6964 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6966 if (h_snapshot != INVALID_HANDLE_VALUE)
6968 PROCESSENTRY32 pe;
6969 BOOL res;
6971 pe.dwSize = sizeof (PROCESSENTRY32);
6972 for (res = process32_first (h_snapshot, &pe); res;
6973 res = process32_next (h_snapshot, &pe))
6975 if (proc_id == pe.th32ProcessID)
6977 if (proc_id == 0)
6978 decoded_cmd = build_string ("Idle");
6979 else
6981 /* Decode the command name from locale-specific
6982 encoding. */
6983 cmd_str = build_unibyte_string (pe.szExeFile);
6985 decoded_cmd =
6986 code_convert_string_norecord (cmd_str,
6987 Vlocale_coding_system, 0);
6989 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6990 attrs = Fcons (Fcons (Qppid,
6991 make_fixnum_or_float (pe.th32ParentProcessID)),
6992 attrs);
6993 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6994 attrs);
6995 attrs = Fcons (Fcons (Qthcount,
6996 make_fixnum_or_float (pe.cntThreads)),
6997 attrs);
6998 found_proc = 1;
6999 break;
7003 CloseHandle (h_snapshot);
7006 if (!found_proc)
7007 return Qnil;
7009 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7010 FALSE, proc_id);
7011 /* If we were denied a handle to the process, try again after
7012 enabling the SeDebugPrivilege in our process. */
7013 if (!h_proc)
7015 TOKEN_PRIVILEGES priv_current;
7017 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
7019 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7020 FALSE, proc_id);
7021 restore_privilege (&priv_current);
7022 revert_to_self ();
7025 if (h_proc)
7027 result = open_process_token (h_proc, TOKEN_QUERY, &token);
7028 if (result)
7030 result = get_token_information (token, TokenUser, NULL, 0, &blen);
7031 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7033 buf = xmalloc (blen);
7034 result = get_token_information (token, TokenUser,
7035 (LPVOID)buf, blen, &needed);
7036 if (result)
7038 memcpy (&user_token, buf, sizeof (user_token));
7039 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
7041 euid = get_rid (user_token.User.Sid);
7042 result = lookup_account_sid (NULL, user_token.User.Sid,
7043 uname, &ulength,
7044 domain, &dlength,
7045 &user_type);
7046 if (result)
7047 w32_add_to_cache (user_token.User.Sid, euid, uname);
7048 else
7050 strcpy (uname, "unknown");
7051 result = TRUE;
7054 ulength = strlen (uname);
7058 if (result)
7060 /* Determine a reasonable euid and gid values. */
7061 if (xstrcasecmp ("administrator", uname) == 0)
7063 euid = 500; /* well-known Administrator uid */
7064 egid = 513; /* well-known None gid */
7066 else
7068 /* Get group id and name. */
7069 result = get_token_information (token, TokenPrimaryGroup,
7070 (LPVOID)buf, blen, &needed);
7071 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7073 buf = xrealloc (buf, blen = needed);
7074 result = get_token_information (token, TokenPrimaryGroup,
7075 (LPVOID)buf, blen, &needed);
7077 if (result)
7079 memcpy (&group_token, buf, sizeof (group_token));
7080 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7082 egid = get_rid (group_token.PrimaryGroup);
7083 dlength = sizeof (domain);
7084 result =
7085 lookup_account_sid (NULL, group_token.PrimaryGroup,
7086 gname, &glength, NULL, &dlength,
7087 &user_type);
7088 if (result)
7089 w32_add_to_cache (group_token.PrimaryGroup,
7090 egid, gname);
7091 else
7093 strcpy (gname, "None");
7094 result = TRUE;
7097 glength = strlen (gname);
7101 xfree (buf);
7103 if (!result)
7105 if (!is_windows_9x ())
7107 /* We couldn't open the process token, presumably because of
7108 insufficient access rights. Assume this process is run
7109 by the system. */
7110 strcpy (uname, "SYSTEM");
7111 strcpy (gname, "None");
7112 euid = 18; /* SYSTEM */
7113 egid = 513; /* None */
7114 glength = strlen (gname);
7115 ulength = strlen (uname);
7117 /* If we are running under Windows 9X, where security calls are
7118 not supported, we assume all processes are run by the current
7119 user. */
7120 else if (GetUserName (uname, &ulength))
7122 if (xstrcasecmp ("administrator", uname) == 0)
7123 euid = 0;
7124 else
7125 euid = 123;
7126 egid = euid;
7127 strcpy (gname, "None");
7128 glength = strlen (gname);
7129 ulength = strlen (uname);
7131 else
7133 euid = 123;
7134 egid = 123;
7135 strcpy (uname, "administrator");
7136 ulength = strlen (uname);
7137 strcpy (gname, "None");
7138 glength = strlen (gname);
7140 if (token)
7141 CloseHandle (token);
7144 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7145 tem = make_unibyte_string (uname, ulength);
7146 attrs = Fcons (Fcons (Quser,
7147 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7148 attrs);
7149 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7150 tem = make_unibyte_string (gname, glength);
7151 attrs = Fcons (Fcons (Qgroup,
7152 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7153 attrs);
7155 if (global_memory_status_ex (&memstex))
7156 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7157 totphys = memstex.ullTotalPhys / 1024.0;
7158 #else
7159 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7160 double, so we need to do this for it... */
7162 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7163 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7164 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7166 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7168 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7169 else if (global_memory_status (&memst))
7170 totphys = memst.dwTotalPhys / 1024.0;
7172 if (h_proc
7173 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7174 sizeof (mem_ex)))
7176 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7178 attrs = Fcons (Fcons (Qmajflt,
7179 make_fixnum_or_float (mem_ex.PageFaultCount)),
7180 attrs);
7181 attrs = Fcons (Fcons (Qvsize,
7182 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7183 attrs);
7184 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7185 if (totphys)
7186 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7188 else if (h_proc
7189 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7191 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7193 attrs = Fcons (Fcons (Qmajflt,
7194 make_fixnum_or_float (mem.PageFaultCount)),
7195 attrs);
7196 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7197 if (totphys)
7198 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7200 else if (h_proc
7201 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7203 DWORD rss = maxrss / 1024;
7205 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7206 if (totphys)
7207 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7210 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7212 attrs = Fcons (Fcons (Qutime, utime), attrs);
7213 attrs = Fcons (Fcons (Qstime, stime), attrs);
7214 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7215 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7216 attrs = Fcons (Fcons (Qetime, etime), attrs);
7217 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7220 /* FIXME: Retrieve command line by walking the PEB of the process. */
7222 if (h_proc)
7223 CloseHandle (h_proc);
7224 return attrs;
7228 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7229 unsigned long long *totalswap, unsigned long long *freeswap)
7231 MEMORYSTATUS memst;
7232 MEMORY_STATUS_EX memstex;
7234 /* Use GlobalMemoryStatusEx if available, as it can report more than
7235 2GB of memory. */
7236 if (global_memory_status_ex (&memstex))
7238 *totalram = memstex.ullTotalPhys;
7239 *freeram = memstex.ullAvailPhys;
7240 *totalswap = memstex.ullTotalPageFile;
7241 *freeswap = memstex.ullAvailPageFile;
7242 return 0;
7244 else if (global_memory_status (&memst))
7246 *totalram = memst.dwTotalPhys;
7247 *freeram = memst.dwAvailPhys;
7248 *totalswap = memst.dwTotalPageFile;
7249 *freeswap = memst.dwAvailPageFile;
7250 return 0;
7252 else
7253 return -1;
7257 /* Wrappers for winsock functions to map between our file descriptors
7258 and winsock's handles; also set h_errno for convenience.
7260 To allow Emacs to run on systems which don't have winsock support
7261 installed, we dynamically link to winsock on startup if present, and
7262 otherwise provide the minimum necessary functionality
7263 (eg. gethostname). */
7265 /* function pointers for relevant socket functions */
7266 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7267 void (PASCAL *pfn_WSASetLastError) (int iError);
7268 int (PASCAL *pfn_WSAGetLastError) (void);
7269 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7270 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7271 WSANETWORKEVENTS *NetworkEvents);
7273 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7274 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7275 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7276 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7277 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7278 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7279 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7280 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7281 int (PASCAL *pfn_closesocket) (SOCKET s);
7282 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7283 int (PASCAL *pfn_WSACleanup) (void);
7285 u_short (PASCAL *pfn_htons) (u_short hostshort);
7286 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7287 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7288 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7289 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7290 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7291 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7292 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7293 const char * optval, int optlen);
7294 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7295 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7296 int * namelen);
7297 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7298 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7299 struct sockaddr * from, int * fromlen);
7300 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7301 const struct sockaddr * to, int tolen);
7303 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7304 const struct addrinfo *, struct addrinfo **);
7305 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7307 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7308 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7309 #ifndef HANDLE_FLAG_INHERIT
7310 #define HANDLE_FLAG_INHERIT 1
7311 #endif
7313 HANDLE winsock_lib;
7314 static int winsock_inuse;
7316 BOOL term_winsock (void);
7318 BOOL
7319 term_winsock (void)
7321 if (winsock_lib != NULL && winsock_inuse == 0)
7323 release_listen_threads ();
7324 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7325 after WSAStartup returns successfully, but it seems reasonable
7326 to allow unloading winsock anyway in that case. */
7327 if (pfn_WSACleanup () == 0 ||
7328 pfn_WSAGetLastError () == WSAENETDOWN)
7330 if (FreeLibrary (winsock_lib))
7331 winsock_lib = NULL;
7332 return TRUE;
7335 return FALSE;
7338 BOOL
7339 init_winsock (int load_now)
7341 WSADATA winsockData;
7343 if (winsock_lib != NULL)
7344 return TRUE;
7346 pfn_SetHandleInformation
7347 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7348 "SetHandleInformation");
7350 winsock_lib = LoadLibrary ("Ws2_32.dll");
7352 if (winsock_lib != NULL)
7354 /* dynamically link to socket functions */
7356 #define LOAD_PROC(fn) \
7357 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7358 goto fail;
7360 LOAD_PROC (WSAStartup);
7361 LOAD_PROC (WSASetLastError);
7362 LOAD_PROC (WSAGetLastError);
7363 LOAD_PROC (WSAEventSelect);
7364 LOAD_PROC (WSAEnumNetworkEvents);
7365 LOAD_PROC (WSACreateEvent);
7366 LOAD_PROC (WSACloseEvent);
7367 LOAD_PROC (socket);
7368 LOAD_PROC (bind);
7369 LOAD_PROC (connect);
7370 LOAD_PROC (ioctlsocket);
7371 LOAD_PROC (recv);
7372 LOAD_PROC (send);
7373 LOAD_PROC (closesocket);
7374 LOAD_PROC (shutdown);
7375 LOAD_PROC (htons);
7376 LOAD_PROC (ntohs);
7377 LOAD_PROC (inet_addr);
7378 LOAD_PROC (gethostname);
7379 LOAD_PROC (gethostbyname);
7380 LOAD_PROC (getservbyname);
7381 LOAD_PROC (getpeername);
7382 LOAD_PROC (WSACleanup);
7383 LOAD_PROC (setsockopt);
7384 LOAD_PROC (listen);
7385 LOAD_PROC (getsockname);
7386 LOAD_PROC (accept);
7387 LOAD_PROC (recvfrom);
7388 LOAD_PROC (sendto);
7389 #undef LOAD_PROC
7391 /* Try loading functions not available before XP. */
7392 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7393 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7394 /* Paranoia: these two functions should go together, so if one
7395 is absent, we cannot use the other. */
7396 if (pfn_getaddrinfo == NULL)
7397 pfn_freeaddrinfo = NULL;
7398 else if (pfn_freeaddrinfo == NULL)
7399 pfn_getaddrinfo = NULL;
7401 /* specify version 1.1 of winsock */
7402 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7404 if (winsockData.wVersion != 0x101)
7405 goto fail;
7407 if (!load_now)
7409 /* Report that winsock exists and is usable, but leave
7410 socket functions disabled. I am assuming that calling
7411 WSAStartup does not require any network interaction,
7412 and in particular does not cause or require a dial-up
7413 connection to be established. */
7415 pfn_WSACleanup ();
7416 FreeLibrary (winsock_lib);
7417 winsock_lib = NULL;
7419 winsock_inuse = 0;
7420 return TRUE;
7423 fail:
7424 FreeLibrary (winsock_lib);
7425 winsock_lib = NULL;
7428 return FALSE;
7432 int h_errno = 0;
7434 /* Function to map winsock error codes to errno codes for those errno
7435 code defined in errno.h (errno values not defined by errno.h are
7436 already in nt/inc/sys/socket.h). */
7437 static void
7438 set_errno (void)
7440 int wsa_err;
7442 h_errno = 0;
7443 if (winsock_lib == NULL)
7444 wsa_err = EINVAL;
7445 else
7446 wsa_err = pfn_WSAGetLastError ();
7448 switch (wsa_err)
7450 case WSAEACCES: errno = EACCES; break;
7451 case WSAEBADF: errno = EBADF; break;
7452 case WSAEFAULT: errno = EFAULT; break;
7453 case WSAEINTR: errno = EINTR; break;
7454 case WSAEINVAL: errno = EINVAL; break;
7455 case WSAEMFILE: errno = EMFILE; break;
7456 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7457 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7458 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7459 case WSAENOTCONN: errno = ENOTCONN; break;
7460 default: errno = wsa_err; break;
7464 static void
7465 check_errno (void)
7467 h_errno = 0;
7468 if (winsock_lib != NULL)
7469 pfn_WSASetLastError (0);
7472 /* Extend strerror to handle the winsock-specific error codes. */
7473 struct {
7474 int errnum;
7475 const char * msg;
7476 } _wsa_errlist[] = {
7477 {WSAEINTR , "Interrupted function call"},
7478 {WSAEBADF , "Bad file descriptor"},
7479 {WSAEACCES , "Permission denied"},
7480 {WSAEFAULT , "Bad address"},
7481 {WSAEINVAL , "Invalid argument"},
7482 {WSAEMFILE , "Too many open files"},
7484 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7485 {WSAEINPROGRESS , "Operation now in progress"},
7486 {WSAEALREADY , "Operation already in progress"},
7487 {WSAENOTSOCK , "Socket operation on non-socket"},
7488 {WSAEDESTADDRREQ , "Destination address required"},
7489 {WSAEMSGSIZE , "Message too long"},
7490 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7491 {WSAENOPROTOOPT , "Bad protocol option"},
7492 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7493 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7494 {WSAEOPNOTSUPP , "Operation not supported"},
7495 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7496 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7497 {WSAEADDRINUSE , "Address already in use"},
7498 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7499 {WSAENETDOWN , "Network is down"},
7500 {WSAENETUNREACH , "Network is unreachable"},
7501 {WSAENETRESET , "Network dropped connection on reset"},
7502 {WSAECONNABORTED , "Software caused connection abort"},
7503 {WSAECONNRESET , "Connection reset by peer"},
7504 {WSAENOBUFS , "No buffer space available"},
7505 {WSAEISCONN , "Socket is already connected"},
7506 {WSAENOTCONN , "Socket is not connected"},
7507 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7508 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7509 {WSAETIMEDOUT , "Connection timed out"},
7510 {WSAECONNREFUSED , "Connection refused"},
7511 {WSAELOOP , "Network loop"}, /* not sure */
7512 {WSAENAMETOOLONG , "Name is too long"},
7513 {WSAEHOSTDOWN , "Host is down"},
7514 {WSAEHOSTUNREACH , "No route to host"},
7515 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7516 {WSAEPROCLIM , "Too many processes"},
7517 {WSAEUSERS , "Too many users"}, /* not sure */
7518 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7519 {WSAESTALE , "Data is stale"}, /* not sure */
7520 {WSAEREMOTE , "Remote error"}, /* not sure */
7522 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7523 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7524 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7525 {WSAEDISCON , "Graceful shutdown in progress"},
7526 #ifdef WSAENOMORE
7527 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7528 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7529 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7530 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7531 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7532 {WSASYSCALLFAILURE , "System call failure"},
7533 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7534 {WSATYPE_NOT_FOUND , "Class type not found"},
7535 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7536 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7537 {WSAEREFUSED , "Operation refused"}, /* not sure */
7538 #endif
7540 {WSAHOST_NOT_FOUND , "Host not found"},
7541 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7542 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7543 {WSANO_DATA , "Valid name, no data record of requested type"},
7545 {-1, NULL}
7548 char *
7549 sys_strerror (int error_no)
7551 int i;
7552 static char unknown_msg[40];
7554 if (error_no >= 0 && error_no < sys_nerr)
7555 return sys_errlist[error_no];
7557 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7558 if (_wsa_errlist[i].errnum == error_no)
7559 return (char *)_wsa_errlist[i].msg;
7561 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7562 return unknown_msg;
7565 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7566 but I believe the method of keeping the socket handle separate (and
7567 insuring it is not inheritable) is the correct one. */
7569 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7571 static int socket_to_fd (SOCKET s);
7574 sys_socket (int af, int type, int protocol)
7576 SOCKET s;
7578 if (winsock_lib == NULL)
7580 errno = ENETDOWN;
7581 return -1;
7584 check_errno ();
7586 /* call the real socket function */
7587 s = pfn_socket (af, type, protocol);
7589 if (s != INVALID_SOCKET)
7590 return socket_to_fd (s);
7592 set_errno ();
7593 return -1;
7596 /* Convert a SOCKET to a file descriptor. */
7597 static int
7598 socket_to_fd (SOCKET s)
7600 int fd;
7601 child_process * cp;
7603 /* Although under NT 3.5 _open_osfhandle will accept a socket
7604 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7605 that does not work under NT 3.1. However, we can get the same
7606 effect by using a backdoor function to replace an existing
7607 descriptor handle with the one we want. */
7609 /* allocate a file descriptor (with appropriate flags) */
7610 fd = _open ("NUL:", _O_RDWR);
7611 if (fd >= 0)
7613 /* Make a non-inheritable copy of the socket handle. Note
7614 that it is possible that sockets aren't actually kernel
7615 handles, which appears to be the case on Windows 9x when
7616 the MS Proxy winsock client is installed. */
7618 /* Apparently there is a bug in NT 3.51 with some service
7619 packs, which prevents using DuplicateHandle to make a
7620 socket handle non-inheritable (causes WSACleanup to
7621 hang). The work-around is to use SetHandleInformation
7622 instead if it is available and implemented. */
7623 if (pfn_SetHandleInformation)
7625 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7627 else
7629 HANDLE parent = GetCurrentProcess ();
7630 HANDLE new_s = INVALID_HANDLE_VALUE;
7632 if (DuplicateHandle (parent,
7633 (HANDLE) s,
7634 parent,
7635 &new_s,
7637 FALSE,
7638 DUPLICATE_SAME_ACCESS))
7640 /* It is possible that DuplicateHandle succeeds even
7641 though the socket wasn't really a kernel handle,
7642 because a real handle has the same value. So
7643 test whether the new handle really is a socket. */
7644 unsigned long nonblocking = 0;
7645 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7647 pfn_closesocket (s);
7648 s = (SOCKET) new_s;
7650 else
7652 CloseHandle (new_s);
7657 eassert (fd < MAXDESC);
7658 fd_info[fd].hnd = (HANDLE) s;
7660 /* set our own internal flags */
7661 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7663 cp = new_child ();
7664 if (cp)
7666 cp->fd = fd;
7667 cp->status = STATUS_READ_ACKNOWLEDGED;
7669 /* attach child_process to fd_info */
7670 if (fd_info[ fd ].cp != NULL)
7672 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7673 emacs_abort ();
7676 fd_info[ fd ].cp = cp;
7678 /* success! */
7679 winsock_inuse++; /* count open sockets */
7680 return fd;
7683 /* clean up */
7684 _close (fd);
7686 else
7687 pfn_closesocket (s);
7688 errno = EMFILE;
7689 return -1;
7693 sys_bind (int s, const struct sockaddr * addr, int namelen)
7695 if (winsock_lib == NULL)
7697 errno = ENOTSOCK;
7698 return SOCKET_ERROR;
7701 check_errno ();
7702 if (fd_info[s].flags & FILE_SOCKET)
7704 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7705 if (rc == SOCKET_ERROR)
7706 set_errno ();
7707 return rc;
7709 errno = ENOTSOCK;
7710 return SOCKET_ERROR;
7714 sys_connect (int s, const struct sockaddr * name, int namelen)
7716 if (winsock_lib == NULL)
7718 errno = ENOTSOCK;
7719 return SOCKET_ERROR;
7722 check_errno ();
7723 if (fd_info[s].flags & FILE_SOCKET)
7725 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7726 if (rc == SOCKET_ERROR)
7728 set_errno ();
7729 /* If this is a non-blocking 'connect', set the bit in flags
7730 that will tell reader_thread to wait for connection
7731 before trying to read. */
7732 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7734 errno = EINPROGRESS; /* that's what process.c expects */
7735 fd_info[s].flags |= FILE_CONNECT;
7738 return rc;
7740 errno = ENOTSOCK;
7741 return SOCKET_ERROR;
7744 u_short
7745 sys_htons (u_short hostshort)
7747 return (winsock_lib != NULL) ?
7748 pfn_htons (hostshort) : hostshort;
7751 u_short
7752 sys_ntohs (u_short netshort)
7754 return (winsock_lib != NULL) ?
7755 pfn_ntohs (netshort) : netshort;
7758 unsigned long
7759 sys_inet_addr (const char * cp)
7761 return (winsock_lib != NULL) ?
7762 pfn_inet_addr (cp) : INADDR_NONE;
7766 sys_gethostname (char * name, int namelen)
7768 if (winsock_lib != NULL)
7770 int retval;
7772 check_errno ();
7773 retval = pfn_gethostname (name, namelen);
7774 if (retval == SOCKET_ERROR)
7775 set_errno ();
7776 return retval;
7779 if (namelen > MAX_COMPUTERNAME_LENGTH)
7780 return !GetComputerName (name, (DWORD *)&namelen);
7782 errno = EFAULT;
7783 return SOCKET_ERROR;
7786 struct hostent *
7787 sys_gethostbyname (const char * name)
7789 struct hostent * host;
7790 int h_err = h_errno;
7792 if (winsock_lib == NULL)
7794 h_errno = NO_RECOVERY;
7795 errno = ENETDOWN;
7796 return NULL;
7799 check_errno ();
7800 host = pfn_gethostbyname (name);
7801 if (!host)
7803 set_errno ();
7804 h_errno = errno;
7806 else
7807 h_errno = h_err;
7808 return host;
7811 struct servent *
7812 sys_getservbyname (const char * name, const char * proto)
7814 struct servent * serv;
7816 if (winsock_lib == NULL)
7818 errno = ENETDOWN;
7819 return NULL;
7822 check_errno ();
7823 serv = pfn_getservbyname (name, proto);
7824 if (!serv)
7825 set_errno ();
7826 return serv;
7830 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7832 if (winsock_lib == NULL)
7834 errno = ENETDOWN;
7835 return SOCKET_ERROR;
7838 check_errno ();
7839 if (fd_info[s].flags & FILE_SOCKET)
7841 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7842 if (rc == SOCKET_ERROR)
7843 set_errno ();
7844 return rc;
7846 errno = ENOTSOCK;
7847 return SOCKET_ERROR;
7851 sys_getaddrinfo (const char *node, const char *service,
7852 const struct addrinfo *hints, struct addrinfo **res)
7854 int rc;
7856 if (winsock_lib == NULL)
7858 errno = ENETDOWN;
7859 return SOCKET_ERROR;
7862 check_errno ();
7863 if (pfn_getaddrinfo)
7864 rc = pfn_getaddrinfo (node, service, hints, res);
7865 else
7867 int port = 0;
7868 struct hostent *host_info;
7869 struct gai_storage {
7870 struct addrinfo addrinfo;
7871 struct sockaddr_in sockaddr_in;
7872 } *gai_storage;
7874 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7875 if (hints && hints->ai_flags != 0)
7876 return WSAEINVAL;
7877 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7878 if (!node)
7879 return WSAHOST_NOT_FOUND;
7881 if (service)
7883 const char *protocol =
7884 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7885 struct servent *srv = sys_getservbyname (service, protocol);
7887 if (srv)
7888 port = srv->s_port;
7889 else if (*service >= '0' && *service <= '9')
7891 char *endp;
7893 port = strtoul (service, &endp, 10);
7894 if (*endp || port > 65536)
7895 return WSAHOST_NOT_FOUND;
7896 port = sys_htons ((unsigned short) port);
7898 else
7899 return WSAHOST_NOT_FOUND;
7902 gai_storage = xzalloc (sizeof *gai_storage);
7903 gai_storage->sockaddr_in.sin_port = port;
7904 host_info = sys_gethostbyname (node);
7905 if (host_info)
7907 memcpy (&gai_storage->sockaddr_in.sin_addr,
7908 host_info->h_addr, host_info->h_length);
7909 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7911 else
7913 /* Attempt to interpret host as numeric inet address. */
7914 unsigned long numeric_addr = sys_inet_addr (node);
7916 if (numeric_addr == -1)
7918 free (gai_storage);
7919 return WSAHOST_NOT_FOUND;
7922 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7923 sizeof (gai_storage->sockaddr_in.sin_addr));
7924 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7927 gai_storage->addrinfo.ai_addr =
7928 (struct sockaddr *)&gai_storage->sockaddr_in;
7929 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7930 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7931 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7932 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7933 gai_storage->addrinfo.ai_next = NULL;
7935 *res = &gai_storage->addrinfo;
7936 rc = 0;
7939 return rc;
7942 void
7943 sys_freeaddrinfo (struct addrinfo *ai)
7945 if (winsock_lib == NULL)
7947 errno = ENETDOWN;
7948 return;
7951 check_errno ();
7952 if (pfn_freeaddrinfo)
7953 pfn_freeaddrinfo (ai);
7954 else
7956 eassert (ai->ai_next == NULL);
7957 xfree (ai);
7962 sys_shutdown (int s, int how)
7964 if (winsock_lib == NULL)
7966 errno = ENETDOWN;
7967 return SOCKET_ERROR;
7970 check_errno ();
7971 if (fd_info[s].flags & FILE_SOCKET)
7973 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7974 if (rc == SOCKET_ERROR)
7975 set_errno ();
7976 return rc;
7978 errno = ENOTSOCK;
7979 return SOCKET_ERROR;
7983 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7985 if (winsock_lib == NULL)
7987 errno = ENETDOWN;
7988 return SOCKET_ERROR;
7991 check_errno ();
7992 if (fd_info[s].flags & FILE_SOCKET)
7994 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7995 (const char *)optval, optlen);
7996 if (rc == SOCKET_ERROR)
7997 set_errno ();
7998 return rc;
8000 errno = ENOTSOCK;
8001 return SOCKET_ERROR;
8005 sys_listen (int s, int backlog)
8007 if (winsock_lib == NULL)
8009 errno = ENETDOWN;
8010 return SOCKET_ERROR;
8013 check_errno ();
8014 if (fd_info[s].flags & FILE_SOCKET)
8016 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
8017 if (rc == SOCKET_ERROR)
8018 set_errno ();
8019 else
8020 fd_info[s].flags |= FILE_LISTEN;
8021 return rc;
8023 errno = ENOTSOCK;
8024 return SOCKET_ERROR;
8028 sys_getsockname (int s, struct sockaddr * name, int * namelen)
8030 if (winsock_lib == NULL)
8032 errno = ENETDOWN;
8033 return SOCKET_ERROR;
8036 check_errno ();
8037 if (fd_info[s].flags & FILE_SOCKET)
8039 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
8040 if (rc == SOCKET_ERROR)
8041 set_errno ();
8042 return rc;
8044 errno = ENOTSOCK;
8045 return SOCKET_ERROR;
8049 sys_accept (int s, struct sockaddr * addr, int * addrlen)
8051 if (winsock_lib == NULL)
8053 errno = ENETDOWN;
8054 return -1;
8057 check_errno ();
8058 if (fd_info[s].flags & FILE_LISTEN)
8060 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
8061 int fd = -1;
8062 if (t == INVALID_SOCKET)
8063 set_errno ();
8064 else
8065 fd = socket_to_fd (t);
8067 if (fd >= 0)
8069 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
8070 ResetEvent (fd_info[s].cp->char_avail);
8072 return fd;
8074 errno = ENOTSOCK;
8075 return -1;
8079 sys_recvfrom (int s, char * buf, int len, int flags,
8080 struct sockaddr * from, int * fromlen)
8082 if (winsock_lib == NULL)
8084 errno = ENETDOWN;
8085 return SOCKET_ERROR;
8088 check_errno ();
8089 if (fd_info[s].flags & FILE_SOCKET)
8091 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8092 if (rc == SOCKET_ERROR)
8093 set_errno ();
8094 return rc;
8096 errno = ENOTSOCK;
8097 return SOCKET_ERROR;
8101 sys_sendto (int s, const char * buf, int len, int flags,
8102 const struct sockaddr * to, int tolen)
8104 if (winsock_lib == NULL)
8106 errno = ENETDOWN;
8107 return SOCKET_ERROR;
8110 check_errno ();
8111 if (fd_info[s].flags & FILE_SOCKET)
8113 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8114 if (rc == SOCKET_ERROR)
8115 set_errno ();
8116 return rc;
8118 errno = ENOTSOCK;
8119 return SOCKET_ERROR;
8122 /* Windows does not have an fcntl function. Provide an implementation
8123 good enough for Emacs. */
8125 fcntl (int s, int cmd, int options)
8127 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8128 invoked in a context where fd1 is closed and all descriptors less
8129 than fd1 are open, so sys_dup is an adequate implementation. */
8130 if (cmd == F_DUPFD_CLOEXEC)
8131 return sys_dup (s);
8133 check_errno ();
8134 if (fd_info[s].flags & FILE_SOCKET)
8136 if (winsock_lib == NULL)
8138 errno = ENETDOWN;
8139 return -1;
8142 if (cmd == F_SETFL && options == O_NONBLOCK)
8144 unsigned long nblock = 1;
8145 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8146 if (rc == SOCKET_ERROR)
8147 set_errno ();
8148 /* Keep track of the fact that we set this to non-blocking. */
8149 fd_info[s].flags |= FILE_NDELAY;
8150 return rc;
8152 else
8154 errno = EINVAL;
8155 return SOCKET_ERROR;
8158 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8159 == (FILE_PIPE | FILE_WRITE))
8161 /* Force our writes to pipes be non-blocking. */
8162 if (cmd == F_SETFL && options == O_NONBLOCK)
8164 HANDLE h = (HANDLE)_get_osfhandle (s);
8165 DWORD pipe_mode = PIPE_NOWAIT;
8167 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8169 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8170 return SOCKET_ERROR;
8172 fd_info[s].flags |= FILE_NDELAY;
8173 return 0;
8175 else
8177 errno = EINVAL;
8178 return SOCKET_ERROR;
8181 errno = ENOTSOCK;
8182 return SOCKET_ERROR;
8186 /* Shadow main io functions: we need to handle pipes and sockets more
8187 intelligently. */
8190 sys_close (int fd)
8192 int rc;
8194 if (fd < 0)
8196 errno = EBADF;
8197 return -1;
8200 if (fd < MAXDESC && fd_info[fd].cp)
8202 child_process * cp = fd_info[fd].cp;
8204 fd_info[fd].cp = NULL;
8206 if (CHILD_ACTIVE (cp))
8208 /* if last descriptor to active child_process then cleanup */
8209 int i;
8210 for (i = 0; i < MAXDESC; i++)
8212 if (i == fd)
8213 continue;
8214 if (fd_info[i].cp == cp)
8215 break;
8217 if (i == MAXDESC)
8219 if (fd_info[fd].flags & FILE_SOCKET)
8221 if (winsock_lib == NULL) emacs_abort ();
8223 pfn_shutdown (SOCK_HANDLE (fd), 2);
8224 rc = pfn_closesocket (SOCK_HANDLE (fd));
8226 winsock_inuse--; /* count open sockets */
8228 /* If the process handle is NULL, it's either a socket
8229 or serial connection, or a subprocess that was
8230 already reaped by reap_subprocess, but whose
8231 resources were not yet freed, because its output was
8232 not fully read yet by the time it was reaped. (This
8233 usually happens with async subprocesses whose output
8234 is being read by Emacs.) Otherwise, this process was
8235 not reaped yet, so we set its FD to a negative value
8236 to make sure sys_select will eventually get to
8237 calling the SIGCHLD handler for it, which will then
8238 invoke waitpid and reap_subprocess. */
8239 if (cp->procinfo.hProcess == NULL)
8240 delete_child (cp);
8241 else
8242 cp->fd = -1;
8247 if (fd >= 0 && fd < MAXDESC)
8248 fd_info[fd].flags = 0;
8250 /* Note that sockets do not need special treatment here (at least on
8251 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8252 closesocket is equivalent to CloseHandle, which is to be expected
8253 because socket handles are fully fledged kernel handles. */
8254 rc = _close (fd);
8256 return rc;
8260 sys_dup (int fd)
8262 int new_fd;
8264 new_fd = _dup (fd);
8265 if (new_fd >= 0 && new_fd < MAXDESC)
8267 /* duplicate our internal info as well */
8268 fd_info[new_fd] = fd_info[fd];
8270 return new_fd;
8274 sys_dup2 (int src, int dst)
8276 int rc;
8278 if (dst < 0 || dst >= MAXDESC)
8280 errno = EBADF;
8281 return -1;
8284 /* MS _dup2 seems to have weird side effect when invoked with 2
8285 identical arguments: an attempt to fclose the corresponding stdio
8286 stream after that hangs (we do close standard streams in
8287 init_ntproc). Attempt to avoid that by not calling _dup2 that
8288 way: if SRC is valid, we know that dup2 should be a no-op, so do
8289 nothing and return DST. */
8290 if (src == dst)
8292 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8294 errno = EBADF;
8295 return -1;
8297 return dst;
8300 /* Make sure we close the destination first if it's a pipe or socket. */
8301 if (fd_info[dst].flags != 0)
8302 sys_close (dst);
8304 rc = _dup2 (src, dst);
8305 if (rc == 0)
8307 /* Duplicate our internal info as well. */
8308 fd_info[dst] = fd_info[src];
8310 return rc == 0 ? dst : rc;
8314 pipe2 (int * phandles, int pipe2_flags)
8316 int rc;
8317 unsigned flags;
8318 unsigned pipe_size = 0;
8320 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8322 /* Allow Lisp to override the default buffer size of the pipe. */
8323 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8324 pipe_size = w32_pipe_buffer_size;
8326 /* make pipe handles non-inheritable; when we spawn a child, we
8327 replace the relevant handle with an inheritable one. Also put
8328 pipes into binary mode; we will do text mode translation ourselves
8329 if required. */
8330 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8332 if (rc == 0)
8334 /* Protect against overflow, since Windows can open more handles than
8335 our fd_info array has room for. */
8336 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8338 _close (phandles[0]);
8339 _close (phandles[1]);
8340 errno = EMFILE;
8341 rc = -1;
8343 else
8345 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8346 fd_info[phandles[0]].flags = flags;
8348 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8349 fd_info[phandles[1]].flags = flags;
8353 return rc;
8356 /* Function to do blocking read of one byte, needed to implement
8357 select. It is only allowed on communication ports, sockets, or
8358 pipes. */
8360 _sys_read_ahead (int fd)
8362 child_process * cp;
8363 int rc;
8365 if (fd < 0 || fd >= MAXDESC)
8366 return STATUS_READ_ERROR;
8368 cp = fd_info[fd].cp;
8370 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8371 return STATUS_READ_ERROR;
8373 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8374 || (fd_info[fd].flags & FILE_READ) == 0)
8376 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8377 emacs_abort ();
8380 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8381 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8382 cp->status = STATUS_READ_IN_PROGRESS;
8384 if (fd_info[fd].flags & FILE_PIPE)
8386 rc = _read (fd, &cp->chr, sizeof (char));
8388 /* Give subprocess time to buffer some more output for us before
8389 reporting that input is available; we need this because Windows 95
8390 connects DOS programs to pipes by making the pipe appear to be
8391 the normal console stdout - as a result most DOS programs will
8392 write to stdout without buffering, ie. one character at a
8393 time. Even some W32 programs do this - "dir" in a command
8394 shell on NT is very slow if we don't do this. */
8395 if (rc > 0)
8397 int wait = w32_pipe_read_delay;
8399 if (wait > 0)
8400 Sleep (wait);
8401 else if (wait < 0)
8402 while (++wait <= 0)
8403 /* Yield remainder of our time slice, effectively giving a
8404 temporary priority boost to the child process. */
8405 Sleep (0);
8408 else if (fd_info[fd].flags & FILE_SERIAL)
8410 HANDLE hnd = fd_info[fd].hnd;
8411 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8412 COMMTIMEOUTS ct;
8414 /* Configure timeouts for blocking read. */
8415 if (!GetCommTimeouts (hnd, &ct))
8417 cp->status = STATUS_READ_ERROR;
8418 return STATUS_READ_ERROR;
8420 ct.ReadIntervalTimeout = 0;
8421 ct.ReadTotalTimeoutMultiplier = 0;
8422 ct.ReadTotalTimeoutConstant = 0;
8423 if (!SetCommTimeouts (hnd, &ct))
8425 cp->status = STATUS_READ_ERROR;
8426 return STATUS_READ_ERROR;
8429 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8431 if (GetLastError () != ERROR_IO_PENDING)
8433 cp->status = STATUS_READ_ERROR;
8434 return STATUS_READ_ERROR;
8436 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8438 cp->status = STATUS_READ_ERROR;
8439 return STATUS_READ_ERROR;
8443 else if (fd_info[fd].flags & FILE_SOCKET)
8445 unsigned long nblock = 0;
8446 /* We always want this to block, so temporarily disable NDELAY. */
8447 if (fd_info[fd].flags & FILE_NDELAY)
8448 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8450 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8452 if (fd_info[fd].flags & FILE_NDELAY)
8454 nblock = 1;
8455 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8459 if (rc == sizeof (char))
8460 cp->status = STATUS_READ_SUCCEEDED;
8461 else
8462 cp->status = STATUS_READ_FAILED;
8464 return cp->status;
8468 _sys_wait_accept (int fd)
8470 HANDLE hEv;
8471 child_process * cp;
8472 int rc;
8474 if (fd < 0 || fd >= MAXDESC)
8475 return STATUS_READ_ERROR;
8477 cp = fd_info[fd].cp;
8479 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8480 return STATUS_READ_ERROR;
8482 cp->status = STATUS_READ_FAILED;
8484 hEv = pfn_WSACreateEvent ();
8485 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8486 if (rc != SOCKET_ERROR)
8488 do {
8489 rc = WaitForSingleObject (hEv, 500);
8490 Sleep (5);
8491 } while (rc == WAIT_TIMEOUT
8492 && cp->status != STATUS_READ_ERROR
8493 && cp->char_avail);
8494 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8495 if (rc == WAIT_OBJECT_0)
8496 cp->status = STATUS_READ_SUCCEEDED;
8498 pfn_WSACloseEvent (hEv);
8500 return cp->status;
8504 _sys_wait_connect (int fd)
8506 HANDLE hEv;
8507 child_process * cp;
8508 int rc;
8510 if (fd < 0 || fd >= MAXDESC)
8511 return STATUS_READ_ERROR;
8513 cp = fd_info[fd].cp;
8514 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8515 return STATUS_READ_ERROR;
8517 cp->status = STATUS_READ_FAILED;
8519 hEv = pfn_WSACreateEvent ();
8520 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8521 if (rc != SOCKET_ERROR)
8523 do {
8524 rc = WaitForSingleObject (hEv, 500);
8525 Sleep (5);
8526 } while (rc == WAIT_TIMEOUT
8527 && cp->status != STATUS_READ_ERROR
8528 && cp->char_avail);
8529 if (rc == WAIT_OBJECT_0)
8531 /* We've got an event, but it could be a successful
8532 connection, or it could be a failure. Find out
8533 which one is it. */
8534 WSANETWORKEVENTS events;
8536 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8537 if ((events.lNetworkEvents & FD_CONNECT) != 0
8538 && events.iErrorCode[FD_CONNECT_BIT])
8540 cp->status = STATUS_CONNECT_FAILED;
8541 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8543 else
8545 cp->status = STATUS_READ_SUCCEEDED;
8546 cp->errcode = 0;
8549 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8551 else
8552 pfn_WSACloseEvent (hEv);
8554 return cp->status;
8558 sys_read (int fd, char * buffer, unsigned int count)
8560 int nchars;
8561 int to_read;
8562 DWORD waiting;
8563 char * orig_buffer = buffer;
8565 if (fd < 0)
8567 errno = EBADF;
8568 return -1;
8571 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8573 child_process *cp = fd_info[fd].cp;
8575 if ((fd_info[fd].flags & FILE_READ) == 0)
8577 errno = EBADF;
8578 return -1;
8581 nchars = 0;
8583 /* re-read CR carried over from last read */
8584 if (fd_info[fd].flags & FILE_LAST_CR)
8586 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8587 *buffer++ = 0x0d;
8588 count--;
8589 nchars++;
8590 fd_info[fd].flags &= ~FILE_LAST_CR;
8593 /* presence of a child_process structure means we are operating in
8594 non-blocking mode - otherwise we just call _read directly.
8595 Note that the child_process structure might be missing because
8596 reap_subprocess has been called; in this case the pipe is
8597 already broken, so calling _read on it is okay. */
8598 if (cp)
8600 int current_status = cp->status;
8602 switch (current_status)
8604 case STATUS_READ_FAILED:
8605 case STATUS_READ_ERROR:
8606 /* report normal EOF if nothing in buffer */
8607 if (nchars <= 0)
8608 fd_info[fd].flags |= FILE_AT_EOF;
8609 return nchars;
8611 case STATUS_READ_READY:
8612 case STATUS_READ_IN_PROGRESS:
8613 #if 0
8614 /* This happens all the time during GnuTLS handshake
8615 with the remote, evidently because GnuTLS waits for
8616 the read to complete by retrying the read operation
8617 upon EAGAIN. So I'm disabling the DebPrint to avoid
8618 wasting cycles on something that is not a real
8619 problem. Enable if you need to debug something that
8620 bumps into this. */
8621 DebPrint (("sys_read called when read is in progress %d\n",
8622 current_status));
8623 #endif
8624 errno = EWOULDBLOCK;
8625 return -1;
8627 case STATUS_READ_SUCCEEDED:
8628 /* consume read-ahead char */
8629 *buffer++ = cp->chr;
8630 count--;
8631 nchars++;
8632 cp->status = STATUS_READ_ACKNOWLEDGED;
8633 ResetEvent (cp->char_avail);
8635 case STATUS_READ_ACKNOWLEDGED:
8636 case STATUS_CONNECT_FAILED:
8637 break;
8639 default:
8640 DebPrint (("sys_read: bad status %d\n", current_status));
8641 errno = EBADF;
8642 return -1;
8645 if (fd_info[fd].flags & FILE_PIPE)
8647 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8648 to_read = min (waiting, (DWORD) count);
8650 if (to_read > 0)
8651 nchars += _read (fd, buffer, to_read);
8653 else if (fd_info[fd].flags & FILE_SERIAL)
8655 HANDLE hnd = fd_info[fd].hnd;
8656 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8657 int rc = 0;
8658 COMMTIMEOUTS ct;
8660 if (count > 0)
8662 /* Configure timeouts for non-blocking read. */
8663 if (!GetCommTimeouts (hnd, &ct))
8665 errno = EIO;
8666 return -1;
8668 ct.ReadIntervalTimeout = MAXDWORD;
8669 ct.ReadTotalTimeoutMultiplier = 0;
8670 ct.ReadTotalTimeoutConstant = 0;
8671 if (!SetCommTimeouts (hnd, &ct))
8673 errno = EIO;
8674 return -1;
8677 if (!ResetEvent (ovl->hEvent))
8679 errno = EIO;
8680 return -1;
8682 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8684 if (GetLastError () != ERROR_IO_PENDING)
8686 errno = EIO;
8687 return -1;
8689 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8691 errno = EIO;
8692 return -1;
8695 nchars += rc;
8698 else /* FILE_SOCKET */
8700 if (winsock_lib == NULL) emacs_abort ();
8702 /* When a non-blocking 'connect' call fails,
8703 wait_reading_process_output detects this by calling
8704 'getpeername', and then attempts to obtain the connection
8705 error code by trying to read 1 byte from the socket. If
8706 we try to serve that read by calling 'recv' below, the
8707 error we get is a generic WSAENOTCONN, not the actual
8708 connection error. So instead, we use the actual error
8709 code stashed by '_sys_wait_connect' in cp->errcode.
8710 Alternatively, we could have used 'getsockopt', like on
8711 GNU/Linux, but: (a) I have no idea whether the winsock
8712 version could hang, as it does "on some systems" (see the
8713 comment in process.c); and (b) 'getsockopt' on Windows is
8714 documented to clear the socket error for the entire
8715 process, which I'm not sure is TRT; FIXME. */
8716 if (current_status == STATUS_CONNECT_FAILED
8717 && (fd_info[fd].flags & FILE_CONNECT) != 0
8718 && cp->errcode != 0)
8720 pfn_WSASetLastError (cp->errcode);
8721 set_errno ();
8722 return -1;
8724 /* Do the equivalent of a non-blocking read. */
8725 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8726 if (waiting == 0 && nchars == 0)
8728 errno = EWOULDBLOCK;
8729 return -1;
8732 if (waiting)
8734 /* always use binary mode for sockets */
8735 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8736 if (res == SOCKET_ERROR)
8738 set_errno ();
8739 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8740 errno, SOCK_HANDLE (fd)));
8741 return -1;
8743 nchars += res;
8747 else
8749 int nread = _read (fd, buffer, count);
8750 if (nread >= 0)
8751 nchars += nread;
8752 else if (nchars == 0)
8753 nchars = nread;
8756 if (nchars <= 0)
8757 fd_info[fd].flags |= FILE_AT_EOF;
8758 /* Perform text mode translation if required. */
8759 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8761 nchars = crlf_to_lf (nchars, orig_buffer);
8762 /* If buffer contains only CR, return that. To be absolutely
8763 sure we should attempt to read the next char, but in
8764 practice a CR to be followed by LF would not appear by
8765 itself in the buffer. */
8766 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8768 fd_info[fd].flags |= FILE_LAST_CR;
8769 nchars--;
8773 else
8774 nchars = _read (fd, buffer, count);
8776 return nchars;
8779 /* From w32xfns.c */
8780 extern HANDLE interrupt_handle;
8783 sys_write (int fd, const void * buffer, unsigned int count)
8785 int nchars;
8786 USE_SAFE_ALLOCA;
8788 if (fd < 0)
8790 errno = EBADF;
8791 return -1;
8794 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8796 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8798 errno = EBADF;
8799 return -1;
8802 /* Perform text mode translation if required. */
8803 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8805 char * tmpbuf;
8806 const unsigned char * src = buffer;
8807 unsigned char * dst;
8808 int nbytes = count;
8810 SAFE_NALLOCA (tmpbuf, 2, count);
8811 dst = (unsigned char *)tmpbuf;
8813 while (1)
8815 unsigned char *next;
8816 /* Copy next line or remaining bytes. */
8817 next = _memccpy (dst, src, '\n', nbytes);
8818 if (next)
8820 /* Copied one line ending with '\n'. */
8821 int copied = next - dst;
8822 nbytes -= copied;
8823 src += copied;
8824 /* Insert '\r' before '\n'. */
8825 next[-1] = '\r';
8826 next[0] = '\n';
8827 dst = next + 1;
8828 count++;
8830 else
8831 /* Copied remaining partial line -> now finished. */
8832 break;
8834 buffer = tmpbuf;
8838 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8840 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8841 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8842 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8843 DWORD active = 0;
8845 /* This is async (a.k.a. "overlapped") I/O, so the return value
8846 of FALSE from WriteFile means either an error or the output
8847 will be completed asynchronously (ERROR_IO_PENDING). */
8848 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8850 if (GetLastError () != ERROR_IO_PENDING)
8852 errno = EIO;
8853 nchars = -1;
8855 else
8857 /* Wait for the write to complete, and watch C-g while
8858 at that. */
8859 if (detect_input_pending ())
8860 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8861 INFINITE, QS_ALLINPUT);
8862 else
8863 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8864 switch (active)
8866 case WAIT_OBJECT_0:
8867 /* User pressed C-g, cancel write, then leave.
8868 Don't bother cleaning up as we may only get stuck
8869 in buggy drivers. */
8870 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8871 CancelIo (hnd);
8872 errno = EIO; /* Why not EINTR? */
8873 nchars = -1;
8874 break;
8875 case WAIT_OBJECT_0 + 1:
8876 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8878 errno = EIO;
8879 nchars = -1;
8881 break;
8886 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8888 unsigned long nblock = 0;
8889 if (winsock_lib == NULL) emacs_abort ();
8891 child_process *cp = fd_info[fd].cp;
8893 /* If this is a non-blocking socket whose connection is in
8894 progress or terminated with an error already, return the
8895 proper error code to the caller. */
8896 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8898 /* In case connection is in progress, ENOTCONN that would
8899 result from calling pfn_send is not what callers expect. */
8900 if (cp->status != STATUS_CONNECT_FAILED)
8902 errno = EWOULDBLOCK;
8903 return -1;
8905 /* In case connection failed, use the actual error code
8906 stashed by '_sys_wait_connect' in cp->errcode. */
8907 else if (cp->errcode != 0)
8909 pfn_WSASetLastError (cp->errcode);
8910 set_errno ();
8911 return -1;
8915 /* TODO: implement select() properly so non-blocking I/O works. */
8916 /* For now, make sure the write blocks. */
8917 if (fd_info[fd].flags & FILE_NDELAY)
8918 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8920 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8922 if (nchars == SOCKET_ERROR)
8924 set_errno ();
8925 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8926 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8929 /* Set the socket back to non-blocking if it was before,
8930 for other operations that support it. */
8931 if (fd_info[fd].flags & FILE_NDELAY)
8933 nblock = 1;
8934 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8937 else
8939 /* Some networked filesystems don't like too large writes, so
8940 break them into smaller chunks. See the Comments section of
8941 the MSDN documentation of WriteFile for details behind the
8942 choice of the value of CHUNK below. See also the thread
8943 http://thread.gmane.org/gmane.comp.version-control.git/145294
8944 in the git mailing list. */
8945 const unsigned char *p = buffer;
8946 const bool is_pipe = (fd < MAXDESC
8947 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8948 == (FILE_PIPE | FILE_NDELAY)));
8949 /* Some programs, notably Node.js's node.exe, seem to never
8950 completely empty the pipe, so writing more than the size of
8951 the pipe's buffer always returns ENOSPC, and we loop forever
8952 between send_process and here. As a workaround, write no
8953 more than the pipe's buffer can hold. */
8954 DWORD pipe_buffer_size;
8955 if (is_pipe)
8957 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8958 NULL, &pipe_buffer_size, NULL, NULL))
8960 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8961 pipe_buffer_size = 4096;
8964 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8966 nchars = 0;
8967 errno = 0;
8968 while (count > 0)
8970 unsigned this_chunk = count < chunk ? count : chunk;
8971 int n = _write (fd, p, this_chunk);
8973 if (n > 0)
8974 nchars += n;
8975 if (n < 0)
8977 /* When there's no buffer space in a pipe that is in the
8978 non-blocking mode, _write returns ENOSPC. We return
8979 EAGAIN instead, which should trigger the logic in
8980 send_process that enters waiting loop and calls
8981 wait_reading_process_output to allow process input to
8982 be accepted during the wait. Those calls to
8983 wait_reading_process_output allow sys_select to
8984 notice when process input becomes available, thus
8985 avoiding deadlock whereby each side of the pipe is
8986 blocked on write, waiting for the other party to read
8987 its end of the pipe. */
8988 if (errno == ENOSPC && is_pipe)
8989 errno = EAGAIN;
8990 if (nchars == 0)
8991 nchars = -1;
8992 break;
8994 else if (n < this_chunk)
8995 break;
8996 count -= n;
8997 p += n;
9001 SAFE_FREE ();
9002 return nchars;
9006 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
9008 /* Return information about network interface IFNAME, or about all
9009 interfaces (if IFNAME is nil). */
9010 static Lisp_Object
9011 network_interface_get_info (Lisp_Object ifname)
9013 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
9014 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
9015 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
9016 Lisp_Object res = Qnil;
9018 if (retval == ERROR_BUFFER_OVERFLOW)
9020 ainfo = xrealloc (ainfo, ainfo_len);
9021 retval = get_adapters_info (ainfo, &ainfo_len);
9024 if (retval == ERROR_SUCCESS)
9026 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
9027 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
9028 int if_num;
9029 struct sockaddr_in sa;
9031 /* For the below, we need some winsock functions, so make sure
9032 the winsock DLL is loaded. If we cannot successfully load
9033 it, they will have no use of the information we provide,
9034 anyway, so punt. */
9035 if (!winsock_lib && !init_winsock (1))
9036 goto done;
9038 for (adapter = ainfo; adapter; adapter = adapter->Next)
9040 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
9041 u_long ip_addr;
9042 /* Present Unix-compatible interface names, instead of the
9043 Windows names, which are really GUIDs not readable by
9044 humans. */
9045 static const char *ifmt[] = {
9046 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
9047 "lo", "ifx%d"
9049 enum {
9050 NONE = -1,
9051 ETHERNET = 0,
9052 TOKENRING = 1,
9053 FDDI = 2,
9054 PPP = 3,
9055 SLIP = 4,
9056 WLAN = 5,
9057 LOOPBACK = 6,
9058 OTHER_IF = 7
9059 } ifmt_idx;
9061 switch (adapter->Type)
9063 case MIB_IF_TYPE_ETHERNET:
9064 /* Windows before Vista reports wireless adapters as
9065 Ethernet. Work around by looking at the Description
9066 string. */
9067 if (strstr (adapter->Description, "Wireless "))
9069 ifmt_idx = WLAN;
9070 if_num = wlan_count++;
9072 else
9074 ifmt_idx = ETHERNET;
9075 if_num = eth_count++;
9077 break;
9078 case MIB_IF_TYPE_TOKENRING:
9079 ifmt_idx = TOKENRING;
9080 if_num = tr_count++;
9081 break;
9082 case MIB_IF_TYPE_FDDI:
9083 ifmt_idx = FDDI;
9084 if_num = fddi_count++;
9085 break;
9086 case MIB_IF_TYPE_PPP:
9087 ifmt_idx = PPP;
9088 if_num = ppp_count++;
9089 break;
9090 case MIB_IF_TYPE_SLIP:
9091 ifmt_idx = SLIP;
9092 if_num = sl_count++;
9093 break;
9094 case IF_TYPE_IEEE80211:
9095 ifmt_idx = WLAN;
9096 if_num = wlan_count++;
9097 break;
9098 case MIB_IF_TYPE_LOOPBACK:
9099 if (lo_count < 0)
9101 ifmt_idx = LOOPBACK;
9102 if_num = lo_count++;
9104 else
9105 ifmt_idx = NONE;
9106 break;
9107 default:
9108 ifmt_idx = OTHER_IF;
9109 if_num = ifx_count++;
9110 break;
9112 if (ifmt_idx == NONE)
9113 continue;
9114 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9116 sa.sin_family = AF_INET;
9117 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9118 if (ip_addr == INADDR_NONE)
9120 /* Bogus address, skip this interface. */
9121 continue;
9123 sa.sin_addr.s_addr = ip_addr;
9124 sa.sin_port = 0;
9125 if (NILP (ifname))
9126 res = Fcons (Fcons (build_string (namebuf),
9127 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9128 sizeof (struct sockaddr))),
9129 res);
9130 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9132 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9133 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9134 Lisp_Object flags = Qnil;
9135 int n;
9136 u_long net_mask;
9138 /* Flags. We guess most of them by type, since the
9139 Windows flags are different and hard to get by. */
9140 flags = Fcons (intern ("up"), flags);
9141 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9143 flags = Fcons (intern ("broadcast"), flags);
9144 flags = Fcons (intern ("multicast"), flags);
9146 flags = Fcons (intern ("running"), flags);
9147 if (ifmt_idx == PPP)
9149 flags = Fcons (intern ("pointopoint"), flags);
9150 flags = Fcons (intern ("noarp"), flags);
9152 if (adapter->HaveWins)
9153 flags = Fcons (intern ("WINS"), flags);
9154 if (adapter->DhcpEnabled)
9155 flags = Fcons (intern ("dynamic"), flags);
9157 res = Fcons (flags, res);
9159 /* Hardware address and its family. */
9160 for (n = 0; n < adapter->AddressLength; n++)
9161 p->contents[n] = make_number ((int) adapter->Address[n]);
9162 /* Windows does not support AF_LINK or AF_PACKET family
9163 of addresses. Use an arbitrary family number that is
9164 identical to what GNU/Linux returns. */
9165 res = Fcons (Fcons (make_number (1), hwaddr), res);
9167 /* Network mask. */
9168 sa.sin_family = AF_INET;
9169 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9170 if (net_mask != INADDR_NONE)
9172 sa.sin_addr.s_addr = net_mask;
9173 sa.sin_port = 0;
9174 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9175 sizeof (struct sockaddr)),
9176 res);
9178 else
9179 res = Fcons (Qnil, res);
9181 sa.sin_family = AF_INET;
9182 if (ip_addr != INADDR_NONE)
9184 /* Broadcast address is only reported by
9185 GetAdaptersAddresses, which is of limited
9186 availability. Generate it on our own. */
9187 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9189 sa.sin_addr.s_addr = bcast_addr;
9190 sa.sin_port = 0;
9191 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9192 sizeof (struct sockaddr)),
9193 res);
9195 /* IP address. */
9196 sa.sin_addr.s_addr = ip_addr;
9197 sa.sin_port = 0;
9198 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9199 sizeof (struct sockaddr)),
9200 res);
9202 else
9203 res = Fcons (Qnil, Fcons (Qnil, res));
9206 /* GetAdaptersInfo is documented to not report loopback
9207 interfaces, so we generate one out of thin air. */
9208 if (!lo_count)
9210 sa.sin_family = AF_INET;
9211 sa.sin_port = 0;
9212 if (NILP (ifname))
9214 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9215 res = Fcons (Fcons (build_string ("lo"),
9216 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9217 sizeof (struct sockaddr))),
9218 res);
9220 else if (strcmp (SSDATA (ifname), "lo") == 0)
9222 res = Fcons (Fcons (intern ("running"),
9223 Fcons (intern ("loopback"),
9224 Fcons (intern ("up"), Qnil))), Qnil);
9225 /* 772 is what 3 different GNU/Linux systems report for
9226 the loopback interface. */
9227 res = Fcons (Fcons (make_number (772),
9228 Fmake_vector (make_number (6),
9229 make_number (0))),
9230 res);
9231 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9232 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9233 sizeof (struct sockaddr)),
9234 res);
9235 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
9236 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9237 sizeof (struct sockaddr)),
9238 res);
9239 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9240 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9241 sizeof (struct sockaddr)),
9242 res);
9248 done:
9249 xfree (ainfo);
9250 return res;
9253 Lisp_Object
9254 network_interface_list (void)
9256 return network_interface_get_info (Qnil);
9259 Lisp_Object
9260 network_interface_info (Lisp_Object ifname)
9262 CHECK_STRING (ifname);
9263 return network_interface_get_info (ifname);
9267 /* The Windows CRT functions are "optimized for speed", so they don't
9268 check for timezone and DST changes if they were last called less
9269 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9270 all Emacs features that repeatedly call time functions (e.g.,
9271 display-time) are in real danger of missing timezone and DST
9272 changes. Calling tzset before each localtime call fixes that. */
9273 struct tm *
9274 sys_localtime (const time_t *t)
9276 tzset ();
9277 return localtime (t);
9282 /* Try loading LIBRARY_ID from the file(s) specified in
9283 Vdynamic_library_alist. If the library is loaded successfully,
9284 return the handle of the DLL, and record the filename in the
9285 property :loaded-from of LIBRARY_ID. If the library could not be
9286 found, or when it was already loaded (because the handle is not
9287 recorded anywhere, and so is lost after use), return NULL.
9289 We could also save the handle in :loaded-from, but currently
9290 there's no use case for it. */
9291 HMODULE
9292 w32_delayed_load (Lisp_Object library_id)
9294 HMODULE dll_handle = NULL;
9296 CHECK_SYMBOL (library_id);
9298 if (CONSP (Vdynamic_library_alist)
9299 && NILP (Fassq (library_id, Vlibrary_cache)))
9301 Lisp_Object found = Qnil;
9302 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9304 if (CONSP (dlls))
9305 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9307 Lisp_Object dll = XCAR (dlls);
9308 char name[MAX_UTF8_PATH];
9309 DWORD res = -1;
9311 CHECK_STRING (dll);
9312 dll = ENCODE_FILE (dll);
9313 if (w32_unicode_filenames)
9315 wchar_t name_w[MAX_PATH];
9317 filename_to_utf16 (SSDATA (dll), name_w);
9318 dll_handle = LoadLibraryW (name_w);
9319 if (dll_handle)
9321 res = GetModuleFileNameW (dll_handle, name_w,
9322 sizeof (name_w));
9323 if (res > 0)
9324 filename_from_utf16 (name_w, name);
9327 else
9329 char name_a[MAX_PATH];
9331 filename_to_ansi (SSDATA (dll), name_a);
9332 dll_handle = LoadLibraryA (name_a);
9333 if (dll_handle)
9335 res = GetModuleFileNameA (dll_handle, name_a,
9336 sizeof (name_a));
9337 if (res > 0)
9338 filename_from_ansi (name_a, name);
9341 if (dll_handle)
9343 ptrdiff_t len = strlen (name);
9344 found = Fcons (dll,
9345 (res > 0)
9346 /* Possibly truncated */
9347 ? make_specified_string (name, -1, len, 1)
9348 : Qnil);
9349 /* This prevents thread start and end notifications
9350 from being sent to the DLL, for every thread we
9351 start. We don't need those notifications because
9352 threads we create never use any of these DLLs, only
9353 the main thread uses them. This is supposed to
9354 speed up thread creation. */
9355 DisableThreadLibraryCalls (dll_handle);
9356 break;
9360 Fput (library_id, QCloaded_from, found);
9363 return dll_handle;
9367 void
9368 check_windows_init_file (void)
9370 /* A common indication that Emacs is not installed properly is when
9371 it cannot find the Windows installation file. If this file does
9372 not exist in the expected place, tell the user. */
9374 if (!noninteractive && !inhibit_window_system
9375 /* Vload_path is not yet initialized when we are loading
9376 loadup.el. */
9377 && NILP (Vpurify_flag))
9379 Lisp_Object init_file;
9380 int fd;
9382 /* Implementation note: this function runs early during Emacs
9383 startup, before startup.el is run. So Vload_path is still in
9384 its initial unibyte form, but it holds UTF-8 encoded file
9385 names, since init_callproc was already called. So we do not
9386 need to ENCODE_FILE here, but we do need to convert the file
9387 names from UTF-8 to ANSI. */
9388 init_file = build_string ("term/w32-win");
9389 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9390 if (fd < 0)
9392 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9393 char *init_file_name = SSDATA (init_file);
9394 char *load_path = SSDATA (load_path_print);
9395 char *buffer = alloca (1024
9396 + strlen (init_file_name)
9397 + strlen (load_path));
9398 char *msg = buffer;
9399 int needed;
9401 sprintf (buffer,
9402 "The Emacs Windows initialization file \"%s.el\" "
9403 "could not be found in your Emacs installation. "
9404 "Emacs checked the following directories for this file:\n"
9405 "\n%s\n\n"
9406 "When Emacs cannot find this file, it usually means that it "
9407 "was not installed properly, or its distribution file was "
9408 "not unpacked properly.\nSee the README.W32 file in the "
9409 "top-level Emacs directory for more information.",
9410 init_file_name, load_path);
9411 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9412 buffer, -1, NULL, 0);
9413 if (needed > 0)
9415 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9417 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9418 -1, msg_w, needed);
9419 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9420 NULL, 0, NULL, NULL);
9421 if (needed > 0)
9423 char *msg_a = alloca (needed + 1);
9425 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9426 NULL, NULL);
9427 msg = msg_a;
9430 MessageBox (NULL,
9431 msg,
9432 "Emacs Abort Dialog",
9433 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9434 /* Use the low-level system abort. */
9435 abort ();
9437 else
9439 _close (fd);
9444 void
9445 term_ntproc (int ignored)
9447 (void)ignored;
9449 term_timers ();
9451 /* shutdown the socket interface if necessary */
9452 term_winsock ();
9454 term_w32select ();
9457 void
9458 init_ntproc (int dumping)
9460 sigset_t initial_mask = 0;
9462 /* Initialize the socket interface now if available and requested by
9463 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9464 delayed until open-network-stream is called (w32-has-winsock can
9465 also be used to dynamically load or reload winsock).
9467 Conveniently, init_environment is called before us, so
9468 PRELOAD_WINSOCK can be set in the registry. */
9470 /* Always initialize this correctly. */
9471 winsock_lib = NULL;
9473 if (getenv ("PRELOAD_WINSOCK") != NULL)
9474 init_winsock (TRUE);
9476 /* Initial preparation for subprocess support: replace our standard
9477 handles with non-inheritable versions. */
9479 HANDLE parent;
9480 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9481 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9482 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9484 parent = GetCurrentProcess ();
9486 /* ignore errors when duplicating and closing; typically the
9487 handles will be invalid when running as a gui program. */
9488 DuplicateHandle (parent,
9489 GetStdHandle (STD_INPUT_HANDLE),
9490 parent,
9491 &stdin_save,
9493 FALSE,
9494 DUPLICATE_SAME_ACCESS);
9496 DuplicateHandle (parent,
9497 GetStdHandle (STD_OUTPUT_HANDLE),
9498 parent,
9499 &stdout_save,
9501 FALSE,
9502 DUPLICATE_SAME_ACCESS);
9504 DuplicateHandle (parent,
9505 GetStdHandle (STD_ERROR_HANDLE),
9506 parent,
9507 &stderr_save,
9509 FALSE,
9510 DUPLICATE_SAME_ACCESS);
9512 fclose (stdin);
9513 fclose (stdout);
9514 fclose (stderr);
9516 if (stdin_save != INVALID_HANDLE_VALUE)
9517 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9518 else
9519 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9520 _fdopen (0, "r");
9522 if (stdout_save != INVALID_HANDLE_VALUE)
9523 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9524 else
9525 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9526 _fdopen (1, "w");
9528 if (stderr_save != INVALID_HANDLE_VALUE)
9529 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9530 else
9531 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9532 _fdopen (2, "w");
9535 /* unfortunately, atexit depends on implementation of malloc */
9536 /* atexit (term_ntproc); */
9537 if (!dumping)
9539 /* Make sure we start with all signals unblocked. */
9540 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9541 signal (SIGABRT, term_ntproc);
9543 init_timers ();
9545 /* determine which drives are fixed, for GetCachedVolumeInformation */
9547 /* GetDriveType must have trailing backslash. */
9548 char drive[] = "A:\\";
9550 /* Loop over all possible drive letters */
9551 while (*drive <= 'Z')
9553 /* Record if this drive letter refers to a fixed drive. */
9554 fixed_drives[DRIVE_INDEX (*drive)] =
9555 (GetDriveType (drive) == DRIVE_FIXED);
9557 (*drive)++;
9560 /* Reset the volume info cache. */
9561 volume_cache = NULL;
9566 shutdown_handler ensures that buffers' autosave files are
9567 up to date when the user logs off, or the system shuts down.
9569 static BOOL WINAPI
9570 shutdown_handler (DWORD type)
9572 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9573 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9574 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9575 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9577 /* Shut down cleanly, making sure autosave files are up to date. */
9578 shut_down_emacs (0, Qnil);
9581 /* Allow other handlers to handle this signal. */
9582 return FALSE;
9585 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9586 NT, return a handle to GDI32.DLL. */
9587 HANDLE
9588 maybe_load_unicows_dll (void)
9590 if (os_subtype == OS_9X)
9592 HANDLE ret = LoadLibrary ("Unicows.dll");
9593 if (ret)
9595 /* These two functions are present on Windows 9X as stubs
9596 that always fail. We need the real implementations from
9597 UNICOWS.DLL, so we must call these functions through
9598 pointers, and assign the correct addresses to these
9599 pointers at program startup (see emacs.c, which calls
9600 this function early on). */
9601 pMultiByteToWideChar =
9602 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9603 pWideCharToMultiByte =
9604 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9605 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9606 return ret;
9608 else
9610 int button;
9612 button = MessageBox (NULL,
9613 "Emacs cannot load the UNICOWS.DLL library.\n"
9614 "This library is essential for using Emacs\n"
9615 "on this system. You need to install it.\n\n"
9616 "Emacs will exit when you click OK.",
9617 "Emacs cannot load UNICOWS.DLL",
9618 MB_ICONERROR | MB_TASKMODAL
9619 | MB_SETFOREGROUND | MB_OK);
9620 switch (button)
9622 case IDOK:
9623 default:
9624 exit (1);
9628 else
9630 /* On NT family of Windows, these two functions are always
9631 linked in, so we just assign their addresses to the 2
9632 pointers; no need for the LoadLibrary dance. */
9633 pMultiByteToWideChar = MultiByteToWideChar;
9634 pWideCharToMultiByte = WideCharToMultiByte;
9635 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9636 if (w32_major_version < 5)
9637 multiByteToWideCharFlags = 0;
9638 else
9639 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9640 return LoadLibrary ("Gdi32.dll");
9645 globals_of_w32 is used to initialize those global variables that
9646 must always be initialized on startup even when the global variable
9647 initialized is non zero (see the function main in emacs.c).
9649 void
9650 globals_of_w32 (void)
9652 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9654 get_process_times_fn = (GetProcessTimes_Proc)
9655 GetProcAddress (kernel32, "GetProcessTimes");
9657 DEFSYM (QCloaded_from, ":loaded-from");
9659 g_b_init_is_windows_9x = 0;
9660 g_b_init_open_process_token = 0;
9661 g_b_init_get_token_information = 0;
9662 g_b_init_lookup_account_sid = 0;
9663 g_b_init_get_sid_sub_authority = 0;
9664 g_b_init_get_sid_sub_authority_count = 0;
9665 g_b_init_get_security_info = 0;
9666 g_b_init_get_file_security_w = 0;
9667 g_b_init_get_file_security_a = 0;
9668 g_b_init_get_security_descriptor_owner = 0;
9669 g_b_init_get_security_descriptor_group = 0;
9670 g_b_init_is_valid_sid = 0;
9671 g_b_init_create_toolhelp32_snapshot = 0;
9672 g_b_init_process32_first = 0;
9673 g_b_init_process32_next = 0;
9674 g_b_init_open_thread_token = 0;
9675 g_b_init_impersonate_self = 0;
9676 g_b_init_revert_to_self = 0;
9677 g_b_init_get_process_memory_info = 0;
9678 g_b_init_get_process_working_set_size = 0;
9679 g_b_init_global_memory_status = 0;
9680 g_b_init_global_memory_status_ex = 0;
9681 g_b_init_equal_sid = 0;
9682 g_b_init_copy_sid = 0;
9683 g_b_init_get_length_sid = 0;
9684 g_b_init_get_native_system_info = 0;
9685 g_b_init_get_system_times = 0;
9686 g_b_init_create_symbolic_link_w = 0;
9687 g_b_init_create_symbolic_link_a = 0;
9688 g_b_init_get_security_descriptor_dacl = 0;
9689 g_b_init_convert_sd_to_sddl = 0;
9690 g_b_init_convert_sddl_to_sd = 0;
9691 g_b_init_is_valid_security_descriptor = 0;
9692 g_b_init_set_file_security_w = 0;
9693 g_b_init_set_file_security_a = 0;
9694 g_b_init_set_named_security_info_w = 0;
9695 g_b_init_set_named_security_info_a = 0;
9696 g_b_init_get_adapters_info = 0;
9697 g_b_init_compare_string_w = 0;
9698 g_b_init_debug_break_process = 0;
9699 num_of_processors = 0;
9700 /* The following sets a handler for shutdown notifications for
9701 console apps. This actually applies to Emacs in both console and
9702 GUI modes, since we had to fool windows into thinking emacs is a
9703 console application to get console mode to work. */
9704 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9706 /* "None" is the default group name on standalone workstations. */
9707 strcpy (dflt_group_name, "None");
9709 /* Reset, in case it has some value inherited from dump time. */
9710 w32_stat_get_owner_group = 0;
9712 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9713 (a.k.a. "wide") APIs to invoke functions that accept file
9714 names. */
9715 if (is_windows_9x ())
9716 w32_unicode_filenames = 0;
9717 else
9718 w32_unicode_filenames = 1;
9720 #ifdef HAVE_MODULES
9721 dynlib_reset_last_error ();
9722 #endif
9724 w32_crypto_hprov = (HCRYPTPROV)0;
9727 /* For make-serial-process */
9729 serial_open (Lisp_Object port_obj)
9731 char *port = SSDATA (port_obj);
9732 HANDLE hnd;
9733 child_process *cp;
9734 int fd = -1;
9736 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9737 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9738 if (hnd == INVALID_HANDLE_VALUE)
9739 error ("Could not open %s", port);
9740 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9741 if (fd == -1)
9742 error ("Could not open %s", port);
9744 cp = new_child ();
9745 if (!cp)
9746 error ("Could not create child process");
9747 cp->fd = fd;
9748 cp->status = STATUS_READ_ACKNOWLEDGED;
9749 fd_info[ fd ].hnd = hnd;
9750 fd_info[ fd ].flags |=
9751 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9752 if (fd_info[ fd ].cp != NULL)
9754 error ("fd_info[fd = %d] is already in use", fd);
9756 fd_info[ fd ].cp = cp;
9757 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9758 if (cp->ovl_read.hEvent == NULL)
9759 error ("Could not create read event");
9760 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9761 if (cp->ovl_write.hEvent == NULL)
9762 error ("Could not create write event");
9764 return fd;
9767 /* For serial-process-configure */
9768 void
9769 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9771 Lisp_Object childp2 = Qnil;
9772 Lisp_Object tem = Qnil;
9773 HANDLE hnd;
9774 DCB dcb;
9775 COMMTIMEOUTS ct;
9776 char summary[4] = "???"; /* This usually becomes "8N1". */
9778 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9779 error ("Not a serial process");
9780 hnd = fd_info[ p->outfd ].hnd;
9782 childp2 = Fcopy_sequence (p->childp);
9784 /* Initialize timeouts for blocking read and blocking write. */
9785 if (!GetCommTimeouts (hnd, &ct))
9786 error ("GetCommTimeouts() failed");
9787 ct.ReadIntervalTimeout = 0;
9788 ct.ReadTotalTimeoutMultiplier = 0;
9789 ct.ReadTotalTimeoutConstant = 0;
9790 ct.WriteTotalTimeoutMultiplier = 0;
9791 ct.WriteTotalTimeoutConstant = 0;
9792 if (!SetCommTimeouts (hnd, &ct))
9793 error ("SetCommTimeouts() failed");
9794 /* Read port attributes and prepare default configuration. */
9795 memset (&dcb, 0, sizeof (dcb));
9796 dcb.DCBlength = sizeof (DCB);
9797 if (!GetCommState (hnd, &dcb))
9798 error ("GetCommState() failed");
9799 dcb.fBinary = TRUE;
9800 dcb.fNull = FALSE;
9801 dcb.fAbortOnError = FALSE;
9802 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9803 dcb.ErrorChar = 0;
9804 dcb.EofChar = 0;
9805 dcb.EvtChar = 0;
9807 /* Configure speed. */
9808 if (!NILP (Fplist_member (contact, QCspeed)))
9809 tem = Fplist_get (contact, QCspeed);
9810 else
9811 tem = Fplist_get (p->childp, QCspeed);
9812 CHECK_NUMBER (tem);
9813 dcb.BaudRate = XINT (tem);
9814 childp2 = Fplist_put (childp2, QCspeed, tem);
9816 /* Configure bytesize. */
9817 if (!NILP (Fplist_member (contact, QCbytesize)))
9818 tem = Fplist_get (contact, QCbytesize);
9819 else
9820 tem = Fplist_get (p->childp, QCbytesize);
9821 if (NILP (tem))
9822 tem = make_number (8);
9823 CHECK_NUMBER (tem);
9824 if (XINT (tem) != 7 && XINT (tem) != 8)
9825 error (":bytesize must be nil (8), 7, or 8");
9826 dcb.ByteSize = XINT (tem);
9827 summary[0] = XINT (tem) + '0';
9828 childp2 = Fplist_put (childp2, QCbytesize, tem);
9830 /* Configure parity. */
9831 if (!NILP (Fplist_member (contact, QCparity)))
9832 tem = Fplist_get (contact, QCparity);
9833 else
9834 tem = Fplist_get (p->childp, QCparity);
9835 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9836 error (":parity must be nil (no parity), `even', or `odd'");
9837 dcb.fParity = FALSE;
9838 dcb.Parity = NOPARITY;
9839 dcb.fErrorChar = FALSE;
9840 if (NILP (tem))
9842 summary[1] = 'N';
9844 else if (EQ (tem, Qeven))
9846 summary[1] = 'E';
9847 dcb.fParity = TRUE;
9848 dcb.Parity = EVENPARITY;
9849 dcb.fErrorChar = TRUE;
9851 else if (EQ (tem, Qodd))
9853 summary[1] = 'O';
9854 dcb.fParity = TRUE;
9855 dcb.Parity = ODDPARITY;
9856 dcb.fErrorChar = TRUE;
9858 childp2 = Fplist_put (childp2, QCparity, tem);
9860 /* Configure stopbits. */
9861 if (!NILP (Fplist_member (contact, QCstopbits)))
9862 tem = Fplist_get (contact, QCstopbits);
9863 else
9864 tem = Fplist_get (p->childp, QCstopbits);
9865 if (NILP (tem))
9866 tem = make_number (1);
9867 CHECK_NUMBER (tem);
9868 if (XINT (tem) != 1 && XINT (tem) != 2)
9869 error (":stopbits must be nil (1 stopbit), 1, or 2");
9870 summary[2] = XINT (tem) + '0';
9871 if (XINT (tem) == 1)
9872 dcb.StopBits = ONESTOPBIT;
9873 else if (XINT (tem) == 2)
9874 dcb.StopBits = TWOSTOPBITS;
9875 childp2 = Fplist_put (childp2, QCstopbits, tem);
9877 /* Configure flowcontrol. */
9878 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9879 tem = Fplist_get (contact, QCflowcontrol);
9880 else
9881 tem = Fplist_get (p->childp, QCflowcontrol);
9882 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9883 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9884 dcb.fOutxCtsFlow = FALSE;
9885 dcb.fOutxDsrFlow = FALSE;
9886 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9887 dcb.fDsrSensitivity = FALSE;
9888 dcb.fTXContinueOnXoff = FALSE;
9889 dcb.fOutX = FALSE;
9890 dcb.fInX = FALSE;
9891 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9892 dcb.XonChar = 17; /* Control-Q */
9893 dcb.XoffChar = 19; /* Control-S */
9894 if (NILP (tem))
9896 /* Already configured. */
9898 else if (EQ (tem, Qhw))
9900 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9901 dcb.fOutxCtsFlow = TRUE;
9903 else if (EQ (tem, Qsw))
9905 dcb.fOutX = TRUE;
9906 dcb.fInX = TRUE;
9908 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9910 /* Activate configuration. */
9911 if (!SetCommState (hnd, &dcb))
9912 error ("SetCommState() failed");
9914 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9915 pset_childp (p, childp2);
9918 /* For make-pipe-process */
9919 void
9920 register_aux_fd (int infd)
9922 child_process *cp;
9924 cp = new_child ();
9925 if (!cp)
9926 error ("Could not create child process");
9927 cp->fd = infd;
9928 cp->status = STATUS_READ_ACKNOWLEDGED;
9930 if (fd_info[ infd ].cp != NULL)
9932 error ("fd_info[fd = %d] is already in use", infd);
9934 fd_info[ infd ].cp = cp;
9935 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9938 #ifdef HAVE_GNUTLS
9940 ssize_t
9941 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9943 int n, err;
9944 struct Lisp_Process *process = (struct Lisp_Process *)p;
9945 int fd = process->infd;
9947 n = sys_read (fd, (char*)buf, sz);
9949 if (n >= 0)
9950 return n;
9952 err = errno;
9954 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9955 if (err == EWOULDBLOCK)
9956 err = EAGAIN;
9958 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9960 return -1;
9963 ssize_t
9964 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9966 struct Lisp_Process *process = (struct Lisp_Process *)p;
9967 int fd = process->outfd;
9968 ssize_t n = sys_write (fd, buf, sz);
9970 /* 0 or more bytes written means everything went fine. */
9971 if (n >= 0)
9972 return n;
9974 /* Negative bytes written means we got an error in errno.
9975 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9976 emacs_gnutls_transport_set_errno (process->gnutls_state,
9977 errno == EWOULDBLOCK ? EAGAIN : errno);
9979 return -1;
9981 #endif /* HAVE_GNUTLS */
9983 /* end of w32.c */