Restore a test that was removed by a recent commit
[emacs.git] / src / w32.c
blobf35ad67d829e89675001a2d9dba59e1b28025e70
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 #include <sys/timeb.h>
2983 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2985 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2987 struct _timeb tb;
2988 _ftime (&tb);
2990 tv->tv_sec = tb.time;
2991 tv->tv_usec = tb.millitm * 1000L;
2992 /* Implementation note: _ftime sometimes doesn't update the dstflag
2993 according to the new timezone when the system timezone is
2994 changed. We could fix that by using GetSystemTime and
2995 GetTimeZoneInformation, but that doesn't seem necessary, since
2996 Emacs always calls gettimeofday with the 2nd argument NULL (see
2997 current_emacs_time). */
2998 if (tz)
3000 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
3001 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
3003 return 0;
3006 /* Emulate fdutimens. */
3008 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
3009 TIMESPEC[0] and TIMESPEC[1], respectively.
3010 FD must be either negative -- in which case it is ignored --
3011 or a file descriptor that is open on FILE.
3012 If FD is nonnegative, then FILE can be NULL, which means
3013 use just futimes instead of utimes.
3014 If TIMESPEC is null, FAIL.
3015 Return 0 on success, -1 (setting errno) on failure. */
3018 fdutimens (int fd, char const *file, struct timespec const timespec[2])
3020 if (!timespec)
3022 errno = ENOSYS;
3023 return -1;
3025 if (fd < 0 && !file)
3027 errno = EBADF;
3028 return -1;
3030 /* _futime's prototype defines 2nd arg as having the type 'struct
3031 _utimbuf', while utime needs to accept 'struct utimbuf' for
3032 compatibility with Posix. So we need to use 2 different (but
3033 equivalent) types to avoid compiler warnings, sigh. */
3034 if (fd >= 0)
3036 struct _utimbuf _ut;
3038 _ut.actime = timespec[0].tv_sec;
3039 _ut.modtime = timespec[1].tv_sec;
3040 return _futime (fd, &_ut);
3042 else
3044 struct utimbuf ut;
3046 ut.actime = timespec[0].tv_sec;
3047 ut.modtime = timespec[1].tv_sec;
3048 /* Call 'utime', which is implemented below, not the MS library
3049 function, which fails on directories. */
3050 return utime (file, &ut);
3055 /* ------------------------------------------------------------------------- */
3056 /* IO support and wrapper functions for the Windows API. */
3057 /* ------------------------------------------------------------------------- */
3059 /* Place a wrapper around the MSVC version of ctime. It returns NULL
3060 on network directories, so we handle that case here.
3061 (Ulrich Leodolter, 1/11/95). */
3062 char *
3063 sys_ctime (const time_t *t)
3065 char *str = (char *) ctime (t);
3066 return (str ? str : (char *)"Sun Jan 01 00:00:00 1970");
3069 /* Emulate sleep...we could have done this with a define, but that
3070 would necessitate including windows.h in the files that used it.
3071 This is much easier. */
3072 void
3073 sys_sleep (int seconds)
3075 Sleep (seconds * 1000);
3078 /* Internal MSVC functions for low-level descriptor munging */
3079 extern int __cdecl _set_osfhnd (int fd, long h);
3080 extern int __cdecl _free_osfhnd (int fd);
3082 /* parallel array of private info on file handles */
3083 filedesc fd_info [ MAXDESC ];
3085 typedef struct volume_info_data {
3086 struct volume_info_data * next;
3088 /* time when info was obtained */
3089 DWORD timestamp;
3091 /* actual volume info */
3092 char * root_dir;
3093 DWORD serialnum;
3094 DWORD maxcomp;
3095 DWORD flags;
3096 char * name;
3097 char * type;
3098 } volume_info_data;
3100 /* Global referenced by various functions. */
3101 static volume_info_data volume_info;
3103 /* Vector to indicate which drives are local and fixed (for which cached
3104 data never expires). */
3105 static BOOL fixed_drives[26];
3107 /* Consider cached volume information to be stale if older than 10s,
3108 at least for non-local drives. Info for fixed drives is never stale. */
3109 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3110 #define VOLINFO_STILL_VALID( root_dir, info ) \
3111 ( ( isalpha (root_dir[0]) && \
3112 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3113 || GetTickCount () - info->timestamp < 10000 )
3115 /* Cache support functions. */
3117 /* Simple linked list with linear search is sufficient. */
3118 static volume_info_data *volume_cache = NULL;
3120 static volume_info_data *
3121 lookup_volume_info (char * root_dir)
3123 volume_info_data * info;
3125 for (info = volume_cache; info; info = info->next)
3126 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3127 break;
3128 return info;
3131 static void
3132 add_volume_info (char * root_dir, volume_info_data * info)
3134 info->root_dir = xstrdup (root_dir);
3135 unixtodos_filename (info->root_dir);
3136 info->next = volume_cache;
3137 volume_cache = info;
3141 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3142 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3143 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3144 static volume_info_data *
3145 GetCachedVolumeInformation (char * root_dir)
3147 volume_info_data * info;
3148 char default_root[ MAX_UTF8_PATH ];
3149 char name[MAX_PATH+1];
3150 char type[MAX_PATH+1];
3152 /* NULL for root_dir means use root from current directory. */
3153 if (root_dir == NULL)
3155 if (w32_unicode_filenames)
3157 wchar_t curdirw[MAX_PATH];
3159 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3160 return NULL;
3161 filename_from_utf16 (curdirw, default_root);
3163 else
3165 char curdira[MAX_PATH];
3167 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3168 return NULL;
3169 filename_from_ansi (curdira, default_root);
3171 parse_root (default_root, (const char **)&root_dir);
3172 *root_dir = 0;
3173 root_dir = default_root;
3176 /* Local fixed drives can be cached permanently. Removable drives
3177 cannot be cached permanently, since the volume name and serial
3178 number (if nothing else) can change. Remote drives should be
3179 treated as if they are removable, since there is no sure way to
3180 tell whether they are or not. Also, the UNC association of drive
3181 letters mapped to remote volumes can be changed at any time (even
3182 by other processes) without notice.
3184 As a compromise, so we can benefit from caching info for remote
3185 volumes, we use a simple expiry mechanism to invalidate cache
3186 entries that are more than ten seconds old. */
3188 #if 0
3189 /* No point doing this, because WNetGetConnection is even slower than
3190 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3191 GetDriveType is about the only call of this type which does not
3192 involve network access, and so is extremely quick). */
3194 /* Map drive letter to UNC if remote. */
3195 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3197 char remote_name[ 256 ];
3198 char drive[3] = { root_dir[0], ':' };
3200 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3201 == NO_ERROR)
3202 /* do something */ ;
3204 #endif
3206 info = lookup_volume_info (root_dir);
3208 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3210 DWORD serialnum;
3211 DWORD maxcomp;
3212 DWORD flags;
3214 /* Info is not cached, or is stale. */
3215 if (w32_unicode_filenames)
3217 wchar_t root_w[MAX_PATH];
3218 wchar_t name_w[MAX_PATH+1];
3219 wchar_t type_w[MAX_PATH+1];
3221 filename_to_utf16 (root_dir, root_w);
3222 if (!GetVolumeInformationW (root_w,
3223 name_w, sizeof (name_w),
3224 &serialnum,
3225 &maxcomp,
3226 &flags,
3227 type_w, sizeof (type_w)))
3228 return NULL;
3229 /* Hmm... not really 100% correct, as these 2 are not file
3230 names... */
3231 filename_from_utf16 (name_w, name);
3232 filename_from_utf16 (type_w, type);
3234 else
3236 char root_a[MAX_PATH];
3237 char name_a[MAX_PATH+1];
3238 char type_a[MAX_PATH+1];
3240 filename_to_ansi (root_dir, root_a);
3241 if (!GetVolumeInformationA (root_a,
3242 name_a, sizeof (name_a),
3243 &serialnum,
3244 &maxcomp,
3245 &flags,
3246 type_a, sizeof (type_a)))
3247 return NULL;
3248 filename_from_ansi (name_a, name);
3249 filename_from_ansi (type_a, type);
3252 /* Cache the volume information for future use, overwriting existing
3253 entry if present. */
3254 if (info == NULL)
3256 info = xmalloc (sizeof (volume_info_data));
3257 add_volume_info (root_dir, info);
3259 else
3261 xfree (info->name);
3262 xfree (info->type);
3265 info->name = xstrdup (name);
3266 unixtodos_filename (info->name);
3267 info->serialnum = serialnum;
3268 info->maxcomp = maxcomp;
3269 info->flags = flags;
3270 info->type = xstrdup (type);
3271 info->timestamp = GetTickCount ();
3274 return info;
3277 /* Get information on the volume where NAME is held; set path pointer to
3278 start of pathname in NAME (past UNC header\volume header if present),
3279 if pPath is non-NULL.
3281 Note: if NAME includes symlinks, the information is for the volume
3282 of the symlink, not of its target. That's because, even though
3283 GetVolumeInformation returns information about the symlink target
3284 of its argument, we only pass the root directory to
3285 GetVolumeInformation, not the full NAME. */
3286 static int
3287 get_volume_info (const char * name, const char ** pPath)
3289 char temp[MAX_UTF8_PATH];
3290 char *rootname = NULL; /* default to current volume */
3291 volume_info_data * info;
3292 int root_len = parse_root (name, pPath);
3294 if (name == NULL)
3295 return FALSE;
3297 /* Copy the root name of the volume, if given. */
3298 if (root_len)
3300 strncpy (temp, name, root_len);
3301 temp[root_len] = '\0';
3302 unixtodos_filename (temp);
3303 rootname = temp;
3306 info = GetCachedVolumeInformation (rootname);
3307 if (info != NULL)
3309 /* Set global referenced by other functions. */
3310 volume_info = *info;
3311 return TRUE;
3313 return FALSE;
3316 /* Determine if volume is FAT format (ie. only supports short 8.3
3317 names); also set path pointer to start of pathname in name, if
3318 pPath is non-NULL. */
3319 static int
3320 is_fat_volume (const char * name, const char ** pPath)
3322 if (get_volume_info (name, pPath))
3323 return (volume_info.maxcomp == 12);
3324 return FALSE;
3327 /* Convert all slashes in a filename to backslashes, and map filename
3328 to a valid 8.3 name if necessary. The result is a pointer to a
3329 static buffer, so CAVEAT EMPTOR! */
3330 const char *map_w32_filename (const char *, const char **);
3332 const char *
3333 map_w32_filename (const char * name, const char ** pPath)
3335 static char shortname[MAX_UTF8_PATH];
3336 char * str = shortname;
3337 char c;
3338 char * path;
3339 const char * save_name = name;
3341 if (strlen (name) >= sizeof (shortname))
3343 /* Return a filename which will cause callers to fail. */
3344 strcpy (shortname, "?");
3345 return shortname;
3348 if (!fatal_error_in_progress /* disable fancy processing during crash */
3349 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3351 register int left = 8; /* maximum number of chars in part */
3352 register int extn = 0; /* extension added? */
3353 register int dots = 2; /* maximum number of dots allowed */
3355 while (name < path)
3356 *str++ = *name++; /* skip past UNC header */
3358 while ((c = *name++))
3360 switch ( c )
3362 case ':':
3363 case '\\':
3364 case '/':
3365 *str++ = (c == ':' ? ':' : '\\');
3366 extn = 0; /* reset extension flags */
3367 dots = 2; /* max 2 dots */
3368 left = 8; /* max length 8 for main part */
3369 break;
3370 case '.':
3371 if ( dots )
3373 /* Convert path components of the form .xxx to _xxx,
3374 but leave . and .. as they are. This allows .emacs
3375 to be read as _emacs, for example. */
3377 if (! *name ||
3378 *name == '.' ||
3379 IS_DIRECTORY_SEP (*name))
3381 *str++ = '.';
3382 dots--;
3384 else
3386 *str++ = '_';
3387 left--;
3388 dots = 0;
3391 else if ( !extn )
3393 *str++ = '.';
3394 extn = 1; /* we've got an extension */
3395 left = 3; /* 3 chars in extension */
3397 else
3399 /* any embedded dots after the first are converted to _ */
3400 *str++ = '_';
3402 break;
3403 case '~':
3404 case '#': /* don't lose these, they're important */
3405 if ( ! left )
3406 str[-1] = c; /* replace last character of part */
3407 /* FALLTHRU */
3408 default:
3409 if ( left && 'A' <= c && c <= 'Z' )
3411 *str++ = tolower (c); /* map to lower case (looks nicer) */
3412 left--;
3413 dots = 0; /* started a path component */
3415 break;
3418 *str = '\0';
3420 else
3422 strcpy (shortname, name);
3423 unixtodos_filename (shortname);
3426 if (pPath)
3427 *pPath = shortname + (path - save_name);
3429 return shortname;
3432 static int
3433 is_exec (const char * name)
3435 char * p = strrchr (name, '.');
3436 return
3437 (p != NULL
3438 && (xstrcasecmp (p, ".exe") == 0 ||
3439 xstrcasecmp (p, ".com") == 0 ||
3440 xstrcasecmp (p, ".bat") == 0 ||
3441 xstrcasecmp (p, ".cmd") == 0));
3444 /* Emulate the Unix directory procedures opendir, closedir, and
3445 readdir. We rename them to sys_* names because some versions of
3446 MinGW startup code call opendir and readdir to glob wildcards, and
3447 the code that calls them doesn't grok UTF-8 encoded file names we
3448 produce in dirent->d_name[]. */
3450 struct dirent dir_static; /* simulated directory contents */
3451 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3452 static int dir_is_fat;
3453 static char dir_pathname[MAX_UTF8_PATH];
3454 static WIN32_FIND_DATAW dir_find_data_w;
3455 static WIN32_FIND_DATAA dir_find_data_a;
3456 #define DIR_FIND_DATA_W 1
3457 #define DIR_FIND_DATA_A 2
3458 static int last_dir_find_data = -1;
3460 /* Support shares on a network resource as subdirectories of a read-only
3461 root directory. */
3462 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3463 static HANDLE open_unc_volume (const char *);
3464 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3465 static void close_unc_volume (HANDLE);
3467 DIR *
3468 sys_opendir (const char *filename)
3470 DIR *dirp;
3472 /* Opening is done by FindFirstFile. However, a read is inherent to
3473 this operation, so we defer the open until read time. */
3475 if (dir_find_handle != INVALID_HANDLE_VALUE)
3476 return NULL;
3477 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3478 return NULL;
3480 /* Note: We don't support traversal of UNC volumes via symlinks.
3481 Doing so would mean punishing 99.99% of use cases by resolving
3482 all the possible symlinks in FILENAME, recursively. */
3483 if (is_unc_volume (filename))
3485 wnet_enum_handle = open_unc_volume (filename);
3486 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3487 return NULL;
3490 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3491 return NULL;
3493 dirp->dd_fd = 0;
3494 dirp->dd_loc = 0;
3495 dirp->dd_size = 0;
3497 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3498 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3499 /* Note: We don't support symlinks to file names on FAT volumes.
3500 Doing so would mean punishing 99.99% of use cases by resolving
3501 all the possible symlinks in FILENAME, recursively. */
3502 dir_is_fat = is_fat_volume (filename, NULL);
3504 return dirp;
3507 void
3508 sys_closedir (DIR *dirp)
3510 /* If we have a find-handle open, close it. */
3511 if (dir_find_handle != INVALID_HANDLE_VALUE)
3513 FindClose (dir_find_handle);
3514 dir_find_handle = INVALID_HANDLE_VALUE;
3516 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3518 close_unc_volume (wnet_enum_handle);
3519 wnet_enum_handle = INVALID_HANDLE_VALUE;
3521 xfree ((char *) dirp);
3524 struct dirent *
3525 sys_readdir (DIR *dirp)
3527 int downcase = !NILP (Vw32_downcase_file_names);
3529 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3531 if (!read_unc_volume (wnet_enum_handle,
3532 dir_find_data_w.cFileName,
3533 dir_find_data_a.cFileName,
3534 MAX_PATH))
3535 return NULL;
3537 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3538 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3540 char filename[MAX_UTF8_PATH];
3541 int ln;
3542 bool last_slash = true;
3544 /* Note: We don't need to worry about dir_pathname being longer
3545 than MAX_UTF8_PATH, as sys_opendir already took care of that
3546 when it called map_w32_filename: that function will put a "?"
3547 in its return value in that case, thus failing all the calls
3548 below. */
3549 strcpy (filename, dir_pathname);
3550 ln = strlen (filename);
3551 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3552 last_slash = false;
3554 /* Note: No need to resolve symlinks in FILENAME, because
3555 FindFirst opens the directory that is the target of a
3556 symlink. */
3557 if (w32_unicode_filenames)
3559 wchar_t fnw[MAX_PATH + 2];
3561 filename_to_utf16 (filename, fnw);
3562 if (!last_slash)
3563 wcscat (fnw, L"\\");
3564 wcscat (fnw, L"*");
3565 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3567 else
3569 char fna[MAX_PATH + 2];
3571 filename_to_ansi (filename, fna);
3572 if (!last_slash)
3573 strcat (fna, "\\");
3574 strcat (fna, "*");
3575 /* If FILENAME is not representable by the current ANSI
3576 codepage, we don't want FindFirstFileA to interpret the
3577 '?' characters as a wildcard. */
3578 if (_mbspbrk (fna, "?"))
3579 dir_find_handle = INVALID_HANDLE_VALUE;
3580 else
3581 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3584 if (dir_find_handle == INVALID_HANDLE_VALUE)
3586 /* Any changes in the value of errno here should be in sync
3587 with what directory_files_internal does when it calls
3588 readdir. */
3589 switch (GetLastError ())
3591 /* Windows uses this value when FindFirstFile finds no
3592 files that match the wildcard. This is not supposed
3593 to happen, since our wildcard is "*", but just in
3594 case, if there's some weird empty directory with not
3595 even "." and ".." entries... */
3596 case ERROR_FILE_NOT_FOUND:
3597 errno = 0;
3598 /* FALLTHRU */
3599 default:
3600 break;
3601 case ERROR_ACCESS_DENIED:
3602 case ERROR_NETWORK_ACCESS_DENIED:
3603 errno = EACCES;
3604 break;
3605 case ERROR_PATH_NOT_FOUND:
3606 case ERROR_INVALID_DRIVE:
3607 case ERROR_NOT_READY:
3608 case ERROR_BAD_NETPATH:
3609 case ERROR_BAD_NET_NAME:
3610 errno = ENOENT;
3611 break;
3613 return NULL;
3616 else if (w32_unicode_filenames)
3618 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3620 errno = 0;
3621 return NULL;
3624 else
3626 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3628 errno = 0;
3629 return NULL;
3633 /* Emacs never uses this value, so don't bother making it match
3634 value returned by stat(). */
3635 dir_static.d_ino = 1;
3637 if (w32_unicode_filenames)
3639 if (downcase || dir_is_fat)
3641 wchar_t tem[MAX_PATH];
3643 wcscpy (tem, dir_find_data_w.cFileName);
3644 CharLowerW (tem);
3645 filename_from_utf16 (tem, dir_static.d_name);
3647 else
3648 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3649 last_dir_find_data = DIR_FIND_DATA_W;
3651 else
3653 char tem[MAX_PATH];
3655 /* If the file name in cFileName[] includes `?' characters, it
3656 means the original file name used characters that cannot be
3657 represented by the current ANSI codepage. To avoid total
3658 lossage, retrieve the short 8+3 alias of the long file
3659 name. */
3660 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3662 strcpy (tem, dir_find_data_a.cAlternateFileName);
3663 /* 8+3 aliases are returned in all caps, which could break
3664 various alists that look at filenames' extensions. */
3665 downcase = 1;
3667 else if (downcase || dir_is_fat)
3668 strcpy (tem, dir_find_data_a.cFileName);
3669 else
3670 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3671 if (downcase || dir_is_fat)
3673 _mbslwr (tem);
3674 filename_from_ansi (tem, dir_static.d_name);
3676 last_dir_find_data = DIR_FIND_DATA_A;
3679 dir_static.d_namlen = strlen (dir_static.d_name);
3680 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3681 dir_static.d_namlen - dir_static.d_namlen % 4;
3683 return &dir_static;
3686 static HANDLE
3687 open_unc_volume (const char *path)
3689 const char *fn = map_w32_filename (path, NULL);
3690 DWORD result;
3691 HANDLE henum;
3693 if (w32_unicode_filenames)
3695 NETRESOURCEW nrw;
3696 wchar_t fnw[MAX_PATH];
3698 nrw.dwScope = RESOURCE_GLOBALNET;
3699 nrw.dwType = RESOURCETYPE_DISK;
3700 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3701 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3702 nrw.lpLocalName = NULL;
3703 filename_to_utf16 (fn, fnw);
3704 nrw.lpRemoteName = fnw;
3705 nrw.lpComment = NULL;
3706 nrw.lpProvider = NULL;
3708 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3709 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3711 else
3713 NETRESOURCEA nra;
3714 char fna[MAX_PATH];
3716 nra.dwScope = RESOURCE_GLOBALNET;
3717 nra.dwType = RESOURCETYPE_DISK;
3718 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3719 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3720 nra.lpLocalName = NULL;
3721 filename_to_ansi (fn, fna);
3722 nra.lpRemoteName = fna;
3723 nra.lpComment = NULL;
3724 nra.lpProvider = NULL;
3726 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3727 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3729 if (result == NO_ERROR)
3730 return henum;
3731 else
3733 /* Make sure directory_files_internal reports a sensible error. */
3734 errno = ENOENT;
3735 return INVALID_HANDLE_VALUE;
3739 static void *
3740 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3742 DWORD count;
3743 int result;
3744 char *buffer;
3745 DWORD bufsize = 512;
3746 void *retval;
3748 count = 1;
3749 if (w32_unicode_filenames)
3751 wchar_t *ptrw;
3753 bufsize *= 2;
3754 buffer = alloca (bufsize);
3755 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3756 if (result != NO_ERROR)
3757 return NULL;
3758 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3759 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3760 ptrw += 2;
3761 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3762 ptrw++;
3763 wcsncpy (fname_w, ptrw, size);
3764 retval = fname_w;
3766 else
3768 int dbcs_p = max_filename_mbslen () > 1;
3769 char *ptra;
3771 buffer = alloca (bufsize);
3772 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3773 if (result != NO_ERROR)
3774 return NULL;
3775 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3776 ptra += 2;
3777 if (!dbcs_p)
3778 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3779 else
3781 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3782 ptra = CharNextExA (file_name_codepage, ptra, 0);
3784 ptra++;
3785 strncpy (fname_a, ptra, size);
3786 retval = fname_a;
3789 return retval;
3792 static void
3793 close_unc_volume (HANDLE henum)
3795 if (henum != INVALID_HANDLE_VALUE)
3796 WNetCloseEnum (henum);
3799 static DWORD
3800 unc_volume_file_attributes (const char *path)
3802 HANDLE henum;
3803 DWORD attrs;
3805 henum = open_unc_volume (path);
3806 if (henum == INVALID_HANDLE_VALUE)
3807 return -1;
3809 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3811 close_unc_volume (henum);
3813 return attrs;
3816 /* Ensure a network connection is authenticated. */
3817 static void
3818 logon_network_drive (const char *path)
3820 char share[MAX_UTF8_PATH];
3821 int n_slashes;
3822 char drive[4];
3823 UINT drvtype;
3824 char *p;
3825 DWORD val;
3827 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3828 drvtype = DRIVE_REMOTE;
3829 else if (path[0] == '\0' || path[1] != ':')
3830 drvtype = GetDriveType (NULL);
3831 else
3833 drive[0] = path[0];
3834 drive[1] = ':';
3835 drive[2] = '\\';
3836 drive[3] = '\0';
3837 drvtype = GetDriveType (drive);
3840 /* Only logon to networked drives. */
3841 if (drvtype != DRIVE_REMOTE)
3842 return;
3844 n_slashes = 2;
3845 strncpy (share, path, MAX_UTF8_PATH);
3846 /* Truncate to just server and share name. */
3847 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3849 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3851 *p = '\0';
3852 break;
3856 if (w32_unicode_filenames)
3858 NETRESOURCEW resourcew;
3859 wchar_t share_w[MAX_PATH];
3861 resourcew.dwScope = RESOURCE_GLOBALNET;
3862 resourcew.dwType = RESOURCETYPE_DISK;
3863 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3864 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3865 resourcew.lpLocalName = NULL;
3866 filename_to_utf16 (share, share_w);
3867 resourcew.lpRemoteName = share_w;
3868 resourcew.lpProvider = NULL;
3870 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3872 else
3874 NETRESOURCEA resourcea;
3875 char share_a[MAX_PATH];
3877 resourcea.dwScope = RESOURCE_GLOBALNET;
3878 resourcea.dwType = RESOURCETYPE_DISK;
3879 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3880 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3881 resourcea.lpLocalName = NULL;
3882 filename_to_ansi (share, share_a);
3883 resourcea.lpRemoteName = share_a;
3884 resourcea.lpProvider = NULL;
3886 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3889 switch (val)
3891 case NO_ERROR:
3892 case ERROR_ALREADY_ASSIGNED:
3893 break;
3894 case ERROR_ACCESS_DENIED:
3895 case ERROR_LOGON_FAILURE:
3896 errno = EACCES;
3897 break;
3898 case ERROR_BUSY:
3899 errno = EAGAIN;
3900 break;
3901 case ERROR_BAD_NET_NAME:
3902 case ERROR_NO_NET_OR_BAD_PATH:
3903 case ERROR_NO_NETWORK:
3904 case ERROR_CANCELLED:
3905 default:
3906 errno = ENOENT;
3907 break;
3911 /* Emulate faccessat(2). */
3913 faccessat (int dirfd, const char * path, int mode, int flags)
3915 DWORD attributes;
3917 if (dirfd != AT_FDCWD
3918 && !(IS_DIRECTORY_SEP (path[0])
3919 || IS_DEVICE_SEP (path[1])))
3921 errno = EBADF;
3922 return -1;
3925 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3926 newer versions blow up when passed D_OK. */
3927 path = map_w32_filename (path, NULL);
3928 /* If the last element of PATH is a symlink, we need to resolve it
3929 to get the attributes of its target file. Note: any symlinks in
3930 PATH elements other than the last one are transparently resolved
3931 by GetFileAttributes below. */
3932 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3933 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3934 path = chase_symlinks (path);
3936 if (w32_unicode_filenames)
3938 wchar_t path_w[MAX_PATH];
3940 filename_to_utf16 (path, path_w);
3941 attributes = GetFileAttributesW (path_w);
3943 else
3945 char path_a[MAX_PATH];
3947 filename_to_ansi (path, path_a);
3948 attributes = GetFileAttributesA (path_a);
3951 if (attributes == -1)
3953 DWORD w32err = GetLastError ();
3955 switch (w32err)
3957 case ERROR_INVALID_NAME:
3958 case ERROR_BAD_PATHNAME:
3959 if (is_unc_volume (path))
3961 attributes = unc_volume_file_attributes (path);
3962 if (attributes == -1)
3964 errno = EACCES;
3965 return -1;
3967 goto check_attrs;
3969 /* FALLTHROUGH */
3970 case ERROR_FILE_NOT_FOUND:
3971 case ERROR_BAD_NETPATH:
3972 errno = ENOENT;
3973 break;
3974 default:
3975 errno = EACCES;
3976 break;
3978 return -1;
3981 check_attrs:
3982 if ((mode & X_OK) != 0
3983 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3985 errno = EACCES;
3986 return -1;
3988 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3990 errno = EACCES;
3991 return -1;
3993 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3995 errno = EACCES;
3996 return -1;
3998 return 0;
4001 /* A special test for DIRNAME being a directory accessible by the
4002 current user. This is needed because the security permissions in
4003 directory's ACLs are not visible in the Posix-style mode bits
4004 returned by 'stat' and in attributes returned by GetFileAttributes.
4005 So a directory would seem like it's readable by the current user,
4006 but will in fact error out with EACCES when they actually try. */
4008 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
4010 char pattern[MAX_UTF8_PATH];
4011 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
4012 HANDLE dh;
4014 /* Network volumes need a different reading method. */
4015 if (is_unc_volume (dirname))
4017 void *read_result = NULL;
4018 wchar_t fnw[MAX_PATH];
4019 char fna[MAX_PATH];
4021 dh = open_unc_volume (dirname);
4022 if (dh != INVALID_HANDLE_VALUE)
4024 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
4025 close_unc_volume (dh);
4027 /* Treat empty volumes as accessible. */
4028 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
4031 /* Note: map_w32_filename makes sure DIRNAME is not longer than
4032 MAX_UTF8_PATH. */
4033 strcpy (pattern, map_w32_filename (dirname, NULL));
4035 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
4036 opens the directory that is the target of a symlink. */
4037 if (w32_unicode_filenames)
4039 wchar_t pat_w[MAX_PATH + 2];
4040 WIN32_FIND_DATAW dfd_w;
4042 filename_to_utf16 (pattern, pat_w);
4043 if (!last_slash)
4044 wcscat (pat_w, L"\\");
4045 wcscat (pat_w, L"*");
4046 dh = FindFirstFileW (pat_w, &dfd_w);
4048 else
4050 char pat_a[MAX_PATH + 2];
4051 WIN32_FIND_DATAA dfd_a;
4053 filename_to_ansi (pattern, pat_a);
4054 if (!last_slash)
4055 strcpy (pat_a, "\\");
4056 strcat (pat_a, "*");
4057 /* In case DIRNAME cannot be expressed in characters from the
4058 current ANSI codepage. */
4059 if (_mbspbrk (pat_a, "?"))
4060 dh = INVALID_HANDLE_VALUE;
4061 else
4062 dh = FindFirstFileA (pat_a, &dfd_a);
4065 if (dh == INVALID_HANDLE_VALUE)
4066 return 0;
4067 FindClose (dh);
4068 return 1;
4071 /* A version of 'access' to be used locally with file names in
4072 locale-specific encoding. Does not resolve symlinks and does not
4073 support file names on FAT12 and FAT16 volumes, but that's OK, since
4074 we only invoke this function for files inside the Emacs source or
4075 installation tree, on directories (so any symlinks should have the
4076 directory bit set), and on short file names such as "C:/.emacs". */
4077 static int
4078 sys_access (const char *fname, int mode)
4080 char fname_copy[MAX_PATH], *p;
4081 DWORD attributes;
4083 strcpy (fname_copy, fname);
4084 /* Do the equivalent of unixtodos_filename. */
4085 for (p = fname_copy; *p; p = CharNext (p))
4086 if (*p == '/')
4087 *p = '\\';
4089 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4091 DWORD w32err = GetLastError ();
4093 switch (w32err)
4095 case ERROR_INVALID_NAME:
4096 case ERROR_BAD_PATHNAME:
4097 case ERROR_FILE_NOT_FOUND:
4098 case ERROR_BAD_NETPATH:
4099 errno = ENOENT;
4100 break;
4101 default:
4102 errno = EACCES;
4103 break;
4105 return -1;
4107 if ((mode & X_OK) != 0
4108 && !(is_exec (fname_copy)
4109 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4111 errno = EACCES;
4112 return -1;
4114 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4116 errno = EACCES;
4117 return -1;
4119 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4121 errno = EACCES;
4122 return -1;
4124 return 0;
4127 /* Shadow some MSVC runtime functions to map requests for long filenames
4128 to reasonable short names if necessary. This was originally added to
4129 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4130 long file names. */
4133 sys_chdir (const char * path)
4135 path = map_w32_filename (path, NULL);
4136 if (w32_unicode_filenames)
4138 wchar_t newdir_w[MAX_PATH];
4140 if (filename_to_utf16 (path, newdir_w) == 0)
4141 return _wchdir (newdir_w);
4142 return -1;
4144 else
4146 char newdir_a[MAX_PATH];
4148 if (filename_to_ansi (path, newdir_a) == 0)
4149 return _chdir (newdir_a);
4150 return -1;
4155 sys_chmod (const char * path, int mode)
4157 path = chase_symlinks (map_w32_filename (path, NULL));
4158 if (w32_unicode_filenames)
4160 wchar_t path_w[MAX_PATH];
4162 filename_to_utf16 (path, path_w);
4163 return _wchmod (path_w, mode);
4165 else
4167 char path_a[MAX_PATH];
4169 filename_to_ansi (path, path_a);
4170 return _chmod (path_a, mode);
4175 sys_creat (const char * path, int mode)
4177 path = map_w32_filename (path, NULL);
4178 if (w32_unicode_filenames)
4180 wchar_t path_w[MAX_PATH];
4182 filename_to_utf16 (path, path_w);
4183 return _wcreat (path_w, mode);
4185 else
4187 char path_a[MAX_PATH];
4189 filename_to_ansi (path, path_a);
4190 return _creat (path_a, mode);
4194 FILE *
4195 sys_fopen (const char * path, const char * mode)
4197 int fd;
4198 int oflag;
4199 const char * mode_save = mode;
4201 /* Force all file handles to be non-inheritable. This is necessary to
4202 ensure child processes don't unwittingly inherit handles that might
4203 prevent future file access. */
4205 if (mode[0] == 'r')
4206 oflag = O_RDONLY;
4207 else if (mode[0] == 'w' || mode[0] == 'a')
4208 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4209 else
4210 return NULL;
4212 /* Only do simplistic option parsing. */
4213 while (*++mode)
4214 if (mode[0] == '+')
4216 oflag &= ~(O_RDONLY | O_WRONLY);
4217 oflag |= O_RDWR;
4219 else if (mode[0] == 'b')
4221 oflag &= ~O_TEXT;
4222 oflag |= O_BINARY;
4224 else if (mode[0] == 't')
4226 oflag &= ~O_BINARY;
4227 oflag |= O_TEXT;
4229 else break;
4231 path = map_w32_filename (path, NULL);
4232 if (w32_unicode_filenames)
4234 wchar_t path_w[MAX_PATH];
4236 filename_to_utf16 (path, path_w);
4237 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4239 else
4241 char path_a[MAX_PATH];
4243 filename_to_ansi (path, path_a);
4244 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4246 if (fd < 0)
4247 return NULL;
4249 return _fdopen (fd, mode_save);
4252 /* This only works on NTFS volumes, but is useful to have. */
4254 sys_link (const char * old, const char * new)
4256 HANDLE fileh;
4257 int result = -1;
4258 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4259 wchar_t oldname_w[MAX_PATH];
4260 char oldname_a[MAX_PATH];
4262 if (old == NULL || new == NULL)
4264 errno = ENOENT;
4265 return -1;
4268 strcpy (oldname, map_w32_filename (old, NULL));
4269 strcpy (newname, map_w32_filename (new, NULL));
4271 if (w32_unicode_filenames)
4273 filename_to_utf16 (oldname, oldname_w);
4274 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4275 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4277 else
4279 filename_to_ansi (oldname, oldname_a);
4280 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4281 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4283 if (fileh != INVALID_HANDLE_VALUE)
4285 int wlen;
4287 /* Confusingly, the "alternate" stream name field does not apply
4288 when restoring a hard link, and instead contains the actual
4289 stream data for the link (ie. the name of the link to create).
4290 The WIN32_STREAM_ID structure before the cStreamName field is
4291 the stream header, which is then immediately followed by the
4292 stream data. */
4294 struct {
4295 WIN32_STREAM_ID wid;
4296 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4297 } data;
4299 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4300 indicates that flag is unsupported for CP_UTF8, and OTOH says
4301 it is the default anyway. */
4302 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4303 data.wid.cStreamName, MAX_PATH);
4304 if (wlen > 0)
4306 LPVOID context = NULL;
4307 DWORD wbytes = 0;
4309 data.wid.dwStreamId = BACKUP_LINK;
4310 data.wid.dwStreamAttributes = 0;
4311 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4312 data.wid.Size.HighPart = 0;
4313 data.wid.dwStreamNameSize = 0;
4315 if (BackupWrite (fileh, (LPBYTE)&data,
4316 offsetof (WIN32_STREAM_ID, cStreamName)
4317 + data.wid.Size.LowPart,
4318 &wbytes, FALSE, FALSE, &context)
4319 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4321 /* succeeded */
4322 result = 0;
4324 else
4326 DWORD err = GetLastError ();
4327 DWORD attributes;
4329 switch (err)
4331 case ERROR_ACCESS_DENIED:
4332 /* This is what happens when OLDNAME is a directory,
4333 since Windows doesn't support hard links to
4334 directories. Posix says to set errno to EPERM in
4335 that case. */
4336 if (w32_unicode_filenames)
4337 attributes = GetFileAttributesW (oldname_w);
4338 else
4339 attributes = GetFileAttributesA (oldname_a);
4340 if (attributes != -1
4341 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4342 errno = EPERM;
4343 else if (attributes == -1
4344 && is_unc_volume (oldname)
4345 && unc_volume_file_attributes (oldname) != -1)
4346 errno = EPERM;
4347 else
4348 errno = EACCES;
4349 break;
4350 case ERROR_TOO_MANY_LINKS:
4351 errno = EMLINK;
4352 break;
4353 case ERROR_NOT_SAME_DEVICE:
4354 errno = EXDEV;
4355 break;
4356 default:
4357 errno = EINVAL;
4358 break;
4363 CloseHandle (fileh);
4365 else
4366 errno = ENOENT;
4368 return result;
4372 sys_mkdir (const char * path)
4374 path = map_w32_filename (path, NULL);
4376 if (w32_unicode_filenames)
4378 wchar_t path_w[MAX_PATH];
4380 filename_to_utf16 (path, path_w);
4381 return _wmkdir (path_w);
4383 else
4385 char path_a[MAX_PATH];
4387 filename_to_ansi (path, path_a);
4388 return _mkdir (path_a);
4393 sys_open (const char * path, int oflag, int mode)
4395 const char* mpath = map_w32_filename (path, NULL);
4396 int res = -1;
4398 if (w32_unicode_filenames)
4400 wchar_t mpath_w[MAX_PATH];
4402 filename_to_utf16 (mpath, mpath_w);
4403 /* If possible, try to open file without _O_CREAT, to be able to
4404 write to existing hidden and system files. Force all file
4405 handles to be non-inheritable. */
4406 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4407 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4408 if (res < 0)
4409 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4411 else
4413 char mpath_a[MAX_PATH];
4415 filename_to_ansi (mpath, mpath_a);
4416 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4417 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4418 if (res < 0)
4419 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4422 return res;
4425 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4426 when using mktemp.
4428 Standard algorithm for generating a temporary file name seems to be
4429 use pid or tid with a letter on the front (in place of the 6 X's)
4430 and cycle through the letters to find a unique name. We extend
4431 that to allow any reasonable character as the first of the 6 X's,
4432 so that the number of simultaneously used temporary files will be
4433 greater. */
4436 mkostemp (char * template, int flags)
4438 char * p;
4439 int i, fd = -1;
4440 unsigned uid = GetCurrentThreadId ();
4441 int save_errno = errno;
4442 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4444 errno = EINVAL;
4445 if (template == NULL)
4446 return -1;
4448 p = template + strlen (template);
4449 i = 5;
4450 /* replace up to the last 5 X's with uid in decimal */
4451 while (--p >= template && p[0] == 'X' && --i >= 0)
4453 p[0] = '0' + uid % 10;
4454 uid /= 10;
4457 if (i < 0 && p[0] == 'X')
4459 i = 0;
4462 p[0] = first_char[i];
4463 if ((fd = sys_open (template,
4464 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4465 S_IRUSR | S_IWUSR)) >= 0
4466 || errno != EEXIST)
4468 if (fd >= 0)
4469 errno = save_errno;
4470 return fd;
4473 while (++i < sizeof (first_char));
4476 /* Template is badly formed or else we can't generate a unique name. */
4477 return -1;
4481 fchmod (int fd, mode_t mode)
4483 return 0;
4487 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4489 BOOL result;
4490 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4491 int newname_dev;
4492 int oldname_dev;
4493 bool have_temp_a = false;
4495 /* MoveFile on Windows 95 doesn't correctly change the short file name
4496 alias in a number of circumstances (it is not easy to predict when
4497 just by looking at oldname and newname, unfortunately). In these
4498 cases, renaming through a temporary name avoids the problem.
4500 A second problem on Windows 95 is that renaming through a temp name when
4501 newname is uppercase fails (the final long name ends up in
4502 lowercase, although the short alias might be uppercase) UNLESS the
4503 long temp name is not 8.3.
4505 So, on Windows 95 we always rename through a temp name, and we make sure
4506 the temp name has a long extension to ensure correct renaming. */
4508 strcpy (temp, map_w32_filename (oldname, NULL));
4510 /* volume_info is set indirectly by map_w32_filename. */
4511 oldname_dev = volume_info.serialnum;
4513 if (os_subtype == OS_9X)
4515 char * o;
4516 char * p;
4517 int i = 0;
4518 char oldname_a[MAX_PATH];
4520 oldname = map_w32_filename (oldname, NULL);
4521 filename_to_ansi (oldname, oldname_a);
4522 filename_to_ansi (temp, temp_a);
4523 if ((o = strrchr (oldname_a, '\\')))
4524 o++;
4525 else
4526 o = (char *) oldname_a;
4528 if ((p = strrchr (temp_a, '\\')))
4529 p++;
4530 else
4531 p = temp_a;
4535 /* Force temp name to require a manufactured 8.3 alias - this
4536 seems to make the second rename work properly. */
4537 sprintf (p, "_.%s.%d", o, i);
4538 i++;
4539 result = rename (oldname_a, temp_a);
4541 /* This loop must surely terminate! */
4542 while (result < 0 && errno == EEXIST);
4543 if (result < 0)
4544 return -1;
4545 have_temp_a = true;
4548 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4549 (at least if it is a file; don't do this for directories).
4551 Since we mustn't do this if we are just changing the case of the
4552 file name (we would end up deleting the file we are trying to
4553 rename!), we let rename detect if the destination file already
4554 exists - that way we avoid the possible pitfalls of trying to
4555 determine ourselves whether two names really refer to the same
4556 file, which is not always possible in the general case. (Consider
4557 all the permutations of shared or subst'd drives, etc.) */
4559 newname = map_w32_filename (newname, NULL);
4561 /* volume_info is set indirectly by map_w32_filename. */
4562 newname_dev = volume_info.serialnum;
4564 if (w32_unicode_filenames)
4566 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4568 filename_to_utf16 (temp, temp_w);
4569 filename_to_utf16 (newname, newname_w);
4570 result = _wrename (temp_w, newname_w);
4571 if (result < 0 && force)
4573 DWORD w32err = GetLastError ();
4575 if (errno == EACCES
4576 && newname_dev != oldname_dev)
4578 /* The implementation of `rename' on Windows does not return
4579 errno = EXDEV when you are moving a directory to a
4580 different storage device (ex. logical disk). It returns
4581 EACCES instead. So here we handle such situations and
4582 return EXDEV. */
4583 DWORD attributes;
4585 if ((attributes = GetFileAttributesW (temp_w)) != -1
4586 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4587 errno = EXDEV;
4589 else if (errno == EEXIST)
4591 if (_wchmod (newname_w, 0666) != 0)
4592 return result;
4593 if (_wunlink (newname_w) != 0)
4594 return result;
4595 result = _wrename (temp_w, newname_w);
4597 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4598 && is_symlink (temp))
4600 /* This is Windows prohibiting the user from creating a
4601 symlink in another place, since that requires
4602 privileges. */
4603 errno = EPERM;
4607 else
4609 char newname_a[MAX_PATH];
4611 if (!have_temp_a)
4612 filename_to_ansi (temp, temp_a);
4613 filename_to_ansi (newname, newname_a);
4614 result = rename (temp_a, newname_a);
4615 if (result < 0 && force)
4617 DWORD w32err = GetLastError ();
4619 if (errno == EACCES
4620 && newname_dev != oldname_dev)
4622 DWORD attributes;
4624 if ((attributes = GetFileAttributesA (temp_a)) != -1
4625 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4626 errno = EXDEV;
4628 else if (errno == EEXIST)
4630 if (_chmod (newname_a, 0666) != 0)
4631 return result;
4632 if (_unlink (newname_a) != 0)
4633 return result;
4634 result = rename (temp_a, newname_a);
4636 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4637 && is_symlink (temp))
4638 errno = EPERM;
4642 return result;
4646 sys_rename (char const *old, char const *new)
4648 return sys_rename_replace (old, new, TRUE);
4652 sys_rmdir (const char * path)
4654 path = map_w32_filename (path, NULL);
4656 if (w32_unicode_filenames)
4658 wchar_t path_w[MAX_PATH];
4660 filename_to_utf16 (path, path_w);
4661 return _wrmdir (path_w);
4663 else
4665 char path_a[MAX_PATH];
4667 filename_to_ansi (path, path_a);
4668 return _rmdir (path_a);
4673 sys_unlink (const char * path)
4675 int rmstatus, e;
4677 path = map_w32_filename (path, NULL);
4679 if (w32_unicode_filenames)
4681 wchar_t path_w[MAX_PATH];
4683 filename_to_utf16 (path, path_w);
4684 /* On Unix, unlink works without write permission. */
4685 _wchmod (path_w, 0666);
4686 rmstatus = _wunlink (path_w);
4687 e = errno;
4688 /* Symlinks to directories can only be deleted by _rmdir;
4689 _unlink returns EACCES. */
4690 if (rmstatus != 0
4691 && errno == EACCES
4692 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4693 rmstatus = _wrmdir (path_w);
4694 else
4695 errno = e;
4697 else
4699 char path_a[MAX_PATH];
4701 filename_to_ansi (path, path_a);
4702 _chmod (path_a, 0666);
4703 rmstatus = _unlink (path_a);
4704 e = errno;
4705 if (rmstatus != 0
4706 && errno == EACCES
4707 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4708 rmstatus = _rmdir (path_a);
4709 else
4710 errno = e;
4713 return rmstatus;
4716 static FILETIME utc_base_ft;
4717 static ULONGLONG utc_base; /* In 100ns units */
4718 static int init = 0;
4720 #define FILETIME_TO_U64(result, ft) \
4721 do { \
4722 ULARGE_INTEGER uiTemp; \
4723 uiTemp.LowPart = (ft).dwLowDateTime; \
4724 uiTemp.HighPart = (ft).dwHighDateTime; \
4725 result = uiTemp.QuadPart; \
4726 } while (0)
4728 static void
4729 initialize_utc_base (void)
4731 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4732 SYSTEMTIME st;
4734 st.wYear = 1970;
4735 st.wMonth = 1;
4736 st.wDay = 1;
4737 st.wHour = 0;
4738 st.wMinute = 0;
4739 st.wSecond = 0;
4740 st.wMilliseconds = 0;
4742 SystemTimeToFileTime (&st, &utc_base_ft);
4743 FILETIME_TO_U64 (utc_base, utc_base_ft);
4746 static time_t
4747 convert_time (FILETIME ft)
4749 ULONGLONG tmp;
4751 if (!init)
4753 initialize_utc_base ();
4754 init = 1;
4757 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4758 return 0;
4760 FILETIME_TO_U64 (tmp, ft);
4761 return (time_t) ((tmp - utc_base) / 10000000L);
4764 static void
4765 convert_from_time_t (time_t time, FILETIME * pft)
4767 ULARGE_INTEGER tmp;
4769 if (!init)
4771 initialize_utc_base ();
4772 init = 1;
4775 /* time in 100ns units since 1-Jan-1601 */
4776 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4777 pft->dwHighDateTime = tmp.HighPart;
4778 pft->dwLowDateTime = tmp.LowPart;
4781 static PSECURITY_DESCRIPTOR
4782 get_file_security_desc_by_handle (HANDLE h)
4784 PSECURITY_DESCRIPTOR psd = NULL;
4785 DWORD err;
4786 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4787 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4789 err = get_security_info (h, SE_FILE_OBJECT, si,
4790 NULL, NULL, NULL, NULL, &psd);
4791 if (err != ERROR_SUCCESS)
4792 return NULL;
4794 return psd;
4797 static PSECURITY_DESCRIPTOR
4798 get_file_security_desc_by_name (const char *fname)
4800 PSECURITY_DESCRIPTOR psd = NULL;
4801 DWORD sd_len, err;
4802 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4803 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4805 if (!get_file_security (fname, si, psd, 0, &sd_len))
4807 err = GetLastError ();
4808 if (err != ERROR_INSUFFICIENT_BUFFER)
4809 return NULL;
4812 psd = xmalloc (sd_len);
4813 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4815 xfree (psd);
4816 return NULL;
4819 return psd;
4822 static DWORD
4823 get_rid (PSID sid)
4825 unsigned n_subauthorities;
4827 /* Use the last sub-authority value of the RID, the relative
4828 portion of the SID, as user/group ID. */
4829 n_subauthorities = *get_sid_sub_authority_count (sid);
4830 if (n_subauthorities < 1)
4831 return 0; /* the "World" RID */
4832 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4835 /* Caching SID and account values for faster lokup. */
4837 struct w32_id {
4838 unsigned rid;
4839 struct w32_id *next;
4840 char name[GNLEN+1];
4841 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4844 static struct w32_id *w32_idlist;
4846 static int
4847 w32_cached_id (PSID sid, unsigned *id, char *name)
4849 struct w32_id *tail, *found;
4851 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4853 if (equal_sid ((PSID)tail->sid, sid))
4855 found = tail;
4856 break;
4859 if (found)
4861 *id = found->rid;
4862 strcpy (name, found->name);
4863 return 1;
4865 else
4866 return 0;
4869 static void
4870 w32_add_to_cache (PSID sid, unsigned id, char *name)
4872 DWORD sid_len;
4873 struct w32_id *new_entry;
4875 /* We don't want to leave behind stale cache from when Emacs was
4876 dumped. */
4877 if (initialized)
4879 sid_len = get_length_sid (sid);
4880 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4881 if (new_entry)
4883 new_entry->rid = id;
4884 strcpy (new_entry->name, name);
4885 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4886 new_entry->next = w32_idlist;
4887 w32_idlist = new_entry;
4892 #define UID 1
4893 #define GID 2
4895 static int
4896 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4898 PSID sid = NULL;
4899 BOOL dflt;
4900 SID_NAME_USE ignore;
4901 char name[UNLEN+1];
4902 DWORD name_len = sizeof (name);
4903 char domain[1024];
4904 DWORD domain_len = sizeof (domain);
4905 int use_dflt = 0;
4906 int result;
4908 if (what == UID)
4909 result = get_security_descriptor_owner (psd, &sid, &dflt);
4910 else if (what == GID)
4911 result = get_security_descriptor_group (psd, &sid, &dflt);
4912 else
4913 result = 0;
4915 if (!result || !is_valid_sid (sid))
4916 use_dflt = 1;
4917 else if (!w32_cached_id (sid, id, nm))
4919 if (!lookup_account_sid (NULL, sid, name, &name_len,
4920 domain, &domain_len, &ignore)
4921 || name_len > UNLEN+1)
4922 use_dflt = 1;
4923 else
4925 *id = get_rid (sid);
4926 strcpy (nm, name);
4927 w32_add_to_cache (sid, *id, name);
4930 return use_dflt;
4933 static void
4934 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4936 int dflt_usr = 0, dflt_grp = 0;
4938 if (!psd)
4940 dflt_usr = 1;
4941 dflt_grp = 1;
4943 else
4945 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4946 dflt_usr = 1;
4947 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4948 dflt_grp = 1;
4950 /* Consider files to belong to current user/group, if we cannot get
4951 more accurate information. */
4952 if (dflt_usr)
4954 st->st_uid = dflt_passwd.pw_uid;
4955 strcpy (st->st_uname, dflt_passwd.pw_name);
4957 if (dflt_grp)
4959 st->st_gid = dflt_passwd.pw_gid;
4960 strcpy (st->st_gname, dflt_group.gr_name);
4964 /* Return non-zero if NAME is a potentially slow filesystem. */
4965 int is_slow_fs (const char *);
4968 is_slow_fs (const char *name)
4970 char drive_root[4];
4971 UINT devtype;
4973 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4974 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4975 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4976 devtype = GetDriveType (NULL); /* use root of current drive */
4977 else
4979 /* GetDriveType needs the root directory of the drive. */
4980 strncpy (drive_root, name, 2);
4981 drive_root[2] = '\\';
4982 drive_root[3] = '\0';
4983 devtype = GetDriveType (drive_root);
4985 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4988 /* If this is non-zero, the caller wants accurate information about
4989 file's owner and group, which could be expensive to get. dired.c
4990 uses this flag when needed for the job at hand. */
4991 int w32_stat_get_owner_group;
4993 /* MSVC stat function can't cope with UNC names and has other bugs, so
4994 replace it with our own. This also allows us to calculate consistent
4995 inode values and owner/group without hacks in the main Emacs code,
4996 and support file names encoded in UTF-8. */
4998 static int
4999 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
5001 char *name, *save_name, *r;
5002 WIN32_FIND_DATAW wfd_w;
5003 WIN32_FIND_DATAA wfd_a;
5004 HANDLE fh;
5005 unsigned __int64 fake_inode = 0;
5006 int permission;
5007 int len;
5008 int rootdir = FALSE;
5009 PSECURITY_DESCRIPTOR psd = NULL;
5010 int is_a_symlink = 0;
5011 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
5012 DWORD access_rights = 0;
5013 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
5014 FILETIME ctime, atime, wtime;
5015 wchar_t name_w[MAX_PATH];
5016 char name_a[MAX_PATH];
5018 if (path == NULL || buf == NULL)
5020 errno = EFAULT;
5021 return -1;
5024 save_name = name = (char *) map_w32_filename (path, &path);
5025 /* Must be valid filename, no wild cards or other invalid
5026 characters. */
5027 if (strpbrk (name, "*?|<>\""))
5029 errno = ENOENT;
5030 return -1;
5033 len = strlen (name);
5034 /* Allocate 1 extra byte so that we could append a slash to a root
5035 directory, down below. */
5036 name = strcpy (alloca (len + 2), name);
5038 /* Avoid a somewhat costly call to is_symlink if the filesystem
5039 doesn't support symlinks. */
5040 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5041 is_a_symlink = is_symlink (name);
5043 /* Plan A: Open the file and get all the necessary information via
5044 the resulting handle. This solves several issues in one blow:
5046 . retrieves attributes for the target of a symlink, if needed
5047 . gets attributes of root directories and symlinks pointing to
5048 root directories, thus avoiding the need for special-casing
5049 these and detecting them by examining the file-name format
5050 . retrieves more accurate attributes (e.g., non-zero size for
5051 some directories, esp. directories that are junction points)
5052 . correctly resolves "c:/..", "/.." and similar file names
5053 . avoids run-time penalties for 99% of use cases
5055 Plan A is always tried first, unless the user asked not to (but
5056 if the file is a symlink and we need to follow links, we try Plan
5057 A even if the user asked not to).
5059 If Plan A fails, we go to Plan B (below), where various
5060 potentially expensive techniques must be used to handle "special"
5061 files such as UNC volumes etc. */
5062 if (!(NILP (Vw32_get_true_file_attributes)
5063 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
5064 /* Following symlinks requires getting the info by handle. */
5065 || (is_a_symlink && follow_symlinks))
5067 BY_HANDLE_FILE_INFORMATION info;
5069 if (is_a_symlink && !follow_symlinks)
5070 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5071 /* READ_CONTROL access rights are required to get security info
5072 by handle. But if the OS doesn't support security in the
5073 first place, we don't need to try. */
5074 if (is_windows_9x () != TRUE)
5075 access_rights |= READ_CONTROL;
5077 if (w32_unicode_filenames)
5079 filename_to_utf16 (name, name_w);
5080 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
5081 file_flags, NULL);
5082 /* If CreateFile fails with READ_CONTROL, try again with
5083 zero as access rights. */
5084 if (fh == INVALID_HANDLE_VALUE && access_rights)
5085 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
5086 file_flags, NULL);
5088 else
5090 filename_to_ansi (name, name_a);
5091 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5092 file_flags, NULL);
5093 if (fh == INVALID_HANDLE_VALUE && access_rights)
5094 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5095 file_flags, NULL);
5097 if (fh == INVALID_HANDLE_VALUE)
5098 goto no_true_file_attributes;
5100 /* This is more accurate in terms of getting the correct number
5101 of links, but is quite slow (it is noticeable when Emacs is
5102 making a list of file name completions). */
5103 if (GetFileInformationByHandle (fh, &info))
5105 nlinks = info.nNumberOfLinks;
5106 /* Might as well use file index to fake inode values, but this
5107 is not guaranteed to be unique unless we keep a handle open
5108 all the time (even then there are situations where it is
5109 not unique). Reputedly, there are at most 48 bits of info
5110 (on NTFS, presumably less on FAT). */
5111 fake_inode = info.nFileIndexHigh;
5112 fake_inode <<= 32;
5113 fake_inode += info.nFileIndexLow;
5114 serialnum = info.dwVolumeSerialNumber;
5115 fs_high = info.nFileSizeHigh;
5116 fs_low = info.nFileSizeLow;
5117 ctime = info.ftCreationTime;
5118 atime = info.ftLastAccessTime;
5119 wtime = info.ftLastWriteTime;
5120 fattrs = info.dwFileAttributes;
5122 else
5124 /* We don't go to Plan B here, because it's not clear that
5125 it's a good idea. The only known use case where
5126 CreateFile succeeds, but GetFileInformationByHandle fails
5127 (with ERROR_INVALID_FUNCTION) is for character devices
5128 such as NUL, PRN, etc. For these, switching to Plan B is
5129 a net loss, because we lose the character device
5130 attribute returned by GetFileType below (FindFirstFile
5131 doesn't set that bit in the attributes), and the other
5132 fields don't make sense for character devices anyway.
5133 Emacs doesn't really care for non-file entities in the
5134 context of l?stat, so neither do we. */
5136 /* w32err is assigned so one could put a breakpoint here and
5137 examine its value, when GetFileInformationByHandle
5138 fails. */
5139 DWORD w32err = GetLastError ();
5141 switch (w32err)
5143 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5144 errno = ENOENT;
5145 return -1;
5149 /* Test for a symlink before testing for a directory, since
5150 symlinks to directories have the directory bit set, but we
5151 don't want them to appear as directories. */
5152 if (is_a_symlink && !follow_symlinks)
5153 buf->st_mode = S_IFLNK;
5154 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5155 buf->st_mode = S_IFDIR;
5156 else
5158 DWORD ftype = GetFileType (fh);
5160 switch (ftype)
5162 case FILE_TYPE_DISK:
5163 buf->st_mode = S_IFREG;
5164 break;
5165 case FILE_TYPE_PIPE:
5166 buf->st_mode = S_IFIFO;
5167 break;
5168 case FILE_TYPE_CHAR:
5169 case FILE_TYPE_UNKNOWN:
5170 default:
5171 buf->st_mode = S_IFCHR;
5174 /* We produce the fallback owner and group data, based on the
5175 current user that runs Emacs, in the following cases:
5177 . caller didn't request owner and group info
5178 . this is Windows 9X
5179 . getting security by handle failed, and we need to produce
5180 information for the target of a symlink (this is better
5181 than producing a potentially misleading info about the
5182 symlink itself)
5184 If getting security by handle fails, and we don't need to
5185 resolve symlinks, we try getting security by name. */
5186 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5187 get_file_owner_and_group (NULL, buf);
5188 else
5190 psd = get_file_security_desc_by_handle (fh);
5191 if (psd)
5193 get_file_owner_and_group (psd, buf);
5194 LocalFree (psd);
5196 else if (!(is_a_symlink && follow_symlinks))
5198 psd = get_file_security_desc_by_name (name);
5199 get_file_owner_and_group (psd, buf);
5200 xfree (psd);
5202 else
5203 get_file_owner_and_group (NULL, buf);
5205 CloseHandle (fh);
5207 else
5209 no_true_file_attributes:
5210 /* Plan B: Either getting a handle on the file failed, or the
5211 caller explicitly asked us to not bother making this
5212 information more accurate.
5214 Implementation note: In Plan B, we never bother to resolve
5215 symlinks, even if we got here because we tried Plan A and
5216 failed. That's because, even if the caller asked for extra
5217 precision by setting Vw32_get_true_file_attributes to t,
5218 resolving symlinks requires acquiring a file handle to the
5219 symlink, which we already know will fail. And if the user
5220 did not ask for extra precision, resolving symlinks will fly
5221 in the face of that request, since the user then wants the
5222 lightweight version of the code. */
5223 rootdir = (path >= save_name + len - 1
5224 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5226 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5227 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5228 if (IS_DIRECTORY_SEP (r[0])
5229 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5230 r[1] = r[2] = '\0';
5232 /* Note: If NAME is a symlink to the root of a UNC volume
5233 (i.e. "\\SERVER"), we will not detect that here, and we will
5234 return data about the symlink as result of FindFirst below.
5235 This is unfortunate, but that marginal use case does not
5236 justify a call to chase_symlinks which would impose a penalty
5237 on all the other use cases. (We get here for symlinks to
5238 roots of UNC volumes because CreateFile above fails for them,
5239 unlike with symlinks to root directories X:\ of drives.) */
5240 if (is_unc_volume (name))
5242 fattrs = unc_volume_file_attributes (name);
5243 if (fattrs == -1)
5244 return -1;
5246 ctime = atime = wtime = utc_base_ft;
5248 else if (rootdir)
5250 /* Make sure root directories end in a slash. */
5251 if (!IS_DIRECTORY_SEP (name[len-1]))
5252 strcpy (name + len, "\\");
5253 if (GetDriveType (name) < 2)
5255 errno = ENOENT;
5256 return -1;
5259 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5260 ctime = atime = wtime = utc_base_ft;
5262 else
5264 int have_wfd = -1;
5266 /* Make sure non-root directories do NOT end in a slash,
5267 otherwise FindFirstFile might fail. */
5268 if (IS_DIRECTORY_SEP (name[len-1]))
5269 name[len - 1] = 0;
5271 /* (This is hacky, but helps when doing file completions on
5272 network drives.) Optimize by using information available from
5273 active readdir if possible. */
5274 len = strlen (dir_pathname);
5275 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5276 len--;
5277 if (dir_find_handle != INVALID_HANDLE_VALUE
5278 && last_dir_find_data != -1
5279 && !(is_a_symlink && follow_symlinks)
5280 /* The 2 file-name comparisons below support only ASCII
5281 characters, and will lose (compare not equal) when
5282 the file names include non-ASCII characters that are
5283 the same but for the case. However, doing this
5284 properly involves: (a) converting both file names to
5285 UTF-16, (b) lower-casing both names using CharLowerW,
5286 and (c) comparing the results; this would be quite a
5287 bit slower, whereas Plan B is for users who want
5288 lightweight albeit inaccurate version of 'stat'. */
5289 && c_strncasecmp (save_name, dir_pathname, len) == 0
5290 && IS_DIRECTORY_SEP (name[len])
5291 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5293 have_wfd = last_dir_find_data;
5294 /* This was the last entry returned by readdir. */
5295 if (last_dir_find_data == DIR_FIND_DATA_W)
5296 wfd_w = dir_find_data_w;
5297 else
5298 wfd_a = dir_find_data_a;
5300 else
5302 logon_network_drive (name);
5304 if (w32_unicode_filenames)
5306 filename_to_utf16 (name, name_w);
5307 fh = FindFirstFileW (name_w, &wfd_w);
5308 have_wfd = DIR_FIND_DATA_W;
5310 else
5312 filename_to_ansi (name, name_a);
5313 /* If NAME includes characters not representable by
5314 the current ANSI codepage, filename_to_ansi
5315 usually replaces them with a '?'. We don't want
5316 to let FindFirstFileA interpret those as wildcards,
5317 and "succeed", returning us data from some random
5318 file in the same directory. */
5319 if (_mbspbrk (name_a, "?"))
5320 fh = INVALID_HANDLE_VALUE;
5321 else
5322 fh = FindFirstFileA (name_a, &wfd_a);
5323 have_wfd = DIR_FIND_DATA_A;
5325 if (fh == INVALID_HANDLE_VALUE)
5327 errno = ENOENT;
5328 return -1;
5330 FindClose (fh);
5332 /* Note: if NAME is a symlink, the information we get from
5333 FindFirstFile is for the symlink, not its target. */
5334 if (have_wfd == DIR_FIND_DATA_W)
5336 fattrs = wfd_w.dwFileAttributes;
5337 ctime = wfd_w.ftCreationTime;
5338 atime = wfd_w.ftLastAccessTime;
5339 wtime = wfd_w.ftLastWriteTime;
5340 fs_high = wfd_w.nFileSizeHigh;
5341 fs_low = wfd_w.nFileSizeLow;
5343 else
5345 fattrs = wfd_a.dwFileAttributes;
5346 ctime = wfd_a.ftCreationTime;
5347 atime = wfd_a.ftLastAccessTime;
5348 wtime = wfd_a.ftLastWriteTime;
5349 fs_high = wfd_a.nFileSizeHigh;
5350 fs_low = wfd_a.nFileSizeLow;
5352 fake_inode = 0;
5353 nlinks = 1;
5354 serialnum = volume_info.serialnum;
5356 if (is_a_symlink && !follow_symlinks)
5357 buf->st_mode = S_IFLNK;
5358 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5359 buf->st_mode = S_IFDIR;
5360 else
5361 buf->st_mode = S_IFREG;
5363 get_file_owner_and_group (NULL, buf);
5366 buf->st_ino = fake_inode;
5368 buf->st_dev = serialnum;
5369 buf->st_rdev = serialnum;
5371 buf->st_size = fs_high;
5372 buf->st_size <<= 32;
5373 buf->st_size += fs_low;
5374 buf->st_nlink = nlinks;
5376 /* Convert timestamps to Unix format. */
5377 buf->st_mtime = convert_time (wtime);
5378 buf->st_atime = convert_time (atime);
5379 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5380 buf->st_ctime = convert_time (ctime);
5381 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5383 /* determine rwx permissions */
5384 if (is_a_symlink && !follow_symlinks)
5385 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5386 else
5388 if (fattrs & FILE_ATTRIBUTE_READONLY)
5389 permission = S_IREAD;
5390 else
5391 permission = S_IREAD | S_IWRITE;
5393 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5394 permission |= S_IEXEC;
5395 else if (is_exec (name))
5396 permission |= S_IEXEC;
5399 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5401 return 0;
5405 stat (const char * path, struct stat * buf)
5407 return stat_worker (path, buf, 1);
5411 lstat (const char * path, struct stat * buf)
5413 return stat_worker (path, buf, 0);
5417 fstatat (int fd, char const *name, struct stat *st, int flags)
5419 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5420 This is good enough for the current usage in Emacs, but is fragile.
5422 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5423 Gnulib does this and can serve as a model. */
5424 char fullname[MAX_UTF8_PATH];
5426 if (fd != AT_FDCWD)
5428 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5430 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5431 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5432 < 0)
5434 errno = ENAMETOOLONG;
5435 return -1;
5437 name = fullname;
5440 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5443 /* Provide fstat and utime as well as stat for consistent handling of
5444 file timestamps. */
5446 fstat (int desc, struct stat * buf)
5448 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5449 BY_HANDLE_FILE_INFORMATION info;
5450 unsigned __int64 fake_inode;
5451 int permission;
5453 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5455 case FILE_TYPE_DISK:
5456 buf->st_mode = S_IFREG;
5457 if (!GetFileInformationByHandle (fh, &info))
5459 errno = EACCES;
5460 return -1;
5462 break;
5463 case FILE_TYPE_PIPE:
5464 buf->st_mode = S_IFIFO;
5465 goto non_disk;
5466 case FILE_TYPE_CHAR:
5467 case FILE_TYPE_UNKNOWN:
5468 default:
5469 buf->st_mode = S_IFCHR;
5470 non_disk:
5471 memset (&info, 0, sizeof (info));
5472 info.dwFileAttributes = 0;
5473 info.ftCreationTime = utc_base_ft;
5474 info.ftLastAccessTime = utc_base_ft;
5475 info.ftLastWriteTime = utc_base_ft;
5478 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5479 buf->st_mode = S_IFDIR;
5481 buf->st_nlink = info.nNumberOfLinks;
5482 /* Might as well use file index to fake inode values, but this
5483 is not guaranteed to be unique unless we keep a handle open
5484 all the time (even then there are situations where it is
5485 not unique). Reputedly, there are at most 48 bits of info
5486 (on NTFS, presumably less on FAT). */
5487 fake_inode = info.nFileIndexHigh;
5488 fake_inode <<= 32;
5489 fake_inode += info.nFileIndexLow;
5491 /* MSVC defines _ino_t to be short; other libc's might not. */
5492 if (sizeof (buf->st_ino) == 2)
5493 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5494 else
5495 buf->st_ino = fake_inode;
5497 /* If the caller so requested, get the true file owner and group.
5498 Otherwise, consider the file to belong to the current user. */
5499 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5500 get_file_owner_and_group (NULL, buf);
5501 else
5503 PSECURITY_DESCRIPTOR psd = NULL;
5505 psd = get_file_security_desc_by_handle (fh);
5506 if (psd)
5508 get_file_owner_and_group (psd, buf);
5509 LocalFree (psd);
5511 else
5512 get_file_owner_and_group (NULL, buf);
5515 buf->st_dev = info.dwVolumeSerialNumber;
5516 buf->st_rdev = info.dwVolumeSerialNumber;
5518 buf->st_size = info.nFileSizeHigh;
5519 buf->st_size <<= 32;
5520 buf->st_size += info.nFileSizeLow;
5522 /* Convert timestamps to Unix format. */
5523 buf->st_mtime = convert_time (info.ftLastWriteTime);
5524 buf->st_atime = convert_time (info.ftLastAccessTime);
5525 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5526 buf->st_ctime = convert_time (info.ftCreationTime);
5527 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5529 /* determine rwx permissions */
5530 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5531 permission = S_IREAD;
5532 else
5533 permission = S_IREAD | S_IWRITE;
5535 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5536 permission |= S_IEXEC;
5537 else
5539 #if 0 /* no way of knowing the filename */
5540 char * p = strrchr (name, '.');
5541 if (p != NULL &&
5542 (xstrcasecmp (p, ".exe") == 0 ||
5543 xstrcasecmp (p, ".com") == 0 ||
5544 xstrcasecmp (p, ".bat") == 0 ||
5545 xstrcasecmp (p, ".cmd") == 0))
5546 permission |= S_IEXEC;
5547 #endif
5550 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5552 return 0;
5555 /* A version of 'utime' which handles directories as well as
5556 files. */
5559 utime (const char *name, struct utimbuf *times)
5561 struct utimbuf deftime;
5562 HANDLE fh;
5563 FILETIME mtime;
5564 FILETIME atime;
5566 if (times == NULL)
5568 deftime.modtime = deftime.actime = time (NULL);
5569 times = &deftime;
5572 if (w32_unicode_filenames)
5574 wchar_t name_utf16[MAX_PATH];
5576 if (filename_to_utf16 (name, name_utf16) != 0)
5577 return -1; /* errno set by filename_to_utf16 */
5579 /* Need write access to set times. */
5580 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5581 /* If NAME specifies a directory, FILE_SHARE_DELETE
5582 allows other processes to delete files inside it,
5583 while we have the directory open. */
5584 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5585 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5587 else
5589 char name_ansi[MAX_PATH];
5591 if (filename_to_ansi (name, name_ansi) != 0)
5592 return -1; /* errno set by filename_to_ansi */
5594 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5595 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5596 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5598 if (fh != INVALID_HANDLE_VALUE)
5600 convert_from_time_t (times->actime, &atime);
5601 convert_from_time_t (times->modtime, &mtime);
5602 if (!SetFileTime (fh, NULL, &atime, &mtime))
5604 CloseHandle (fh);
5605 errno = EACCES;
5606 return -1;
5608 CloseHandle (fh);
5610 else
5612 DWORD err = GetLastError ();
5614 switch (err)
5616 case ERROR_FILE_NOT_FOUND:
5617 case ERROR_PATH_NOT_FOUND:
5618 case ERROR_INVALID_DRIVE:
5619 case ERROR_BAD_NETPATH:
5620 case ERROR_DEV_NOT_EXIST:
5621 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5622 file name includes ?s, i.e. translation to ANSI failed. */
5623 case ERROR_INVALID_NAME:
5624 errno = ENOENT;
5625 break;
5626 case ERROR_TOO_MANY_OPEN_FILES:
5627 errno = ENFILE;
5628 break;
5629 case ERROR_ACCESS_DENIED:
5630 case ERROR_SHARING_VIOLATION:
5631 errno = EACCES;
5632 break;
5633 default:
5634 errno = EINVAL;
5635 break;
5637 return -1;
5639 return 0;
5643 sys_umask (int mode)
5645 static int current_mask;
5646 int retval, arg = 0;
5648 /* The only bit we really support is the write bit. Files are
5649 always readable on MS-Windows, and the execute bit does not exist
5650 at all. */
5651 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5652 to prevent access by other users on NTFS. */
5653 if ((mode & S_IWRITE) != 0)
5654 arg |= S_IWRITE;
5656 retval = _umask (arg);
5657 /* Merge into the return value the bits they've set the last time,
5658 which msvcrt.dll ignores and never returns. Emacs insists on its
5659 notion of mask being identical to what we return. */
5660 retval |= (current_mask & ~S_IWRITE);
5661 current_mask = mode;
5663 return retval;
5667 /* Symlink-related functions. */
5668 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5669 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5670 #endif
5673 symlink (char const *filename, char const *linkname)
5675 char linkfn[MAX_UTF8_PATH], *tgtfn;
5676 DWORD flags = 0;
5677 int dir_access, filename_ends_in_slash;
5679 /* Diagnostics follows Posix as much as possible. */
5680 if (filename == NULL || linkname == NULL)
5682 errno = EFAULT;
5683 return -1;
5685 if (!*filename)
5687 errno = ENOENT;
5688 return -1;
5690 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5692 errno = ENAMETOOLONG;
5693 return -1;
5696 strcpy (linkfn, map_w32_filename (linkname, NULL));
5697 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5699 errno = EPERM;
5700 return -1;
5703 /* Note: since empty FILENAME was already rejected, we can safely
5704 refer to FILENAME[1]. */
5705 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5707 /* Non-absolute FILENAME is understood as being relative to
5708 LINKNAME's directory. We need to prepend that directory to
5709 FILENAME to get correct results from faccessat below, since
5710 otherwise it will interpret FILENAME relative to the
5711 directory where the Emacs process runs. Note that
5712 make-symbolic-link always makes sure LINKNAME is a fully
5713 expanded file name. */
5714 char tem[MAX_UTF8_PATH];
5715 char *p = linkfn + strlen (linkfn);
5717 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5718 p--;
5719 if (p > linkfn)
5720 strncpy (tem, linkfn, p - linkfn);
5721 strcpy (tem + (p - linkfn), filename);
5722 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5724 else
5725 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5727 /* Since Windows distinguishes between symlinks to directories and
5728 to files, we provide a kludgy feature: if FILENAME doesn't
5729 exist, but ends in a slash, we create a symlink to directory. If
5730 FILENAME exists and is a directory, we always create a symlink to
5731 directory. */
5732 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5733 if (dir_access == 0 || filename_ends_in_slash)
5734 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5736 tgtfn = (char *)map_w32_filename (filename, NULL);
5737 if (filename_ends_in_slash)
5738 tgtfn[strlen (tgtfn) - 1] = '\0';
5740 errno = 0;
5741 if (!create_symbolic_link (linkfn, tgtfn, flags))
5743 /* ENOSYS is set by create_symbolic_link, when it detects that
5744 the OS doesn't support the CreateSymbolicLink API. */
5745 if (errno != ENOSYS)
5747 DWORD w32err = GetLastError ();
5749 switch (w32err)
5751 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5752 TGTFN point to the same file name, go figure. */
5753 case ERROR_SUCCESS:
5754 case ERROR_FILE_EXISTS:
5755 errno = EEXIST;
5756 break;
5757 case ERROR_ACCESS_DENIED:
5758 errno = EACCES;
5759 break;
5760 case ERROR_FILE_NOT_FOUND:
5761 case ERROR_PATH_NOT_FOUND:
5762 case ERROR_BAD_NETPATH:
5763 case ERROR_INVALID_REPARSE_DATA:
5764 errno = ENOENT;
5765 break;
5766 case ERROR_DIRECTORY:
5767 errno = EISDIR;
5768 break;
5769 case ERROR_PRIVILEGE_NOT_HELD:
5770 case ERROR_NOT_ALL_ASSIGNED:
5771 errno = EPERM;
5772 break;
5773 case ERROR_DISK_FULL:
5774 errno = ENOSPC;
5775 break;
5776 default:
5777 errno = EINVAL;
5778 break;
5781 return -1;
5783 return 0;
5786 /* A quick inexpensive test of whether FILENAME identifies a file that
5787 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5788 must already be in the normalized form returned by
5789 map_w32_filename. If the symlink is to a directory, the
5790 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5792 Note: for repeated operations on many files, it is best to test
5793 whether the underlying volume actually supports symlinks, by
5794 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5795 avoid the call to this function if it doesn't. That's because the
5796 call to GetFileAttributes takes a non-negligible time, especially
5797 on non-local or removable filesystems. See stat_worker for an
5798 example of how to do that. */
5799 static int
5800 is_symlink (const char *filename)
5802 DWORD attrs;
5803 wchar_t filename_w[MAX_PATH];
5804 char filename_a[MAX_PATH];
5805 WIN32_FIND_DATAW wfdw;
5806 WIN32_FIND_DATAA wfda;
5807 HANDLE fh;
5808 int attrs_mean_symlink;
5810 if (w32_unicode_filenames)
5812 filename_to_utf16 (filename, filename_w);
5813 attrs = GetFileAttributesW (filename_w);
5815 else
5817 filename_to_ansi (filename, filename_a);
5818 attrs = GetFileAttributesA (filename_a);
5820 if (attrs == -1)
5822 DWORD w32err = GetLastError ();
5824 switch (w32err)
5826 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5827 break;
5828 case ERROR_ACCESS_DENIED:
5829 errno = EACCES;
5830 break;
5831 case ERROR_FILE_NOT_FOUND:
5832 case ERROR_PATH_NOT_FOUND:
5833 default:
5834 errno = ENOENT;
5835 break;
5837 return 0;
5839 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5840 return 0;
5841 logon_network_drive (filename);
5842 if (w32_unicode_filenames)
5844 fh = FindFirstFileW (filename_w, &wfdw);
5845 attrs_mean_symlink =
5846 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5847 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5848 if (attrs_mean_symlink)
5849 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5851 else if (_mbspbrk (filename_a, "?"))
5853 /* filename_to_ansi failed to convert the file name. */
5854 errno = ENOENT;
5855 return 0;
5857 else
5859 fh = FindFirstFileA (filename_a, &wfda);
5860 attrs_mean_symlink =
5861 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5862 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5863 if (attrs_mean_symlink)
5864 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5866 if (fh == INVALID_HANDLE_VALUE)
5867 return 0;
5868 FindClose (fh);
5869 return attrs_mean_symlink;
5872 /* If NAME identifies a symbolic link, copy into BUF the file name of
5873 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5874 null-terminate the target name, even if it fits. Return the number
5875 of bytes copied, or -1 if NAME is not a symlink or any error was
5876 encountered while resolving it. The file name copied into BUF is
5877 encoded in the current ANSI codepage. */
5878 ssize_t
5879 readlink (const char *name, char *buf, size_t buf_size)
5881 const char *path;
5882 TOKEN_PRIVILEGES privs;
5883 int restore_privs = 0;
5884 HANDLE sh;
5885 ssize_t retval;
5886 char resolved[MAX_UTF8_PATH];
5888 if (name == NULL)
5890 errno = EFAULT;
5891 return -1;
5893 if (!*name)
5895 errno = ENOENT;
5896 return -1;
5899 path = map_w32_filename (name, NULL);
5901 if (strlen (path) > MAX_UTF8_PATH)
5903 errno = ENAMETOOLONG;
5904 return -1;
5907 errno = 0;
5908 if (is_windows_9x () == TRUE
5909 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5910 || !is_symlink (path))
5912 if (!errno)
5913 errno = EINVAL; /* not a symlink */
5914 return -1;
5917 /* Done with simple tests, now we're in for some _real_ work. */
5918 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5919 restore_privs = 1;
5920 /* Implementation note: From here and onward, don't return early,
5921 since that will fail to restore the original set of privileges of
5922 the calling thread. */
5924 retval = -1; /* not too optimistic, are we? */
5926 /* Note: In the next call to CreateFile, we use zero as the 2nd
5927 argument because, when the symlink is a hidden/system file,
5928 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5929 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5930 and directory symlinks. */
5931 if (w32_unicode_filenames)
5933 wchar_t path_w[MAX_PATH];
5935 filename_to_utf16 (path, path_w);
5936 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5937 FILE_FLAG_OPEN_REPARSE_POINT
5938 | FILE_FLAG_BACKUP_SEMANTICS,
5939 NULL);
5941 else
5943 char path_a[MAX_PATH];
5945 filename_to_ansi (path, path_a);
5946 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5947 FILE_FLAG_OPEN_REPARSE_POINT
5948 | FILE_FLAG_BACKUP_SEMANTICS,
5949 NULL);
5951 if (sh != INVALID_HANDLE_VALUE)
5953 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5954 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5955 DWORD retbytes;
5957 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5958 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5959 &retbytes, NULL))
5960 errno = EIO;
5961 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5962 errno = EINVAL;
5963 else
5965 /* Copy the link target name, in wide characters, from
5966 reparse_data, then convert it to multibyte encoding in
5967 the current locale's codepage. */
5968 WCHAR *lwname;
5969 size_t lname_size;
5970 USHORT lwname_len =
5971 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5972 WCHAR *lwname_src =
5973 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5974 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5975 size_t size_to_copy = buf_size;
5977 /* According to MSDN, PrintNameLength does not include the
5978 terminating null character. */
5979 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5980 memcpy (lwname, lwname_src, lwname_len);
5981 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5982 filename_from_utf16 (lwname, resolved);
5983 dostounix_filename (resolved);
5984 lname_size = strlen (resolved) + 1;
5985 if (lname_size <= buf_size)
5986 size_to_copy = lname_size;
5987 strncpy (buf, resolved, size_to_copy);
5988 /* Success! */
5989 retval = size_to_copy;
5991 CloseHandle (sh);
5993 else
5995 /* CreateFile failed. */
5996 DWORD w32err2 = GetLastError ();
5998 switch (w32err2)
6000 case ERROR_FILE_NOT_FOUND:
6001 case ERROR_PATH_NOT_FOUND:
6002 errno = ENOENT;
6003 break;
6004 case ERROR_ACCESS_DENIED:
6005 case ERROR_TOO_MANY_OPEN_FILES:
6006 errno = EACCES;
6007 break;
6008 default:
6009 errno = EPERM;
6010 break;
6013 if (restore_privs)
6015 restore_privilege (&privs);
6016 revert_to_self ();
6019 return retval;
6022 ssize_t
6023 readlinkat (int fd, char const *name, char *buffer,
6024 size_t buffer_size)
6026 /* Rely on a hack: an open directory is modeled as file descriptor 0,
6027 as in fstatat. FIXME: Add proper support for readlinkat. */
6028 char fullname[MAX_UTF8_PATH];
6030 if (fd != AT_FDCWD)
6032 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
6033 < 0)
6035 errno = ENAMETOOLONG;
6036 return -1;
6038 name = fullname;
6041 return readlink (name, buffer, buffer_size);
6044 /* If FILE is a symlink, return its target (stored in a static
6045 buffer); otherwise return FILE.
6047 This function repeatedly resolves symlinks in the last component of
6048 a chain of symlink file names, as in foo -> bar -> baz -> ...,
6049 until it arrives at a file whose last component is not a symlink,
6050 or some error occurs. It returns the target of the last
6051 successfully resolved symlink in the chain. If it succeeds to
6052 resolve even a single symlink, the value returned is an absolute
6053 file name with backslashes (result of GetFullPathName). By
6054 contrast, if the original FILE is returned, it is unaltered.
6056 Note: This function can set errno even if it succeeds.
6058 Implementation note: we only resolve the last portion ("basename")
6059 of the argument FILE and of each following file in the chain,
6060 disregarding any possible symlinks in its leading directories.
6061 This is because Windows system calls and library functions
6062 transparently resolve symlinks in leading directories and return
6063 correct information, as long as the basename is not a symlink. */
6064 static char *
6065 chase_symlinks (const char *file)
6067 static char target[MAX_UTF8_PATH];
6068 char link[MAX_UTF8_PATH];
6069 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
6070 char target_a[MAX_PATH], link_a[MAX_PATH];
6071 ssize_t res, link_len;
6072 int loop_count = 0;
6074 if (is_windows_9x () == TRUE || !is_symlink (file))
6075 return (char *)file;
6077 if (w32_unicode_filenames)
6079 wchar_t file_w[MAX_PATH];
6081 filename_to_utf16 (file, file_w);
6082 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
6083 return (char *)file;
6084 filename_from_utf16 (link_w, link);
6086 else
6088 char file_a[MAX_PATH];
6090 filename_to_ansi (file, file_a);
6091 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6092 return (char *)file;
6093 filename_from_ansi (link_a, link);
6095 link_len = strlen (link);
6097 target[0] = '\0';
6098 do {
6100 /* Remove trailing slashes, as we want to resolve the last
6101 non-trivial part of the link name. */
6102 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6103 link[link_len--] = '\0';
6105 res = readlink (link, target, MAX_UTF8_PATH);
6106 if (res > 0)
6108 target[res] = '\0';
6109 if (!(IS_DEVICE_SEP (target[1])
6110 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6112 /* Target is relative. Append it to the directory part of
6113 the symlink, then copy the result back to target. */
6114 char *p = link + link_len;
6116 while (p > link && !IS_ANY_SEP (p[-1]))
6117 p--;
6118 strcpy (p, target);
6119 strcpy (target, link);
6121 /* Resolve any "." and ".." to get a fully-qualified file name
6122 in link[] again. */
6123 if (w32_unicode_filenames)
6125 filename_to_utf16 (target, target_w);
6126 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6127 if (link_len > 0)
6128 filename_from_utf16 (link_w, link);
6130 else
6132 filename_to_ansi (target, target_a);
6133 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6134 if (link_len > 0)
6135 filename_from_ansi (link_a, link);
6137 link_len = strlen (link);
6139 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6141 if (loop_count > 100)
6142 errno = ELOOP;
6144 if (target[0] == '\0') /* not a single call to readlink succeeded */
6145 return (char *)file;
6146 return target;
6150 /* Posix ACL emulation. */
6153 acl_valid (acl_t acl)
6155 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6158 char *
6159 acl_to_text (acl_t acl, ssize_t *size)
6161 LPTSTR str_acl;
6162 SECURITY_INFORMATION flags =
6163 OWNER_SECURITY_INFORMATION |
6164 GROUP_SECURITY_INFORMATION |
6165 DACL_SECURITY_INFORMATION;
6166 char *retval = NULL;
6167 ULONG local_size;
6168 int e = errno;
6170 errno = 0;
6172 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6174 errno = e;
6175 /* We don't want to mix heaps, so we duplicate the string in our
6176 heap and free the one allocated by the API. */
6177 retval = xstrdup (str_acl);
6178 if (size)
6179 *size = local_size;
6180 LocalFree (str_acl);
6182 else if (errno != ENOTSUP)
6183 errno = EINVAL;
6185 return retval;
6188 acl_t
6189 acl_from_text (const char *acl_str)
6191 PSECURITY_DESCRIPTOR psd, retval = NULL;
6192 ULONG sd_size;
6193 int e = errno;
6195 errno = 0;
6197 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6199 errno = e;
6200 retval = xmalloc (sd_size);
6201 memcpy (retval, psd, sd_size);
6202 LocalFree (psd);
6204 else if (errno != ENOTSUP)
6205 errno = EINVAL;
6207 return retval;
6211 acl_free (void *ptr)
6213 xfree (ptr);
6214 return 0;
6217 acl_t
6218 acl_get_file (const char *fname, acl_type_t type)
6220 PSECURITY_DESCRIPTOR psd = NULL;
6221 const char *filename;
6223 if (type == ACL_TYPE_ACCESS)
6225 DWORD sd_len, err;
6226 SECURITY_INFORMATION si =
6227 OWNER_SECURITY_INFORMATION |
6228 GROUP_SECURITY_INFORMATION |
6229 DACL_SECURITY_INFORMATION ;
6230 int e = errno;
6232 filename = map_w32_filename (fname, NULL);
6233 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6234 fname = chase_symlinks (filename);
6235 else
6236 fname = filename;
6238 errno = 0;
6239 if (!get_file_security (fname, si, psd, 0, &sd_len)
6240 && errno != ENOTSUP)
6242 err = GetLastError ();
6243 if (err == ERROR_INSUFFICIENT_BUFFER)
6245 psd = xmalloc (sd_len);
6246 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6248 xfree (psd);
6249 errno = EIO;
6250 psd = NULL;
6253 else if (err == ERROR_FILE_NOT_FOUND
6254 || err == ERROR_PATH_NOT_FOUND
6255 /* ERROR_INVALID_NAME is what we get if
6256 w32-unicode-filenames is nil and the file cannot
6257 be encoded in the current ANSI codepage. */
6258 || err == ERROR_INVALID_NAME)
6259 errno = ENOENT;
6260 else
6261 errno = EIO;
6263 else if (!errno)
6264 errno = e;
6266 else if (type != ACL_TYPE_DEFAULT)
6267 errno = EINVAL;
6269 return psd;
6273 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6275 TOKEN_PRIVILEGES old1, old2;
6276 DWORD err;
6277 int st = 0, retval = -1;
6278 SECURITY_INFORMATION flags = 0;
6279 PSID psidOwner, psidGroup;
6280 PACL pacl;
6281 BOOL dflt;
6282 BOOL dacl_present;
6283 int e;
6284 const char *filename;
6286 if (acl_valid (acl) != 0
6287 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6289 errno = EINVAL;
6290 return -1;
6293 if (type == ACL_TYPE_DEFAULT)
6295 errno = ENOSYS;
6296 return -1;
6299 filename = map_w32_filename (fname, NULL);
6300 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6301 fname = chase_symlinks (filename);
6302 else
6303 fname = filename;
6305 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6306 &dflt)
6307 && psidOwner)
6308 flags |= OWNER_SECURITY_INFORMATION;
6309 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6310 &dflt)
6311 && psidGroup)
6312 flags |= GROUP_SECURITY_INFORMATION;
6313 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6314 &pacl, &dflt)
6315 && dacl_present)
6316 flags |= DACL_SECURITY_INFORMATION;
6317 if (!flags)
6318 return 0;
6320 /* According to KB-245153, setting the owner will succeed if either:
6321 (1) the caller is the user who will be the new owner, and has the
6322 SE_TAKE_OWNERSHIP privilege, or
6323 (2) the caller has the SE_RESTORE privilege, in which case she can
6324 set any valid user or group as the owner
6326 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6327 privileges, and disregard any failures in obtaining them. If
6328 these privileges cannot be obtained, and do not already exist in
6329 the calling thread's security token, this function could fail
6330 with EPERM. */
6331 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6332 st++;
6333 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6334 st++;
6336 e = errno;
6337 errno = 0;
6338 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6339 DACL inheritance is involved, but it seems to preserve ownership
6340 better than SetNamedSecurityInfo, which is important e.g., in
6341 copy-file. */
6342 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6344 err = GetLastError ();
6346 if (errno != ENOTSUP)
6347 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6348 psidOwner, psidGroup, pacl, NULL);
6350 else
6351 err = ERROR_SUCCESS;
6352 if (err != ERROR_SUCCESS)
6354 if (errno == ENOTSUP)
6356 else if (err == ERROR_INVALID_OWNER
6357 || err == ERROR_NOT_ALL_ASSIGNED
6358 || err == ERROR_ACCESS_DENIED)
6360 /* Maybe the requested ACL and the one the file already has
6361 are identical, in which case we can silently ignore the
6362 failure. (And no, Windows doesn't.) */
6363 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6365 errno = EPERM;
6366 if (current_acl)
6368 char *acl_from = acl_to_text (current_acl, NULL);
6369 char *acl_to = acl_to_text (acl, NULL);
6371 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6373 retval = 0;
6374 errno = e;
6376 if (acl_from)
6377 acl_free (acl_from);
6378 if (acl_to)
6379 acl_free (acl_to);
6380 acl_free (current_acl);
6383 else if (err == ERROR_FILE_NOT_FOUND
6384 || err == ERROR_PATH_NOT_FOUND
6385 /* ERROR_INVALID_NAME is what we get if
6386 w32-unicode-filenames is nil and the file cannot be
6387 encoded in the current ANSI codepage. */
6388 || err == ERROR_INVALID_NAME)
6389 errno = ENOENT;
6390 else
6391 errno = EACCES;
6393 else
6395 retval = 0;
6396 errno = e;
6399 if (st)
6401 if (st >= 2)
6402 restore_privilege (&old2);
6403 restore_privilege (&old1);
6404 revert_to_self ();
6407 return retval;
6410 /* Return true if errno value ERRNUM indicates that ACLs are well
6411 supported on this system. ERRNUM should be an errno value obtained
6412 after an ACL-related system call fails. */
6413 bool
6414 acl_errno_valid (int errnum)
6416 switch (errnum)
6418 case EBUSY:
6419 case EINVAL:
6420 case ENOTSUP:
6421 return false;
6422 default:
6423 return true;
6428 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6429 have a fixed max size for file names, so we don't need the kind of
6430 alloc/malloc/realloc dance the gnulib version does. We also don't
6431 support FD-relative symlinks. */
6432 char *
6433 careadlinkat (int fd, char const *filename,
6434 char *buffer, size_t buffer_size,
6435 struct allocator const *alloc,
6436 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6438 char linkname[MAX_UTF8_PATH];
6439 ssize_t link_size;
6441 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6443 if (link_size > 0)
6445 char *retval = buffer;
6447 linkname[link_size++] = '\0';
6448 if (link_size > buffer_size)
6449 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6450 if (retval)
6451 memcpy (retval, linkname, link_size);
6453 return retval;
6455 return NULL;
6459 w32_copy_file (const char *from, const char *to,
6460 int keep_time, int preserve_ownership, int copy_acls)
6462 acl_t acl = NULL;
6463 BOOL copy_result;
6464 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6465 char from_a[MAX_PATH], to_a[MAX_PATH];
6467 /* We ignore preserve_ownership for now. */
6468 preserve_ownership = preserve_ownership;
6470 if (copy_acls)
6472 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6473 if (acl == NULL && acl_errno_valid (errno))
6474 return -2;
6476 if (w32_unicode_filenames)
6478 filename_to_utf16 (from, from_w);
6479 filename_to_utf16 (to, to_w);
6480 copy_result = CopyFileW (from_w, to_w, FALSE);
6482 else
6484 filename_to_ansi (from, from_a);
6485 filename_to_ansi (to, to_a);
6486 copy_result = CopyFileA (from_a, to_a, FALSE);
6488 if (!copy_result)
6490 /* CopyFile doesn't set errno when it fails. By far the most
6491 "popular" reason is that the target is read-only. */
6492 DWORD err = GetLastError ();
6494 switch (err)
6496 case ERROR_FILE_NOT_FOUND:
6497 errno = ENOENT;
6498 break;
6499 case ERROR_ACCESS_DENIED:
6500 errno = EACCES;
6501 break;
6502 case ERROR_ENCRYPTION_FAILED:
6503 errno = EIO;
6504 break;
6505 default:
6506 errno = EPERM;
6507 break;
6510 if (acl)
6511 acl_free (acl);
6512 return -1;
6514 /* CopyFile retains the timestamp by default. However, see
6515 "Community Additions" for CopyFile: it sounds like that is not
6516 entirely true. Testing on Windows XP confirms that modified time
6517 is copied, but creation and last-access times are not.
6518 FIXME? */
6519 else if (!keep_time)
6521 struct timespec now;
6522 DWORD attributes;
6524 if (w32_unicode_filenames)
6526 /* Ensure file is writable while its times are set. */
6527 attributes = GetFileAttributesW (to_w);
6528 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6529 now = current_timespec ();
6530 if (set_file_times (-1, to, now, now))
6532 /* Restore original attributes. */
6533 SetFileAttributesW (to_w, attributes);
6534 if (acl)
6535 acl_free (acl);
6536 return -3;
6538 /* Restore original attributes. */
6539 SetFileAttributesW (to_w, attributes);
6541 else
6543 attributes = GetFileAttributesA (to_a);
6544 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6545 now = current_timespec ();
6546 if (set_file_times (-1, to, now, now))
6548 SetFileAttributesA (to_a, attributes);
6549 if (acl)
6550 acl_free (acl);
6551 return -3;
6553 SetFileAttributesA (to_a, attributes);
6556 if (acl != NULL)
6558 bool fail =
6559 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6560 acl_free (acl);
6561 if (fail && acl_errno_valid (errno))
6562 return -4;
6565 return 0;
6569 /* Support for browsing other processes and their attributes. See
6570 process.c for the Lisp bindings. */
6572 /* Helper wrapper functions. */
6574 static HANDLE WINAPI
6575 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6577 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6579 if (g_b_init_create_toolhelp32_snapshot == 0)
6581 g_b_init_create_toolhelp32_snapshot = 1;
6582 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6583 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6584 "CreateToolhelp32Snapshot");
6586 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6588 return INVALID_HANDLE_VALUE;
6590 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6593 static BOOL WINAPI
6594 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6596 static Process32First_Proc s_pfn_Process32_First = NULL;
6598 if (g_b_init_process32_first == 0)
6600 g_b_init_process32_first = 1;
6601 s_pfn_Process32_First = (Process32First_Proc)
6602 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6603 "Process32First");
6605 if (s_pfn_Process32_First == NULL)
6607 return FALSE;
6609 return (s_pfn_Process32_First (hSnapshot, lppe));
6612 static BOOL WINAPI
6613 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6615 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6617 if (g_b_init_process32_next == 0)
6619 g_b_init_process32_next = 1;
6620 s_pfn_Process32_Next = (Process32Next_Proc)
6621 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6622 "Process32Next");
6624 if (s_pfn_Process32_Next == NULL)
6626 return FALSE;
6628 return (s_pfn_Process32_Next (hSnapshot, lppe));
6631 static BOOL WINAPI
6632 open_thread_token (HANDLE ThreadHandle,
6633 DWORD DesiredAccess,
6634 BOOL OpenAsSelf,
6635 PHANDLE TokenHandle)
6637 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6638 HMODULE hm_advapi32 = NULL;
6639 if (is_windows_9x () == TRUE)
6641 SetLastError (ERROR_NOT_SUPPORTED);
6642 return FALSE;
6644 if (g_b_init_open_thread_token == 0)
6646 g_b_init_open_thread_token = 1;
6647 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6648 s_pfn_Open_Thread_Token =
6649 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6651 if (s_pfn_Open_Thread_Token == NULL)
6653 SetLastError (ERROR_NOT_SUPPORTED);
6654 return FALSE;
6656 return (
6657 s_pfn_Open_Thread_Token (
6658 ThreadHandle,
6659 DesiredAccess,
6660 OpenAsSelf,
6661 TokenHandle)
6665 static BOOL WINAPI
6666 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6668 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6669 HMODULE hm_advapi32 = NULL;
6670 if (is_windows_9x () == TRUE)
6672 return FALSE;
6674 if (g_b_init_impersonate_self == 0)
6676 g_b_init_impersonate_self = 1;
6677 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6678 s_pfn_Impersonate_Self =
6679 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6681 if (s_pfn_Impersonate_Self == NULL)
6683 return FALSE;
6685 return s_pfn_Impersonate_Self (ImpersonationLevel);
6688 static BOOL WINAPI
6689 revert_to_self (void)
6691 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6692 HMODULE hm_advapi32 = NULL;
6693 if (is_windows_9x () == TRUE)
6695 return FALSE;
6697 if (g_b_init_revert_to_self == 0)
6699 g_b_init_revert_to_self = 1;
6700 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6701 s_pfn_Revert_To_Self =
6702 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6704 if (s_pfn_Revert_To_Self == NULL)
6706 return FALSE;
6708 return s_pfn_Revert_To_Self ();
6711 static BOOL WINAPI
6712 get_process_memory_info (HANDLE h_proc,
6713 PPROCESS_MEMORY_COUNTERS mem_counters,
6714 DWORD bufsize)
6716 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6717 HMODULE hm_psapi = NULL;
6718 if (is_windows_9x () == TRUE)
6720 return FALSE;
6722 if (g_b_init_get_process_memory_info == 0)
6724 g_b_init_get_process_memory_info = 1;
6725 hm_psapi = LoadLibrary ("Psapi.dll");
6726 if (hm_psapi)
6727 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6728 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6730 if (s_pfn_Get_Process_Memory_Info == NULL)
6732 return FALSE;
6734 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6737 static BOOL WINAPI
6738 get_process_working_set_size (HANDLE h_proc,
6739 PSIZE_T minrss,
6740 PSIZE_T maxrss)
6742 static GetProcessWorkingSetSize_Proc
6743 s_pfn_Get_Process_Working_Set_Size = NULL;
6745 if (is_windows_9x () == TRUE)
6747 return FALSE;
6749 if (g_b_init_get_process_working_set_size == 0)
6751 g_b_init_get_process_working_set_size = 1;
6752 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6753 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6754 "GetProcessWorkingSetSize");
6756 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6758 return FALSE;
6760 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6763 static BOOL WINAPI
6764 global_memory_status (MEMORYSTATUS *buf)
6766 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6768 if (is_windows_9x () == TRUE)
6770 return FALSE;
6772 if (g_b_init_global_memory_status == 0)
6774 g_b_init_global_memory_status = 1;
6775 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6776 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6777 "GlobalMemoryStatus");
6779 if (s_pfn_Global_Memory_Status == NULL)
6781 return FALSE;
6783 return s_pfn_Global_Memory_Status (buf);
6786 static BOOL WINAPI
6787 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6789 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6791 if (is_windows_9x () == TRUE)
6793 return FALSE;
6795 if (g_b_init_global_memory_status_ex == 0)
6797 g_b_init_global_memory_status_ex = 1;
6798 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6799 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6800 "GlobalMemoryStatusEx");
6802 if (s_pfn_Global_Memory_Status_Ex == NULL)
6804 return FALSE;
6806 return s_pfn_Global_Memory_Status_Ex (buf);
6809 Lisp_Object
6810 list_system_processes (void)
6812 Lisp_Object proclist = Qnil;
6813 HANDLE h_snapshot;
6815 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6817 if (h_snapshot != INVALID_HANDLE_VALUE)
6819 PROCESSENTRY32 proc_entry;
6820 DWORD proc_id;
6821 BOOL res;
6823 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6824 for (res = process32_first (h_snapshot, &proc_entry); res;
6825 res = process32_next (h_snapshot, &proc_entry))
6827 proc_id = proc_entry.th32ProcessID;
6828 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6831 CloseHandle (h_snapshot);
6832 proclist = Fnreverse (proclist);
6835 return proclist;
6838 static int
6839 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6841 TOKEN_PRIVILEGES priv;
6842 DWORD priv_size = sizeof (priv);
6843 DWORD opriv_size = sizeof (*old_priv);
6844 HANDLE h_token = NULL;
6845 HANDLE h_thread = GetCurrentThread ();
6846 int ret_val = 0;
6847 BOOL res;
6849 res = open_thread_token (h_thread,
6850 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6851 FALSE, &h_token);
6852 if (!res && GetLastError () == ERROR_NO_TOKEN)
6854 if (impersonate_self (SecurityImpersonation))
6855 res = open_thread_token (h_thread,
6856 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6857 FALSE, &h_token);
6859 if (res)
6861 priv.PrivilegeCount = 1;
6862 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6863 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6864 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6865 old_priv, &opriv_size)
6866 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6867 ret_val = 1;
6869 if (h_token)
6870 CloseHandle (h_token);
6872 return ret_val;
6875 static int
6876 restore_privilege (TOKEN_PRIVILEGES *priv)
6878 DWORD priv_size = sizeof (*priv);
6879 HANDLE h_token = NULL;
6880 int ret_val = 0;
6882 if (open_thread_token (GetCurrentThread (),
6883 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6884 FALSE, &h_token))
6886 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6887 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6888 ret_val = 1;
6890 if (h_token)
6891 CloseHandle (h_token);
6893 return ret_val;
6896 static Lisp_Object
6897 ltime (ULONGLONG time_100ns)
6899 ULONGLONG time_sec = time_100ns / 10000000;
6900 int subsec = time_100ns % 10000000;
6901 return list4i (time_sec >> 16, time_sec & 0xffff,
6902 subsec / 10, subsec % 10 * 100000);
6905 #define U64_TO_LISP_TIME(time) ltime (time)
6907 static int
6908 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6909 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6910 double *pcpu)
6912 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6913 ULONGLONG tem1, tem2, tem3, tem;
6915 if (!h_proc
6916 || !get_process_times_fn
6917 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6918 &ft_kernel, &ft_user))
6919 return 0;
6921 GetSystemTimeAsFileTime (&ft_current);
6923 FILETIME_TO_U64 (tem1, ft_kernel);
6924 *stime = U64_TO_LISP_TIME (tem1);
6926 FILETIME_TO_U64 (tem2, ft_user);
6927 *utime = U64_TO_LISP_TIME (tem2);
6929 tem3 = tem1 + tem2;
6930 *ttime = U64_TO_LISP_TIME (tem3);
6932 FILETIME_TO_U64 (tem, ft_creation);
6933 /* Process no 4 (System) returns zero creation time. */
6934 if (tem)
6935 tem -= utc_base;
6936 *ctime = U64_TO_LISP_TIME (tem);
6938 if (tem)
6940 FILETIME_TO_U64 (tem3, ft_current);
6941 tem = (tem3 - utc_base) - tem;
6943 *etime = U64_TO_LISP_TIME (tem);
6945 if (tem)
6947 *pcpu = 100.0 * (tem1 + tem2) / tem;
6948 if (*pcpu > 100)
6949 *pcpu = 100.0;
6951 else
6952 *pcpu = 0;
6954 return 1;
6957 Lisp_Object
6958 system_process_attributes (Lisp_Object pid)
6960 Lisp_Object attrs = Qnil;
6961 Lisp_Object cmd_str, decoded_cmd, tem;
6962 HANDLE h_snapshot, h_proc;
6963 DWORD proc_id;
6964 int found_proc = 0;
6965 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6966 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6967 DWORD glength = sizeof (gname);
6968 HANDLE token = NULL;
6969 SID_NAME_USE user_type;
6970 unsigned char *buf = NULL;
6971 DWORD blen = 0;
6972 TOKEN_USER user_token;
6973 TOKEN_PRIMARY_GROUP group_token;
6974 unsigned euid;
6975 unsigned egid;
6976 PROCESS_MEMORY_COUNTERS mem;
6977 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6978 SIZE_T minrss, maxrss;
6979 MEMORYSTATUS memst;
6980 MEMORY_STATUS_EX memstex;
6981 double totphys = 0.0;
6982 Lisp_Object ctime, stime, utime, etime, ttime;
6983 double pcpu;
6984 BOOL result = FALSE;
6986 CHECK_NUMBER_OR_FLOAT (pid);
6987 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6989 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6991 if (h_snapshot != INVALID_HANDLE_VALUE)
6993 PROCESSENTRY32 pe;
6994 BOOL res;
6996 pe.dwSize = sizeof (PROCESSENTRY32);
6997 for (res = process32_first (h_snapshot, &pe); res;
6998 res = process32_next (h_snapshot, &pe))
7000 if (proc_id == pe.th32ProcessID)
7002 if (proc_id == 0)
7003 decoded_cmd = build_string ("Idle");
7004 else
7006 /* Decode the command name from locale-specific
7007 encoding. */
7008 cmd_str = build_unibyte_string (pe.szExeFile);
7010 decoded_cmd =
7011 code_convert_string_norecord (cmd_str,
7012 Vlocale_coding_system, 0);
7014 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
7015 attrs = Fcons (Fcons (Qppid,
7016 make_fixnum_or_float (pe.th32ParentProcessID)),
7017 attrs);
7018 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
7019 attrs);
7020 attrs = Fcons (Fcons (Qthcount,
7021 make_fixnum_or_float (pe.cntThreads)),
7022 attrs);
7023 found_proc = 1;
7024 break;
7028 CloseHandle (h_snapshot);
7031 if (!found_proc)
7032 return Qnil;
7034 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7035 FALSE, proc_id);
7036 /* If we were denied a handle to the process, try again after
7037 enabling the SeDebugPrivilege in our process. */
7038 if (!h_proc)
7040 TOKEN_PRIVILEGES priv_current;
7042 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
7044 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7045 FALSE, proc_id);
7046 restore_privilege (&priv_current);
7047 revert_to_self ();
7050 if (h_proc)
7052 result = open_process_token (h_proc, TOKEN_QUERY, &token);
7053 if (result)
7055 result = get_token_information (token, TokenUser, NULL, 0, &blen);
7056 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7058 buf = xmalloc (blen);
7059 result = get_token_information (token, TokenUser,
7060 (LPVOID)buf, blen, &needed);
7061 if (result)
7063 memcpy (&user_token, buf, sizeof (user_token));
7064 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
7066 euid = get_rid (user_token.User.Sid);
7067 result = lookup_account_sid (NULL, user_token.User.Sid,
7068 uname, &ulength,
7069 domain, &dlength,
7070 &user_type);
7071 if (result)
7072 w32_add_to_cache (user_token.User.Sid, euid, uname);
7073 else
7075 strcpy (uname, "unknown");
7076 result = TRUE;
7079 ulength = strlen (uname);
7083 if (result)
7085 /* Determine a reasonable euid and gid values. */
7086 if (xstrcasecmp ("administrator", uname) == 0)
7088 euid = 500; /* well-known Administrator uid */
7089 egid = 513; /* well-known None gid */
7091 else
7093 /* Get group id and name. */
7094 result = get_token_information (token, TokenPrimaryGroup,
7095 (LPVOID)buf, blen, &needed);
7096 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7098 buf = xrealloc (buf, blen = needed);
7099 result = get_token_information (token, TokenPrimaryGroup,
7100 (LPVOID)buf, blen, &needed);
7102 if (result)
7104 memcpy (&group_token, buf, sizeof (group_token));
7105 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7107 egid = get_rid (group_token.PrimaryGroup);
7108 dlength = sizeof (domain);
7109 result =
7110 lookup_account_sid (NULL, group_token.PrimaryGroup,
7111 gname, &glength, NULL, &dlength,
7112 &user_type);
7113 if (result)
7114 w32_add_to_cache (group_token.PrimaryGroup,
7115 egid, gname);
7116 else
7118 strcpy (gname, "None");
7119 result = TRUE;
7122 glength = strlen (gname);
7126 xfree (buf);
7128 if (!result)
7130 if (!is_windows_9x ())
7132 /* We couldn't open the process token, presumably because of
7133 insufficient access rights. Assume this process is run
7134 by the system. */
7135 strcpy (uname, "SYSTEM");
7136 strcpy (gname, "None");
7137 euid = 18; /* SYSTEM */
7138 egid = 513; /* None */
7139 glength = strlen (gname);
7140 ulength = strlen (uname);
7142 /* If we are running under Windows 9X, where security calls are
7143 not supported, we assume all processes are run by the current
7144 user. */
7145 else if (GetUserName (uname, &ulength))
7147 if (xstrcasecmp ("administrator", uname) == 0)
7148 euid = 0;
7149 else
7150 euid = 123;
7151 egid = euid;
7152 strcpy (gname, "None");
7153 glength = strlen (gname);
7154 ulength = strlen (uname);
7156 else
7158 euid = 123;
7159 egid = 123;
7160 strcpy (uname, "administrator");
7161 ulength = strlen (uname);
7162 strcpy (gname, "None");
7163 glength = strlen (gname);
7165 if (token)
7166 CloseHandle (token);
7169 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7170 tem = make_unibyte_string (uname, ulength);
7171 attrs = Fcons (Fcons (Quser,
7172 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7173 attrs);
7174 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7175 tem = make_unibyte_string (gname, glength);
7176 attrs = Fcons (Fcons (Qgroup,
7177 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7178 attrs);
7180 if (global_memory_status_ex (&memstex))
7181 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7182 totphys = memstex.ullTotalPhys / 1024.0;
7183 #else
7184 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7185 double, so we need to do this for it... */
7187 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7188 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7189 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7191 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7193 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7194 else if (global_memory_status (&memst))
7195 totphys = memst.dwTotalPhys / 1024.0;
7197 if (h_proc
7198 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7199 sizeof (mem_ex)))
7201 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7203 attrs = Fcons (Fcons (Qmajflt,
7204 make_fixnum_or_float (mem_ex.PageFaultCount)),
7205 attrs);
7206 attrs = Fcons (Fcons (Qvsize,
7207 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7208 attrs);
7209 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7210 if (totphys)
7211 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7213 else if (h_proc
7214 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7216 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7218 attrs = Fcons (Fcons (Qmajflt,
7219 make_fixnum_or_float (mem.PageFaultCount)),
7220 attrs);
7221 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7222 if (totphys)
7223 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7225 else if (h_proc
7226 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7228 DWORD rss = maxrss / 1024;
7230 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7231 if (totphys)
7232 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7235 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7237 attrs = Fcons (Fcons (Qutime, utime), attrs);
7238 attrs = Fcons (Fcons (Qstime, stime), attrs);
7239 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7240 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7241 attrs = Fcons (Fcons (Qetime, etime), attrs);
7242 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7245 /* FIXME: Retrieve command line by walking the PEB of the process. */
7247 if (h_proc)
7248 CloseHandle (h_proc);
7249 return attrs;
7253 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7254 unsigned long long *totalswap, unsigned long long *freeswap)
7256 MEMORYSTATUS memst;
7257 MEMORY_STATUS_EX memstex;
7259 /* Use GlobalMemoryStatusEx if available, as it can report more than
7260 2GB of memory. */
7261 if (global_memory_status_ex (&memstex))
7263 *totalram = memstex.ullTotalPhys;
7264 *freeram = memstex.ullAvailPhys;
7265 *totalswap = memstex.ullTotalPageFile;
7266 *freeswap = memstex.ullAvailPageFile;
7267 return 0;
7269 else if (global_memory_status (&memst))
7271 *totalram = memst.dwTotalPhys;
7272 *freeram = memst.dwAvailPhys;
7273 *totalswap = memst.dwTotalPageFile;
7274 *freeswap = memst.dwAvailPageFile;
7275 return 0;
7277 else
7278 return -1;
7282 /* Wrappers for winsock functions to map between our file descriptors
7283 and winsock's handles; also set h_errno for convenience.
7285 To allow Emacs to run on systems which don't have winsock support
7286 installed, we dynamically link to winsock on startup if present, and
7287 otherwise provide the minimum necessary functionality
7288 (eg. gethostname). */
7290 /* function pointers for relevant socket functions */
7291 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7292 void (PASCAL *pfn_WSASetLastError) (int iError);
7293 int (PASCAL *pfn_WSAGetLastError) (void);
7294 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7295 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7296 WSANETWORKEVENTS *NetworkEvents);
7298 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7299 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7300 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7301 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7302 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7303 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7304 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7305 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7306 int (PASCAL *pfn_closesocket) (SOCKET s);
7307 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7308 int (PASCAL *pfn_WSACleanup) (void);
7310 u_short (PASCAL *pfn_htons) (u_short hostshort);
7311 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7312 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7313 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7314 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7315 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7316 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7317 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7318 const char * optval, int optlen);
7319 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7320 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7321 int * namelen);
7322 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7323 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7324 struct sockaddr * from, int * fromlen);
7325 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7326 const struct sockaddr * to, int tolen);
7328 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7329 const struct addrinfo *, struct addrinfo **);
7330 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7332 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7333 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7334 #ifndef HANDLE_FLAG_INHERIT
7335 #define HANDLE_FLAG_INHERIT 1
7336 #endif
7338 HANDLE winsock_lib;
7339 static int winsock_inuse;
7341 BOOL term_winsock (void);
7343 BOOL
7344 term_winsock (void)
7346 if (winsock_lib != NULL && winsock_inuse == 0)
7348 release_listen_threads ();
7349 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7350 after WSAStartup returns successfully, but it seems reasonable
7351 to allow unloading winsock anyway in that case. */
7352 if (pfn_WSACleanup () == 0 ||
7353 pfn_WSAGetLastError () == WSAENETDOWN)
7355 if (FreeLibrary (winsock_lib))
7356 winsock_lib = NULL;
7357 return TRUE;
7360 return FALSE;
7363 BOOL
7364 init_winsock (int load_now)
7366 WSADATA winsockData;
7368 if (winsock_lib != NULL)
7369 return TRUE;
7371 pfn_SetHandleInformation
7372 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7373 "SetHandleInformation");
7375 winsock_lib = LoadLibrary ("Ws2_32.dll");
7377 if (winsock_lib != NULL)
7379 /* dynamically link to socket functions */
7381 #define LOAD_PROC(fn) \
7382 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7383 goto fail;
7385 LOAD_PROC (WSAStartup);
7386 LOAD_PROC (WSASetLastError);
7387 LOAD_PROC (WSAGetLastError);
7388 LOAD_PROC (WSAEventSelect);
7389 LOAD_PROC (WSAEnumNetworkEvents);
7390 LOAD_PROC (WSACreateEvent);
7391 LOAD_PROC (WSACloseEvent);
7392 LOAD_PROC (socket);
7393 LOAD_PROC (bind);
7394 LOAD_PROC (connect);
7395 LOAD_PROC (ioctlsocket);
7396 LOAD_PROC (recv);
7397 LOAD_PROC (send);
7398 LOAD_PROC (closesocket);
7399 LOAD_PROC (shutdown);
7400 LOAD_PROC (htons);
7401 LOAD_PROC (ntohs);
7402 LOAD_PROC (inet_addr);
7403 LOAD_PROC (gethostname);
7404 LOAD_PROC (gethostbyname);
7405 LOAD_PROC (getservbyname);
7406 LOAD_PROC (getpeername);
7407 LOAD_PROC (WSACleanup);
7408 LOAD_PROC (setsockopt);
7409 LOAD_PROC (listen);
7410 LOAD_PROC (getsockname);
7411 LOAD_PROC (accept);
7412 LOAD_PROC (recvfrom);
7413 LOAD_PROC (sendto);
7414 #undef LOAD_PROC
7416 /* Try loading functions not available before XP. */
7417 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7418 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7419 /* Paranoia: these two functions should go together, so if one
7420 is absent, we cannot use the other. */
7421 if (pfn_getaddrinfo == NULL)
7422 pfn_freeaddrinfo = NULL;
7423 else if (pfn_freeaddrinfo == NULL)
7424 pfn_getaddrinfo = NULL;
7426 /* specify version 1.1 of winsock */
7427 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7429 if (winsockData.wVersion != 0x101)
7430 goto fail;
7432 if (!load_now)
7434 /* Report that winsock exists and is usable, but leave
7435 socket functions disabled. I am assuming that calling
7436 WSAStartup does not require any network interaction,
7437 and in particular does not cause or require a dial-up
7438 connection to be established. */
7440 pfn_WSACleanup ();
7441 FreeLibrary (winsock_lib);
7442 winsock_lib = NULL;
7444 winsock_inuse = 0;
7445 return TRUE;
7448 fail:
7449 FreeLibrary (winsock_lib);
7450 winsock_lib = NULL;
7453 return FALSE;
7457 int h_errno = 0;
7459 /* Function to map winsock error codes to errno codes for those errno
7460 code defined in errno.h (errno values not defined by errno.h are
7461 already in nt/inc/sys/socket.h). */
7462 static void
7463 set_errno (void)
7465 int wsa_err;
7467 h_errno = 0;
7468 if (winsock_lib == NULL)
7469 wsa_err = EINVAL;
7470 else
7471 wsa_err = pfn_WSAGetLastError ();
7473 switch (wsa_err)
7475 case WSAEACCES: errno = EACCES; break;
7476 case WSAEBADF: errno = EBADF; break;
7477 case WSAEFAULT: errno = EFAULT; break;
7478 case WSAEINTR: errno = EINTR; break;
7479 case WSAEINVAL: errno = EINVAL; break;
7480 case WSAEMFILE: errno = EMFILE; break;
7481 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7482 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7483 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7484 case WSAENOTCONN: errno = ENOTCONN; break;
7485 default: errno = wsa_err; break;
7489 static void
7490 check_errno (void)
7492 h_errno = 0;
7493 if (winsock_lib != NULL)
7494 pfn_WSASetLastError (0);
7497 /* Extend strerror to handle the winsock-specific error codes. */
7498 struct {
7499 int errnum;
7500 const char * msg;
7501 } _wsa_errlist[] = {
7502 {WSAEINTR , "Interrupted function call"},
7503 {WSAEBADF , "Bad file descriptor"},
7504 {WSAEACCES , "Permission denied"},
7505 {WSAEFAULT , "Bad address"},
7506 {WSAEINVAL , "Invalid argument"},
7507 {WSAEMFILE , "Too many open files"},
7509 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7510 {WSAEINPROGRESS , "Operation now in progress"},
7511 {WSAEALREADY , "Operation already in progress"},
7512 {WSAENOTSOCK , "Socket operation on non-socket"},
7513 {WSAEDESTADDRREQ , "Destination address required"},
7514 {WSAEMSGSIZE , "Message too long"},
7515 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7516 {WSAENOPROTOOPT , "Bad protocol option"},
7517 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7518 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7519 {WSAEOPNOTSUPP , "Operation not supported"},
7520 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7521 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7522 {WSAEADDRINUSE , "Address already in use"},
7523 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7524 {WSAENETDOWN , "Network is down"},
7525 {WSAENETUNREACH , "Network is unreachable"},
7526 {WSAENETRESET , "Network dropped connection on reset"},
7527 {WSAECONNABORTED , "Software caused connection abort"},
7528 {WSAECONNRESET , "Connection reset by peer"},
7529 {WSAENOBUFS , "No buffer space available"},
7530 {WSAEISCONN , "Socket is already connected"},
7531 {WSAENOTCONN , "Socket is not connected"},
7532 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7533 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7534 {WSAETIMEDOUT , "Connection timed out"},
7535 {WSAECONNREFUSED , "Connection refused"},
7536 {WSAELOOP , "Network loop"}, /* not sure */
7537 {WSAENAMETOOLONG , "Name is too long"},
7538 {WSAEHOSTDOWN , "Host is down"},
7539 {WSAEHOSTUNREACH , "No route to host"},
7540 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7541 {WSAEPROCLIM , "Too many processes"},
7542 {WSAEUSERS , "Too many users"}, /* not sure */
7543 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7544 {WSAESTALE , "Data is stale"}, /* not sure */
7545 {WSAEREMOTE , "Remote error"}, /* not sure */
7547 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7548 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7549 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7550 {WSAEDISCON , "Graceful shutdown in progress"},
7551 #ifdef WSAENOMORE
7552 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7553 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7554 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7555 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7556 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7557 {WSASYSCALLFAILURE , "System call failure"},
7558 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7559 {WSATYPE_NOT_FOUND , "Class type not found"},
7560 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7561 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7562 {WSAEREFUSED , "Operation refused"}, /* not sure */
7563 #endif
7565 {WSAHOST_NOT_FOUND , "Host not found"},
7566 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7567 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7568 {WSANO_DATA , "Valid name, no data record of requested type"},
7570 {-1, NULL}
7573 char *
7574 sys_strerror (int error_no)
7576 int i;
7577 static char unknown_msg[40];
7579 if (error_no >= 0 && error_no < sys_nerr)
7580 return sys_errlist[error_no];
7582 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7583 if (_wsa_errlist[i].errnum == error_no)
7584 return (char *)_wsa_errlist[i].msg;
7586 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7587 return unknown_msg;
7590 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7591 but I believe the method of keeping the socket handle separate (and
7592 insuring it is not inheritable) is the correct one. */
7594 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7596 static int socket_to_fd (SOCKET s);
7599 sys_socket (int af, int type, int protocol)
7601 SOCKET s;
7603 if (winsock_lib == NULL)
7605 errno = ENETDOWN;
7606 return -1;
7609 check_errno ();
7611 /* call the real socket function */
7612 s = pfn_socket (af, type, protocol);
7614 if (s != INVALID_SOCKET)
7615 return socket_to_fd (s);
7617 set_errno ();
7618 return -1;
7621 /* Convert a SOCKET to a file descriptor. */
7622 static int
7623 socket_to_fd (SOCKET s)
7625 int fd;
7626 child_process * cp;
7628 /* Although under NT 3.5 _open_osfhandle will accept a socket
7629 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7630 that does not work under NT 3.1. However, we can get the same
7631 effect by using a backdoor function to replace an existing
7632 descriptor handle with the one we want. */
7634 /* allocate a file descriptor (with appropriate flags) */
7635 fd = _open ("NUL:", _O_RDWR);
7636 if (fd >= 0)
7638 /* Make a non-inheritable copy of the socket handle. Note
7639 that it is possible that sockets aren't actually kernel
7640 handles, which appears to be the case on Windows 9x when
7641 the MS Proxy winsock client is installed. */
7643 /* Apparently there is a bug in NT 3.51 with some service
7644 packs, which prevents using DuplicateHandle to make a
7645 socket handle non-inheritable (causes WSACleanup to
7646 hang). The work-around is to use SetHandleInformation
7647 instead if it is available and implemented. */
7648 if (pfn_SetHandleInformation)
7650 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7652 else
7654 HANDLE parent = GetCurrentProcess ();
7655 HANDLE new_s = INVALID_HANDLE_VALUE;
7657 if (DuplicateHandle (parent,
7658 (HANDLE) s,
7659 parent,
7660 &new_s,
7662 FALSE,
7663 DUPLICATE_SAME_ACCESS))
7665 /* It is possible that DuplicateHandle succeeds even
7666 though the socket wasn't really a kernel handle,
7667 because a real handle has the same value. So
7668 test whether the new handle really is a socket. */
7669 unsigned long nonblocking = 0;
7670 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7672 pfn_closesocket (s);
7673 s = (SOCKET) new_s;
7675 else
7677 CloseHandle (new_s);
7682 eassert (fd < MAXDESC);
7683 fd_info[fd].hnd = (HANDLE) s;
7685 /* set our own internal flags */
7686 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7688 cp = new_child ();
7689 if (cp)
7691 cp->fd = fd;
7692 cp->status = STATUS_READ_ACKNOWLEDGED;
7694 /* attach child_process to fd_info */
7695 if (fd_info[ fd ].cp != NULL)
7697 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7698 emacs_abort ();
7701 fd_info[ fd ].cp = cp;
7703 /* success! */
7704 winsock_inuse++; /* count open sockets */
7705 return fd;
7708 /* clean up */
7709 _close (fd);
7711 else
7712 pfn_closesocket (s);
7713 errno = EMFILE;
7714 return -1;
7718 sys_bind (int s, const struct sockaddr * addr, int namelen)
7720 if (winsock_lib == NULL)
7722 errno = ENOTSOCK;
7723 return SOCKET_ERROR;
7726 check_errno ();
7727 if (fd_info[s].flags & FILE_SOCKET)
7729 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7730 if (rc == SOCKET_ERROR)
7731 set_errno ();
7732 return rc;
7734 errno = ENOTSOCK;
7735 return SOCKET_ERROR;
7739 sys_connect (int s, const struct sockaddr * name, int namelen)
7741 if (winsock_lib == NULL)
7743 errno = ENOTSOCK;
7744 return SOCKET_ERROR;
7747 check_errno ();
7748 if (fd_info[s].flags & FILE_SOCKET)
7750 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7751 if (rc == SOCKET_ERROR)
7753 set_errno ();
7754 /* If this is a non-blocking 'connect', set the bit in flags
7755 that will tell reader_thread to wait for connection
7756 before trying to read. */
7757 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7759 errno = EINPROGRESS; /* that's what process.c expects */
7760 fd_info[s].flags |= FILE_CONNECT;
7763 return rc;
7765 errno = ENOTSOCK;
7766 return SOCKET_ERROR;
7769 u_short
7770 sys_htons (u_short hostshort)
7772 return (winsock_lib != NULL) ?
7773 pfn_htons (hostshort) : hostshort;
7776 u_short
7777 sys_ntohs (u_short netshort)
7779 return (winsock_lib != NULL) ?
7780 pfn_ntohs (netshort) : netshort;
7783 unsigned long
7784 sys_inet_addr (const char * cp)
7786 return (winsock_lib != NULL) ?
7787 pfn_inet_addr (cp) : INADDR_NONE;
7791 sys_gethostname (char * name, int namelen)
7793 if (winsock_lib != NULL)
7795 int retval;
7797 check_errno ();
7798 retval = pfn_gethostname (name, namelen);
7799 if (retval == SOCKET_ERROR)
7800 set_errno ();
7801 return retval;
7804 if (namelen > MAX_COMPUTERNAME_LENGTH)
7805 return !GetComputerName (name, (DWORD *)&namelen);
7807 errno = EFAULT;
7808 return SOCKET_ERROR;
7811 struct hostent *
7812 sys_gethostbyname (const char * name)
7814 struct hostent * host;
7815 int h_err = h_errno;
7817 if (winsock_lib == NULL)
7819 h_errno = NO_RECOVERY;
7820 errno = ENETDOWN;
7821 return NULL;
7824 check_errno ();
7825 host = pfn_gethostbyname (name);
7826 if (!host)
7828 set_errno ();
7829 h_errno = errno;
7831 else
7832 h_errno = h_err;
7833 return host;
7836 struct servent *
7837 sys_getservbyname (const char * name, const char * proto)
7839 struct servent * serv;
7841 if (winsock_lib == NULL)
7843 errno = ENETDOWN;
7844 return NULL;
7847 check_errno ();
7848 serv = pfn_getservbyname (name, proto);
7849 if (!serv)
7850 set_errno ();
7851 return serv;
7855 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7857 if (winsock_lib == NULL)
7859 errno = ENETDOWN;
7860 return SOCKET_ERROR;
7863 check_errno ();
7864 if (fd_info[s].flags & FILE_SOCKET)
7866 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7867 if (rc == SOCKET_ERROR)
7868 set_errno ();
7869 return rc;
7871 errno = ENOTSOCK;
7872 return SOCKET_ERROR;
7876 sys_getaddrinfo (const char *node, const char *service,
7877 const struct addrinfo *hints, struct addrinfo **res)
7879 int rc;
7881 if (winsock_lib == NULL)
7883 errno = ENETDOWN;
7884 return SOCKET_ERROR;
7887 check_errno ();
7888 if (pfn_getaddrinfo)
7889 rc = pfn_getaddrinfo (node, service, hints, res);
7890 else
7892 int port = 0;
7893 struct hostent *host_info;
7894 struct gai_storage {
7895 struct addrinfo addrinfo;
7896 struct sockaddr_in sockaddr_in;
7897 } *gai_storage;
7899 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7900 if (hints && hints->ai_flags != 0)
7901 return WSAEINVAL;
7902 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7903 if (!node)
7904 return WSAHOST_NOT_FOUND;
7906 if (service)
7908 const char *protocol =
7909 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7910 struct servent *srv = sys_getservbyname (service, protocol);
7912 if (srv)
7913 port = srv->s_port;
7914 else if (*service >= '0' && *service <= '9')
7916 char *endp;
7918 port = strtoul (service, &endp, 10);
7919 if (*endp || port > 65536)
7920 return WSAHOST_NOT_FOUND;
7921 port = sys_htons ((unsigned short) port);
7923 else
7924 return WSAHOST_NOT_FOUND;
7927 gai_storage = xzalloc (sizeof *gai_storage);
7928 gai_storage->sockaddr_in.sin_port = port;
7929 host_info = sys_gethostbyname (node);
7930 if (host_info)
7932 memcpy (&gai_storage->sockaddr_in.sin_addr,
7933 host_info->h_addr, host_info->h_length);
7934 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7936 else
7938 /* Attempt to interpret host as numeric inet address. */
7939 unsigned long numeric_addr = sys_inet_addr (node);
7941 if (numeric_addr == -1)
7943 free (gai_storage);
7944 return WSAHOST_NOT_FOUND;
7947 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7948 sizeof (gai_storage->sockaddr_in.sin_addr));
7949 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7952 gai_storage->addrinfo.ai_addr =
7953 (struct sockaddr *)&gai_storage->sockaddr_in;
7954 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7955 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7956 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7957 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7958 gai_storage->addrinfo.ai_next = NULL;
7960 *res = &gai_storage->addrinfo;
7961 rc = 0;
7964 return rc;
7967 void
7968 sys_freeaddrinfo (struct addrinfo *ai)
7970 if (winsock_lib == NULL)
7972 errno = ENETDOWN;
7973 return;
7976 check_errno ();
7977 if (pfn_freeaddrinfo)
7978 pfn_freeaddrinfo (ai);
7979 else
7981 eassert (ai->ai_next == NULL);
7982 xfree (ai);
7987 sys_shutdown (int s, int how)
7989 if (winsock_lib == NULL)
7991 errno = ENETDOWN;
7992 return SOCKET_ERROR;
7995 check_errno ();
7996 if (fd_info[s].flags & FILE_SOCKET)
7998 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7999 if (rc == SOCKET_ERROR)
8000 set_errno ();
8001 return rc;
8003 errno = ENOTSOCK;
8004 return SOCKET_ERROR;
8008 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
8010 if (winsock_lib == NULL)
8012 errno = ENETDOWN;
8013 return SOCKET_ERROR;
8016 check_errno ();
8017 if (fd_info[s].flags & FILE_SOCKET)
8019 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
8020 (const char *)optval, optlen);
8021 if (rc == SOCKET_ERROR)
8022 set_errno ();
8023 return rc;
8025 errno = ENOTSOCK;
8026 return SOCKET_ERROR;
8030 sys_listen (int s, int backlog)
8032 if (winsock_lib == NULL)
8034 errno = ENETDOWN;
8035 return SOCKET_ERROR;
8038 check_errno ();
8039 if (fd_info[s].flags & FILE_SOCKET)
8041 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
8042 if (rc == SOCKET_ERROR)
8043 set_errno ();
8044 else
8045 fd_info[s].flags |= FILE_LISTEN;
8046 return rc;
8048 errno = ENOTSOCK;
8049 return SOCKET_ERROR;
8053 sys_getsockname (int s, struct sockaddr * name, int * namelen)
8055 if (winsock_lib == NULL)
8057 errno = ENETDOWN;
8058 return SOCKET_ERROR;
8061 check_errno ();
8062 if (fd_info[s].flags & FILE_SOCKET)
8064 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
8065 if (rc == SOCKET_ERROR)
8066 set_errno ();
8067 return rc;
8069 errno = ENOTSOCK;
8070 return SOCKET_ERROR;
8074 sys_accept (int s, struct sockaddr * addr, int * addrlen)
8076 if (winsock_lib == NULL)
8078 errno = ENETDOWN;
8079 return -1;
8082 check_errno ();
8083 if (fd_info[s].flags & FILE_LISTEN)
8085 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
8086 int fd = -1;
8087 if (t == INVALID_SOCKET)
8088 set_errno ();
8089 else
8090 fd = socket_to_fd (t);
8092 if (fd >= 0)
8094 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
8095 ResetEvent (fd_info[s].cp->char_avail);
8097 return fd;
8099 errno = ENOTSOCK;
8100 return -1;
8104 sys_recvfrom (int s, char * buf, int len, int flags,
8105 struct sockaddr * from, int * fromlen)
8107 if (winsock_lib == NULL)
8109 errno = ENETDOWN;
8110 return SOCKET_ERROR;
8113 check_errno ();
8114 if (fd_info[s].flags & FILE_SOCKET)
8116 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8117 if (rc == SOCKET_ERROR)
8118 set_errno ();
8119 return rc;
8121 errno = ENOTSOCK;
8122 return SOCKET_ERROR;
8126 sys_sendto (int s, const char * buf, int len, int flags,
8127 const struct sockaddr * to, int tolen)
8129 if (winsock_lib == NULL)
8131 errno = ENETDOWN;
8132 return SOCKET_ERROR;
8135 check_errno ();
8136 if (fd_info[s].flags & FILE_SOCKET)
8138 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8139 if (rc == SOCKET_ERROR)
8140 set_errno ();
8141 return rc;
8143 errno = ENOTSOCK;
8144 return SOCKET_ERROR;
8147 /* Windows does not have an fcntl function. Provide an implementation
8148 good enough for Emacs. */
8150 fcntl (int s, int cmd, int options)
8152 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8153 invoked in a context where fd1 is closed and all descriptors less
8154 than fd1 are open, so sys_dup is an adequate implementation. */
8155 if (cmd == F_DUPFD_CLOEXEC)
8156 return sys_dup (s);
8158 check_errno ();
8159 if (fd_info[s].flags & FILE_SOCKET)
8161 if (winsock_lib == NULL)
8163 errno = ENETDOWN;
8164 return -1;
8167 if (cmd == F_SETFL && options == O_NONBLOCK)
8169 unsigned long nblock = 1;
8170 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8171 if (rc == SOCKET_ERROR)
8172 set_errno ();
8173 /* Keep track of the fact that we set this to non-blocking. */
8174 fd_info[s].flags |= FILE_NDELAY;
8175 return rc;
8177 else
8179 errno = EINVAL;
8180 return SOCKET_ERROR;
8183 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8184 == (FILE_PIPE | FILE_WRITE))
8186 /* Force our writes to pipes be non-blocking. */
8187 if (cmd == F_SETFL && options == O_NONBLOCK)
8189 HANDLE h = (HANDLE)_get_osfhandle (s);
8190 DWORD pipe_mode = PIPE_NOWAIT;
8192 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8194 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8195 return SOCKET_ERROR;
8197 fd_info[s].flags |= FILE_NDELAY;
8198 return 0;
8200 else
8202 errno = EINVAL;
8203 return SOCKET_ERROR;
8206 errno = ENOTSOCK;
8207 return SOCKET_ERROR;
8211 /* Shadow main io functions: we need to handle pipes and sockets more
8212 intelligently. */
8215 sys_close (int fd)
8217 int rc;
8219 if (fd < 0)
8221 errno = EBADF;
8222 return -1;
8225 if (fd < MAXDESC && fd_info[fd].cp)
8227 child_process * cp = fd_info[fd].cp;
8229 fd_info[fd].cp = NULL;
8231 if (CHILD_ACTIVE (cp))
8233 /* if last descriptor to active child_process then cleanup */
8234 int i;
8235 for (i = 0; i < MAXDESC; i++)
8237 if (i == fd)
8238 continue;
8239 if (fd_info[i].cp == cp)
8240 break;
8242 if (i == MAXDESC)
8244 if (fd_info[fd].flags & FILE_SOCKET)
8246 if (winsock_lib == NULL) emacs_abort ();
8248 pfn_shutdown (SOCK_HANDLE (fd), 2);
8249 rc = pfn_closesocket (SOCK_HANDLE (fd));
8251 winsock_inuse--; /* count open sockets */
8253 /* If the process handle is NULL, it's either a socket
8254 or serial connection, or a subprocess that was
8255 already reaped by reap_subprocess, but whose
8256 resources were not yet freed, because its output was
8257 not fully read yet by the time it was reaped. (This
8258 usually happens with async subprocesses whose output
8259 is being read by Emacs.) Otherwise, this process was
8260 not reaped yet, so we set its FD to a negative value
8261 to make sure sys_select will eventually get to
8262 calling the SIGCHLD handler for it, which will then
8263 invoke waitpid and reap_subprocess. */
8264 if (cp->procinfo.hProcess == NULL)
8265 delete_child (cp);
8266 else
8267 cp->fd = -1;
8272 if (fd >= 0 && fd < MAXDESC)
8273 fd_info[fd].flags = 0;
8275 /* Note that sockets do not need special treatment here (at least on
8276 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8277 closesocket is equivalent to CloseHandle, which is to be expected
8278 because socket handles are fully fledged kernel handles. */
8279 rc = _close (fd);
8281 return rc;
8285 sys_dup (int fd)
8287 int new_fd;
8289 new_fd = _dup (fd);
8290 if (new_fd >= 0 && new_fd < MAXDESC)
8292 /* duplicate our internal info as well */
8293 fd_info[new_fd] = fd_info[fd];
8295 return new_fd;
8299 sys_dup2 (int src, int dst)
8301 int rc;
8303 if (dst < 0 || dst >= MAXDESC)
8305 errno = EBADF;
8306 return -1;
8309 /* MS _dup2 seems to have weird side effect when invoked with 2
8310 identical arguments: an attempt to fclose the corresponding stdio
8311 stream after that hangs (we do close standard streams in
8312 init_ntproc). Attempt to avoid that by not calling _dup2 that
8313 way: if SRC is valid, we know that dup2 should be a no-op, so do
8314 nothing and return DST. */
8315 if (src == dst)
8317 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8319 errno = EBADF;
8320 return -1;
8322 return dst;
8325 /* Make sure we close the destination first if it's a pipe or socket. */
8326 if (fd_info[dst].flags != 0)
8327 sys_close (dst);
8329 rc = _dup2 (src, dst);
8330 if (rc == 0)
8332 /* Duplicate our internal info as well. */
8333 fd_info[dst] = fd_info[src];
8335 return rc == 0 ? dst : rc;
8339 pipe2 (int * phandles, int pipe2_flags)
8341 int rc;
8342 unsigned flags;
8343 unsigned pipe_size = 0;
8345 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8347 /* Allow Lisp to override the default buffer size of the pipe. */
8348 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8349 pipe_size = w32_pipe_buffer_size;
8351 /* make pipe handles non-inheritable; when we spawn a child, we
8352 replace the relevant handle with an inheritable one. Also put
8353 pipes into binary mode; we will do text mode translation ourselves
8354 if required. */
8355 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8357 if (rc == 0)
8359 /* Protect against overflow, since Windows can open more handles than
8360 our fd_info array has room for. */
8361 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8363 _close (phandles[0]);
8364 _close (phandles[1]);
8365 errno = EMFILE;
8366 rc = -1;
8368 else
8370 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8371 fd_info[phandles[0]].flags = flags;
8373 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8374 fd_info[phandles[1]].flags = flags;
8378 return rc;
8381 /* Function to do blocking read of one byte, needed to implement
8382 select. It is only allowed on communication ports, sockets, or
8383 pipes. */
8385 _sys_read_ahead (int fd)
8387 child_process * cp;
8388 int rc;
8390 if (fd < 0 || fd >= MAXDESC)
8391 return STATUS_READ_ERROR;
8393 cp = fd_info[fd].cp;
8395 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8396 return STATUS_READ_ERROR;
8398 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8399 || (fd_info[fd].flags & FILE_READ) == 0)
8401 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8402 emacs_abort ();
8405 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8406 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8407 cp->status = STATUS_READ_IN_PROGRESS;
8409 if (fd_info[fd].flags & FILE_PIPE)
8411 rc = _read (fd, &cp->chr, sizeof (char));
8413 /* Give subprocess time to buffer some more output for us before
8414 reporting that input is available; we need this because Windows 95
8415 connects DOS programs to pipes by making the pipe appear to be
8416 the normal console stdout - as a result most DOS programs will
8417 write to stdout without buffering, ie. one character at a
8418 time. Even some W32 programs do this - "dir" in a command
8419 shell on NT is very slow if we don't do this. */
8420 if (rc > 0)
8422 int wait = w32_pipe_read_delay;
8424 if (wait > 0)
8425 Sleep (wait);
8426 else if (wait < 0)
8427 while (++wait <= 0)
8428 /* Yield remainder of our time slice, effectively giving a
8429 temporary priority boost to the child process. */
8430 Sleep (0);
8433 else if (fd_info[fd].flags & FILE_SERIAL)
8435 HANDLE hnd = fd_info[fd].hnd;
8436 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8437 COMMTIMEOUTS ct;
8439 /* Configure timeouts for blocking read. */
8440 if (!GetCommTimeouts (hnd, &ct))
8442 cp->status = STATUS_READ_ERROR;
8443 return STATUS_READ_ERROR;
8445 ct.ReadIntervalTimeout = 0;
8446 ct.ReadTotalTimeoutMultiplier = 0;
8447 ct.ReadTotalTimeoutConstant = 0;
8448 if (!SetCommTimeouts (hnd, &ct))
8450 cp->status = STATUS_READ_ERROR;
8451 return STATUS_READ_ERROR;
8454 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8456 if (GetLastError () != ERROR_IO_PENDING)
8458 cp->status = STATUS_READ_ERROR;
8459 return STATUS_READ_ERROR;
8461 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8463 cp->status = STATUS_READ_ERROR;
8464 return STATUS_READ_ERROR;
8468 else if (fd_info[fd].flags & FILE_SOCKET)
8470 unsigned long nblock = 0;
8471 /* We always want this to block, so temporarily disable NDELAY. */
8472 if (fd_info[fd].flags & FILE_NDELAY)
8473 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8475 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8477 if (fd_info[fd].flags & FILE_NDELAY)
8479 nblock = 1;
8480 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8484 if (rc == sizeof (char))
8485 cp->status = STATUS_READ_SUCCEEDED;
8486 else
8487 cp->status = STATUS_READ_FAILED;
8489 return cp->status;
8493 _sys_wait_accept (int fd)
8495 HANDLE hEv;
8496 child_process * cp;
8497 int rc;
8499 if (fd < 0 || fd >= MAXDESC)
8500 return STATUS_READ_ERROR;
8502 cp = fd_info[fd].cp;
8504 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8505 return STATUS_READ_ERROR;
8507 cp->status = STATUS_READ_FAILED;
8509 hEv = pfn_WSACreateEvent ();
8510 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8511 if (rc != SOCKET_ERROR)
8513 do {
8514 rc = WaitForSingleObject (hEv, 500);
8515 Sleep (5);
8516 } while (rc == WAIT_TIMEOUT
8517 && cp->status != STATUS_READ_ERROR
8518 && cp->char_avail);
8519 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8520 if (rc == WAIT_OBJECT_0)
8521 cp->status = STATUS_READ_SUCCEEDED;
8523 pfn_WSACloseEvent (hEv);
8525 return cp->status;
8529 _sys_wait_connect (int fd)
8531 HANDLE hEv;
8532 child_process * cp;
8533 int rc;
8535 if (fd < 0 || fd >= MAXDESC)
8536 return STATUS_READ_ERROR;
8538 cp = fd_info[fd].cp;
8539 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8540 return STATUS_READ_ERROR;
8542 cp->status = STATUS_READ_FAILED;
8544 hEv = pfn_WSACreateEvent ();
8545 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8546 if (rc != SOCKET_ERROR)
8548 do {
8549 rc = WaitForSingleObject (hEv, 500);
8550 Sleep (5);
8551 } while (rc == WAIT_TIMEOUT
8552 && cp->status != STATUS_READ_ERROR
8553 && cp->char_avail);
8554 if (rc == WAIT_OBJECT_0)
8556 /* We've got an event, but it could be a successful
8557 connection, or it could be a failure. Find out
8558 which one is it. */
8559 WSANETWORKEVENTS events;
8561 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8562 if ((events.lNetworkEvents & FD_CONNECT) != 0
8563 && events.iErrorCode[FD_CONNECT_BIT])
8565 cp->status = STATUS_CONNECT_FAILED;
8566 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8568 else
8570 cp->status = STATUS_READ_SUCCEEDED;
8571 cp->errcode = 0;
8574 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8576 else
8577 pfn_WSACloseEvent (hEv);
8579 return cp->status;
8583 sys_read (int fd, char * buffer, unsigned int count)
8585 int nchars;
8586 int to_read;
8587 DWORD waiting;
8588 char * orig_buffer = buffer;
8590 if (fd < 0)
8592 errno = EBADF;
8593 return -1;
8596 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8598 child_process *cp = fd_info[fd].cp;
8600 if ((fd_info[fd].flags & FILE_READ) == 0)
8602 errno = EBADF;
8603 return -1;
8606 nchars = 0;
8608 /* re-read CR carried over from last read */
8609 if (fd_info[fd].flags & FILE_LAST_CR)
8611 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8612 *buffer++ = 0x0d;
8613 count--;
8614 nchars++;
8615 fd_info[fd].flags &= ~FILE_LAST_CR;
8618 /* presence of a child_process structure means we are operating in
8619 non-blocking mode - otherwise we just call _read directly.
8620 Note that the child_process structure might be missing because
8621 reap_subprocess has been called; in this case the pipe is
8622 already broken, so calling _read on it is okay. */
8623 if (cp)
8625 int current_status = cp->status;
8627 switch (current_status)
8629 case STATUS_READ_FAILED:
8630 case STATUS_READ_ERROR:
8631 /* report normal EOF if nothing in buffer */
8632 if (nchars <= 0)
8633 fd_info[fd].flags |= FILE_AT_EOF;
8634 return nchars;
8636 case STATUS_READ_READY:
8637 case STATUS_READ_IN_PROGRESS:
8638 #if 0
8639 /* This happens all the time during GnuTLS handshake
8640 with the remote, evidently because GnuTLS waits for
8641 the read to complete by retrying the read operation
8642 upon EAGAIN. So I'm disabling the DebPrint to avoid
8643 wasting cycles on something that is not a real
8644 problem. Enable if you need to debug something that
8645 bumps into this. */
8646 DebPrint (("sys_read called when read is in progress %d\n",
8647 current_status));
8648 #endif
8649 errno = EWOULDBLOCK;
8650 return -1;
8652 case STATUS_READ_SUCCEEDED:
8653 /* consume read-ahead char */
8654 *buffer++ = cp->chr;
8655 count--;
8656 nchars++;
8657 cp->status = STATUS_READ_ACKNOWLEDGED;
8658 ResetEvent (cp->char_avail);
8660 case STATUS_READ_ACKNOWLEDGED:
8661 case STATUS_CONNECT_FAILED:
8662 break;
8664 default:
8665 DebPrint (("sys_read: bad status %d\n", current_status));
8666 errno = EBADF;
8667 return -1;
8670 if (fd_info[fd].flags & FILE_PIPE)
8672 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8673 to_read = min (waiting, (DWORD) count);
8675 if (to_read > 0)
8676 nchars += _read (fd, buffer, to_read);
8678 else if (fd_info[fd].flags & FILE_SERIAL)
8680 HANDLE hnd = fd_info[fd].hnd;
8681 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8682 int rc = 0;
8683 COMMTIMEOUTS ct;
8685 if (count > 0)
8687 /* Configure timeouts for non-blocking read. */
8688 if (!GetCommTimeouts (hnd, &ct))
8690 errno = EIO;
8691 return -1;
8693 ct.ReadIntervalTimeout = MAXDWORD;
8694 ct.ReadTotalTimeoutMultiplier = 0;
8695 ct.ReadTotalTimeoutConstant = 0;
8696 if (!SetCommTimeouts (hnd, &ct))
8698 errno = EIO;
8699 return -1;
8702 if (!ResetEvent (ovl->hEvent))
8704 errno = EIO;
8705 return -1;
8707 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8709 if (GetLastError () != ERROR_IO_PENDING)
8711 errno = EIO;
8712 return -1;
8714 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8716 errno = EIO;
8717 return -1;
8720 nchars += rc;
8723 else /* FILE_SOCKET */
8725 if (winsock_lib == NULL) emacs_abort ();
8727 /* When a non-blocking 'connect' call fails,
8728 wait_reading_process_output detects this by calling
8729 'getpeername', and then attempts to obtain the connection
8730 error code by trying to read 1 byte from the socket. If
8731 we try to serve that read by calling 'recv' below, the
8732 error we get is a generic WSAENOTCONN, not the actual
8733 connection error. So instead, we use the actual error
8734 code stashed by '_sys_wait_connect' in cp->errcode.
8735 Alternatively, we could have used 'getsockopt', like on
8736 GNU/Linux, but: (a) I have no idea whether the winsock
8737 version could hang, as it does "on some systems" (see the
8738 comment in process.c); and (b) 'getsockopt' on Windows is
8739 documented to clear the socket error for the entire
8740 process, which I'm not sure is TRT; FIXME. */
8741 if (current_status == STATUS_CONNECT_FAILED
8742 && (fd_info[fd].flags & FILE_CONNECT) != 0
8743 && cp->errcode != 0)
8745 pfn_WSASetLastError (cp->errcode);
8746 set_errno ();
8747 return -1;
8749 /* Do the equivalent of a non-blocking read. */
8750 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8751 if (waiting == 0 && nchars == 0)
8753 errno = EWOULDBLOCK;
8754 return -1;
8757 if (waiting)
8759 /* always use binary mode for sockets */
8760 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8761 if (res == SOCKET_ERROR)
8763 set_errno ();
8764 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8765 errno, SOCK_HANDLE (fd)));
8766 return -1;
8768 nchars += res;
8772 else
8774 int nread = _read (fd, buffer, count);
8775 if (nread >= 0)
8776 nchars += nread;
8777 else if (nchars == 0)
8778 nchars = nread;
8781 if (nchars <= 0)
8782 fd_info[fd].flags |= FILE_AT_EOF;
8783 /* Perform text mode translation if required. */
8784 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8786 nchars = crlf_to_lf (nchars, orig_buffer);
8787 /* If buffer contains only CR, return that. To be absolutely
8788 sure we should attempt to read the next char, but in
8789 practice a CR to be followed by LF would not appear by
8790 itself in the buffer. */
8791 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8793 fd_info[fd].flags |= FILE_LAST_CR;
8794 nchars--;
8798 else
8799 nchars = _read (fd, buffer, count);
8801 return nchars;
8804 /* From w32xfns.c */
8805 extern HANDLE interrupt_handle;
8808 sys_write (int fd, const void * buffer, unsigned int count)
8810 int nchars;
8811 USE_SAFE_ALLOCA;
8813 if (fd < 0)
8815 errno = EBADF;
8816 return -1;
8819 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8821 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8823 errno = EBADF;
8824 return -1;
8827 /* Perform text mode translation if required. */
8828 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8830 char * tmpbuf;
8831 const unsigned char * src = buffer;
8832 unsigned char * dst;
8833 int nbytes = count;
8835 SAFE_NALLOCA (tmpbuf, 2, count);
8836 dst = (unsigned char *)tmpbuf;
8838 while (1)
8840 unsigned char *next;
8841 /* Copy next line or remaining bytes. */
8842 next = _memccpy (dst, src, '\n', nbytes);
8843 if (next)
8845 /* Copied one line ending with '\n'. */
8846 int copied = next - dst;
8847 nbytes -= copied;
8848 src += copied;
8849 /* Insert '\r' before '\n'. */
8850 next[-1] = '\r';
8851 next[0] = '\n';
8852 dst = next + 1;
8853 count++;
8855 else
8856 /* Copied remaining partial line -> now finished. */
8857 break;
8859 buffer = tmpbuf;
8863 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8865 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8866 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8867 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8868 DWORD active = 0;
8870 /* This is async (a.k.a. "overlapped") I/O, so the return value
8871 of FALSE from WriteFile means either an error or the output
8872 will be completed asynchronously (ERROR_IO_PENDING). */
8873 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8875 if (GetLastError () != ERROR_IO_PENDING)
8877 errno = EIO;
8878 nchars = -1;
8880 else
8882 /* Wait for the write to complete, and watch C-g while
8883 at that. */
8884 if (detect_input_pending ())
8885 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8886 INFINITE, QS_ALLINPUT);
8887 else
8888 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8889 switch (active)
8891 case WAIT_OBJECT_0:
8892 /* User pressed C-g, cancel write, then leave.
8893 Don't bother cleaning up as we may only get stuck
8894 in buggy drivers. */
8895 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8896 CancelIo (hnd);
8897 errno = EIO; /* Why not EINTR? */
8898 nchars = -1;
8899 break;
8900 case WAIT_OBJECT_0 + 1:
8901 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8903 errno = EIO;
8904 nchars = -1;
8906 break;
8911 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8913 unsigned long nblock = 0;
8914 if (winsock_lib == NULL) emacs_abort ();
8916 child_process *cp = fd_info[fd].cp;
8918 /* If this is a non-blocking socket whose connection is in
8919 progress or terminated with an error already, return the
8920 proper error code to the caller. */
8921 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8923 /* In case connection is in progress, ENOTCONN that would
8924 result from calling pfn_send is not what callers expect. */
8925 if (cp->status != STATUS_CONNECT_FAILED)
8927 errno = EWOULDBLOCK;
8928 return -1;
8930 /* In case connection failed, use the actual error code
8931 stashed by '_sys_wait_connect' in cp->errcode. */
8932 else if (cp->errcode != 0)
8934 pfn_WSASetLastError (cp->errcode);
8935 set_errno ();
8936 return -1;
8940 /* TODO: implement select() properly so non-blocking I/O works. */
8941 /* For now, make sure the write blocks. */
8942 if (fd_info[fd].flags & FILE_NDELAY)
8943 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8945 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8947 if (nchars == SOCKET_ERROR)
8949 set_errno ();
8950 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8951 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8954 /* Set the socket back to non-blocking if it was before,
8955 for other operations that support it. */
8956 if (fd_info[fd].flags & FILE_NDELAY)
8958 nblock = 1;
8959 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8962 else
8964 /* Some networked filesystems don't like too large writes, so
8965 break them into smaller chunks. See the Comments section of
8966 the MSDN documentation of WriteFile for details behind the
8967 choice of the value of CHUNK below. See also the thread
8968 http://thread.gmane.org/gmane.comp.version-control.git/145294
8969 in the git mailing list. */
8970 const unsigned char *p = buffer;
8971 const bool is_pipe = (fd < MAXDESC
8972 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8973 == (FILE_PIPE | FILE_NDELAY)));
8974 /* Some programs, notably Node.js's node.exe, seem to never
8975 completely empty the pipe, so writing more than the size of
8976 the pipe's buffer always returns ENOSPC, and we loop forever
8977 between send_process and here. As a workaround, write no
8978 more than the pipe's buffer can hold. */
8979 DWORD pipe_buffer_size;
8980 if (is_pipe)
8982 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8983 NULL, &pipe_buffer_size, NULL, NULL))
8985 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8986 pipe_buffer_size = 4096;
8989 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8991 nchars = 0;
8992 errno = 0;
8993 while (count > 0)
8995 unsigned this_chunk = count < chunk ? count : chunk;
8996 int n = _write (fd, p, this_chunk);
8998 if (n > 0)
8999 nchars += n;
9000 if (n < 0)
9002 /* When there's no buffer space in a pipe that is in the
9003 non-blocking mode, _write returns ENOSPC. We return
9004 EAGAIN instead, which should trigger the logic in
9005 send_process that enters waiting loop and calls
9006 wait_reading_process_output to allow process input to
9007 be accepted during the wait. Those calls to
9008 wait_reading_process_output allow sys_select to
9009 notice when process input becomes available, thus
9010 avoiding deadlock whereby each side of the pipe is
9011 blocked on write, waiting for the other party to read
9012 its end of the pipe. */
9013 if (errno == ENOSPC && is_pipe)
9014 errno = EAGAIN;
9015 if (nchars == 0)
9016 nchars = -1;
9017 break;
9019 else if (n < this_chunk)
9020 break;
9021 count -= n;
9022 p += n;
9026 SAFE_FREE ();
9027 return nchars;
9031 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
9033 /* Return information about network interface IFNAME, or about all
9034 interfaces (if IFNAME is nil). */
9035 static Lisp_Object
9036 network_interface_get_info (Lisp_Object ifname)
9038 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
9039 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
9040 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
9041 Lisp_Object res = Qnil;
9043 if (retval == ERROR_BUFFER_OVERFLOW)
9045 ainfo = xrealloc (ainfo, ainfo_len);
9046 retval = get_adapters_info (ainfo, &ainfo_len);
9049 if (retval == ERROR_SUCCESS)
9051 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
9052 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
9053 int if_num;
9054 struct sockaddr_in sa;
9056 /* For the below, we need some winsock functions, so make sure
9057 the winsock DLL is loaded. If we cannot successfully load
9058 it, they will have no use of the information we provide,
9059 anyway, so punt. */
9060 if (!winsock_lib && !init_winsock (1))
9061 goto done;
9063 for (adapter = ainfo; adapter; adapter = adapter->Next)
9065 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
9066 u_long ip_addr;
9067 /* Present Unix-compatible interface names, instead of the
9068 Windows names, which are really GUIDs not readable by
9069 humans. */
9070 static const char *ifmt[] = {
9071 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
9072 "lo", "ifx%d"
9074 enum {
9075 NONE = -1,
9076 ETHERNET = 0,
9077 TOKENRING = 1,
9078 FDDI = 2,
9079 PPP = 3,
9080 SLIP = 4,
9081 WLAN = 5,
9082 LOOPBACK = 6,
9083 OTHER_IF = 7
9084 } ifmt_idx;
9086 switch (adapter->Type)
9088 case MIB_IF_TYPE_ETHERNET:
9089 /* Windows before Vista reports wireless adapters as
9090 Ethernet. Work around by looking at the Description
9091 string. */
9092 if (strstr (adapter->Description, "Wireless "))
9094 ifmt_idx = WLAN;
9095 if_num = wlan_count++;
9097 else
9099 ifmt_idx = ETHERNET;
9100 if_num = eth_count++;
9102 break;
9103 case MIB_IF_TYPE_TOKENRING:
9104 ifmt_idx = TOKENRING;
9105 if_num = tr_count++;
9106 break;
9107 case MIB_IF_TYPE_FDDI:
9108 ifmt_idx = FDDI;
9109 if_num = fddi_count++;
9110 break;
9111 case MIB_IF_TYPE_PPP:
9112 ifmt_idx = PPP;
9113 if_num = ppp_count++;
9114 break;
9115 case MIB_IF_TYPE_SLIP:
9116 ifmt_idx = SLIP;
9117 if_num = sl_count++;
9118 break;
9119 case IF_TYPE_IEEE80211:
9120 ifmt_idx = WLAN;
9121 if_num = wlan_count++;
9122 break;
9123 case MIB_IF_TYPE_LOOPBACK:
9124 if (lo_count < 0)
9126 ifmt_idx = LOOPBACK;
9127 if_num = lo_count++;
9129 else
9130 ifmt_idx = NONE;
9131 break;
9132 default:
9133 ifmt_idx = OTHER_IF;
9134 if_num = ifx_count++;
9135 break;
9137 if (ifmt_idx == NONE)
9138 continue;
9139 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9141 sa.sin_family = AF_INET;
9142 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9143 if (ip_addr == INADDR_NONE)
9145 /* Bogus address, skip this interface. */
9146 continue;
9148 sa.sin_addr.s_addr = ip_addr;
9149 sa.sin_port = 0;
9150 if (NILP (ifname))
9151 res = Fcons (Fcons (build_string (namebuf),
9152 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9153 sizeof (struct sockaddr))),
9154 res);
9155 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9157 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9158 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9159 Lisp_Object flags = Qnil;
9160 int n;
9161 u_long net_mask;
9163 /* Flags. We guess most of them by type, since the
9164 Windows flags are different and hard to get by. */
9165 flags = Fcons (intern ("up"), flags);
9166 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9168 flags = Fcons (intern ("broadcast"), flags);
9169 flags = Fcons (intern ("multicast"), flags);
9171 flags = Fcons (intern ("running"), flags);
9172 if (ifmt_idx == PPP)
9174 flags = Fcons (intern ("pointopoint"), flags);
9175 flags = Fcons (intern ("noarp"), flags);
9177 if (adapter->HaveWins)
9178 flags = Fcons (intern ("WINS"), flags);
9179 if (adapter->DhcpEnabled)
9180 flags = Fcons (intern ("dynamic"), flags);
9182 res = Fcons (flags, res);
9184 /* Hardware address and its family. */
9185 for (n = 0; n < adapter->AddressLength; n++)
9186 p->contents[n] = make_number ((int) adapter->Address[n]);
9187 /* Windows does not support AF_LINK or AF_PACKET family
9188 of addresses. Use an arbitrary family number that is
9189 identical to what GNU/Linux returns. */
9190 res = Fcons (Fcons (make_number (1), hwaddr), res);
9192 /* Network mask. */
9193 sa.sin_family = AF_INET;
9194 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9195 if (net_mask != INADDR_NONE)
9197 sa.sin_addr.s_addr = net_mask;
9198 sa.sin_port = 0;
9199 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9200 sizeof (struct sockaddr)),
9201 res);
9203 else
9204 res = Fcons (Qnil, res);
9206 sa.sin_family = AF_INET;
9207 if (ip_addr != INADDR_NONE)
9209 /* Broadcast address is only reported by
9210 GetAdaptersAddresses, which is of limited
9211 availability. Generate it on our own. */
9212 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9214 sa.sin_addr.s_addr = bcast_addr;
9215 sa.sin_port = 0;
9216 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9217 sizeof (struct sockaddr)),
9218 res);
9220 /* IP address. */
9221 sa.sin_addr.s_addr = ip_addr;
9222 sa.sin_port = 0;
9223 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9224 sizeof (struct sockaddr)),
9225 res);
9227 else
9228 res = Fcons (Qnil, Fcons (Qnil, res));
9231 /* GetAdaptersInfo is documented to not report loopback
9232 interfaces, so we generate one out of thin air. */
9233 if (!lo_count)
9235 sa.sin_family = AF_INET;
9236 sa.sin_port = 0;
9237 if (NILP (ifname))
9239 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9240 res = Fcons (Fcons (build_string ("lo"),
9241 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9242 sizeof (struct sockaddr))),
9243 res);
9245 else if (strcmp (SSDATA (ifname), "lo") == 0)
9247 res = Fcons (Fcons (intern ("running"),
9248 Fcons (intern ("loopback"),
9249 Fcons (intern ("up"), Qnil))), Qnil);
9250 /* 772 is what 3 different GNU/Linux systems report for
9251 the loopback interface. */
9252 res = Fcons (Fcons (make_number (772),
9253 Fmake_vector (make_number (6),
9254 make_number (0))),
9255 res);
9256 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9257 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9258 sizeof (struct sockaddr)),
9259 res);
9260 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
9261 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9262 sizeof (struct sockaddr)),
9263 res);
9264 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9265 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9266 sizeof (struct sockaddr)),
9267 res);
9273 done:
9274 xfree (ainfo);
9275 return res;
9278 Lisp_Object
9279 network_interface_list (void)
9281 return network_interface_get_info (Qnil);
9284 Lisp_Object
9285 network_interface_info (Lisp_Object ifname)
9287 CHECK_STRING (ifname);
9288 return network_interface_get_info (ifname);
9292 /* The Windows CRT functions are "optimized for speed", so they don't
9293 check for timezone and DST changes if they were last called less
9294 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9295 all Emacs features that repeatedly call time functions (e.g.,
9296 display-time) are in real danger of missing timezone and DST
9297 changes. Calling tzset before each localtime call fixes that. */
9298 struct tm *
9299 sys_localtime (const time_t *t)
9301 tzset ();
9302 return localtime (t);
9307 /* Try loading LIBRARY_ID from the file(s) specified in
9308 Vdynamic_library_alist. If the library is loaded successfully,
9309 return the handle of the DLL, and record the filename in the
9310 property :loaded-from of LIBRARY_ID. If the library could not be
9311 found, or when it was already loaded (because the handle is not
9312 recorded anywhere, and so is lost after use), return NULL.
9314 We could also save the handle in :loaded-from, but currently
9315 there's no use case for it. */
9316 HMODULE
9317 w32_delayed_load (Lisp_Object library_id)
9319 HMODULE dll_handle = NULL;
9321 CHECK_SYMBOL (library_id);
9323 if (CONSP (Vdynamic_library_alist)
9324 && NILP (Fassq (library_id, Vlibrary_cache)))
9326 Lisp_Object found = Qnil;
9327 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9329 if (CONSP (dlls))
9330 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9332 Lisp_Object dll = XCAR (dlls);
9333 char name[MAX_UTF8_PATH];
9334 DWORD res = -1;
9336 CHECK_STRING (dll);
9337 dll = ENCODE_FILE (dll);
9338 if (w32_unicode_filenames)
9340 wchar_t name_w[MAX_PATH];
9342 filename_to_utf16 (SSDATA (dll), name_w);
9343 dll_handle = LoadLibraryW (name_w);
9344 if (dll_handle)
9346 res = GetModuleFileNameW (dll_handle, name_w,
9347 sizeof (name_w));
9348 if (res > 0)
9349 filename_from_utf16 (name_w, name);
9352 else
9354 char name_a[MAX_PATH];
9356 filename_to_ansi (SSDATA (dll), name_a);
9357 dll_handle = LoadLibraryA (name_a);
9358 if (dll_handle)
9360 res = GetModuleFileNameA (dll_handle, name_a,
9361 sizeof (name_a));
9362 if (res > 0)
9363 filename_from_ansi (name_a, name);
9366 if (dll_handle)
9368 ptrdiff_t len = strlen (name);
9369 found = Fcons (dll,
9370 (res > 0)
9371 /* Possibly truncated */
9372 ? make_specified_string (name, -1, len, 1)
9373 : Qnil);
9374 /* This prevents thread start and end notifications
9375 from being sent to the DLL, for every thread we
9376 start. We don't need those notifications because
9377 threads we create never use any of these DLLs, only
9378 the main thread uses them. This is supposed to
9379 speed up thread creation. */
9380 DisableThreadLibraryCalls (dll_handle);
9381 break;
9385 Fput (library_id, QCloaded_from, found);
9388 return dll_handle;
9392 void
9393 check_windows_init_file (void)
9395 /* A common indication that Emacs is not installed properly is when
9396 it cannot find the Windows installation file. If this file does
9397 not exist in the expected place, tell the user. */
9399 if (!noninteractive && !inhibit_window_system
9400 /* Vload_path is not yet initialized when we are loading
9401 loadup.el. */
9402 && NILP (Vpurify_flag))
9404 Lisp_Object init_file;
9405 int fd;
9407 /* Implementation note: this function runs early during Emacs
9408 startup, before startup.el is run. So Vload_path is still in
9409 its initial unibyte form, but it holds UTF-8 encoded file
9410 names, since init_callproc was already called. So we do not
9411 need to ENCODE_FILE here, but we do need to convert the file
9412 names from UTF-8 to ANSI. */
9413 init_file = build_string ("term/w32-win");
9414 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9415 if (fd < 0)
9417 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9418 char *init_file_name = SSDATA (init_file);
9419 char *load_path = SSDATA (load_path_print);
9420 char *buffer = alloca (1024
9421 + strlen (init_file_name)
9422 + strlen (load_path));
9423 char *msg = buffer;
9424 int needed;
9426 sprintf (buffer,
9427 "The Emacs Windows initialization file \"%s.el\" "
9428 "could not be found in your Emacs installation. "
9429 "Emacs checked the following directories for this file:\n"
9430 "\n%s\n\n"
9431 "When Emacs cannot find this file, it usually means that it "
9432 "was not installed properly, or its distribution file was "
9433 "not unpacked properly.\nSee the README.W32 file in the "
9434 "top-level Emacs directory for more information.",
9435 init_file_name, load_path);
9436 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9437 buffer, -1, NULL, 0);
9438 if (needed > 0)
9440 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9442 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9443 -1, msg_w, needed);
9444 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9445 NULL, 0, NULL, NULL);
9446 if (needed > 0)
9448 char *msg_a = alloca (needed + 1);
9450 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9451 NULL, NULL);
9452 msg = msg_a;
9455 MessageBox (NULL,
9456 msg,
9457 "Emacs Abort Dialog",
9458 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9459 /* Use the low-level system abort. */
9460 abort ();
9462 else
9464 _close (fd);
9469 void
9470 term_ntproc (int ignored)
9472 (void)ignored;
9474 term_timers ();
9476 /* shutdown the socket interface if necessary */
9477 term_winsock ();
9479 term_w32select ();
9482 void
9483 init_ntproc (int dumping)
9485 sigset_t initial_mask = 0;
9487 /* Initialize the socket interface now if available and requested by
9488 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9489 delayed until open-network-stream is called (w32-has-winsock can
9490 also be used to dynamically load or reload winsock).
9492 Conveniently, init_environment is called before us, so
9493 PRELOAD_WINSOCK can be set in the registry. */
9495 /* Always initialize this correctly. */
9496 winsock_lib = NULL;
9498 if (getenv ("PRELOAD_WINSOCK") != NULL)
9499 init_winsock (TRUE);
9501 /* Initial preparation for subprocess support: replace our standard
9502 handles with non-inheritable versions. */
9504 HANDLE parent;
9505 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9506 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9507 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9509 parent = GetCurrentProcess ();
9511 /* ignore errors when duplicating and closing; typically the
9512 handles will be invalid when running as a gui program. */
9513 DuplicateHandle (parent,
9514 GetStdHandle (STD_INPUT_HANDLE),
9515 parent,
9516 &stdin_save,
9518 FALSE,
9519 DUPLICATE_SAME_ACCESS);
9521 DuplicateHandle (parent,
9522 GetStdHandle (STD_OUTPUT_HANDLE),
9523 parent,
9524 &stdout_save,
9526 FALSE,
9527 DUPLICATE_SAME_ACCESS);
9529 DuplicateHandle (parent,
9530 GetStdHandle (STD_ERROR_HANDLE),
9531 parent,
9532 &stderr_save,
9534 FALSE,
9535 DUPLICATE_SAME_ACCESS);
9537 fclose (stdin);
9538 fclose (stdout);
9539 fclose (stderr);
9541 if (stdin_save != INVALID_HANDLE_VALUE)
9542 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9543 else
9544 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9545 _fdopen (0, "r");
9547 if (stdout_save != INVALID_HANDLE_VALUE)
9548 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9549 else
9550 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9551 _fdopen (1, "w");
9553 if (stderr_save != INVALID_HANDLE_VALUE)
9554 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9555 else
9556 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9557 _fdopen (2, "w");
9560 /* unfortunately, atexit depends on implementation of malloc */
9561 /* atexit (term_ntproc); */
9562 if (!dumping)
9564 /* Make sure we start with all signals unblocked. */
9565 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9566 signal (SIGABRT, term_ntproc);
9568 init_timers ();
9570 /* determine which drives are fixed, for GetCachedVolumeInformation */
9572 /* GetDriveType must have trailing backslash. */
9573 char drive[] = "A:\\";
9575 /* Loop over all possible drive letters */
9576 while (*drive <= 'Z')
9578 /* Record if this drive letter refers to a fixed drive. */
9579 fixed_drives[DRIVE_INDEX (*drive)] =
9580 (GetDriveType (drive) == DRIVE_FIXED);
9582 (*drive)++;
9585 /* Reset the volume info cache. */
9586 volume_cache = NULL;
9591 shutdown_handler ensures that buffers' autosave files are
9592 up to date when the user logs off, or the system shuts down.
9594 static BOOL WINAPI
9595 shutdown_handler (DWORD type)
9597 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9598 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9599 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9600 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9602 /* Shut down cleanly, making sure autosave files are up to date. */
9603 shut_down_emacs (0, Qnil);
9606 /* Allow other handlers to handle this signal. */
9607 return FALSE;
9610 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9611 NT, return a handle to GDI32.DLL. */
9612 HANDLE
9613 maybe_load_unicows_dll (void)
9615 if (os_subtype == OS_9X)
9617 HANDLE ret = LoadLibrary ("Unicows.dll");
9618 if (ret)
9620 /* These two functions are present on Windows 9X as stubs
9621 that always fail. We need the real implementations from
9622 UNICOWS.DLL, so we must call these functions through
9623 pointers, and assign the correct addresses to these
9624 pointers at program startup (see emacs.c, which calls
9625 this function early on). */
9626 pMultiByteToWideChar =
9627 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9628 pWideCharToMultiByte =
9629 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9630 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9631 return ret;
9633 else
9635 int button;
9637 button = MessageBox (NULL,
9638 "Emacs cannot load the UNICOWS.DLL library.\n"
9639 "This library is essential for using Emacs\n"
9640 "on this system. You need to install it.\n\n"
9641 "Emacs will exit when you click OK.",
9642 "Emacs cannot load UNICOWS.DLL",
9643 MB_ICONERROR | MB_TASKMODAL
9644 | MB_SETFOREGROUND | MB_OK);
9645 switch (button)
9647 case IDOK:
9648 default:
9649 exit (1);
9653 else
9655 /* On NT family of Windows, these two functions are always
9656 linked in, so we just assign their addresses to the 2
9657 pointers; no need for the LoadLibrary dance. */
9658 pMultiByteToWideChar = MultiByteToWideChar;
9659 pWideCharToMultiByte = WideCharToMultiByte;
9660 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9661 if (w32_major_version < 5)
9662 multiByteToWideCharFlags = 0;
9663 else
9664 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9665 return LoadLibrary ("Gdi32.dll");
9670 globals_of_w32 is used to initialize those global variables that
9671 must always be initialized on startup even when the global variable
9672 initialized is non zero (see the function main in emacs.c).
9674 void
9675 globals_of_w32 (void)
9677 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9679 get_process_times_fn = (GetProcessTimes_Proc)
9680 GetProcAddress (kernel32, "GetProcessTimes");
9682 DEFSYM (QCloaded_from, ":loaded-from");
9684 g_b_init_is_windows_9x = 0;
9685 g_b_init_open_process_token = 0;
9686 g_b_init_get_token_information = 0;
9687 g_b_init_lookup_account_sid = 0;
9688 g_b_init_get_sid_sub_authority = 0;
9689 g_b_init_get_sid_sub_authority_count = 0;
9690 g_b_init_get_security_info = 0;
9691 g_b_init_get_file_security_w = 0;
9692 g_b_init_get_file_security_a = 0;
9693 g_b_init_get_security_descriptor_owner = 0;
9694 g_b_init_get_security_descriptor_group = 0;
9695 g_b_init_is_valid_sid = 0;
9696 g_b_init_create_toolhelp32_snapshot = 0;
9697 g_b_init_process32_first = 0;
9698 g_b_init_process32_next = 0;
9699 g_b_init_open_thread_token = 0;
9700 g_b_init_impersonate_self = 0;
9701 g_b_init_revert_to_self = 0;
9702 g_b_init_get_process_memory_info = 0;
9703 g_b_init_get_process_working_set_size = 0;
9704 g_b_init_global_memory_status = 0;
9705 g_b_init_global_memory_status_ex = 0;
9706 g_b_init_equal_sid = 0;
9707 g_b_init_copy_sid = 0;
9708 g_b_init_get_length_sid = 0;
9709 g_b_init_get_native_system_info = 0;
9710 g_b_init_get_system_times = 0;
9711 g_b_init_create_symbolic_link_w = 0;
9712 g_b_init_create_symbolic_link_a = 0;
9713 g_b_init_get_security_descriptor_dacl = 0;
9714 g_b_init_convert_sd_to_sddl = 0;
9715 g_b_init_convert_sddl_to_sd = 0;
9716 g_b_init_is_valid_security_descriptor = 0;
9717 g_b_init_set_file_security_w = 0;
9718 g_b_init_set_file_security_a = 0;
9719 g_b_init_set_named_security_info_w = 0;
9720 g_b_init_set_named_security_info_a = 0;
9721 g_b_init_get_adapters_info = 0;
9722 g_b_init_compare_string_w = 0;
9723 g_b_init_debug_break_process = 0;
9724 num_of_processors = 0;
9725 /* The following sets a handler for shutdown notifications for
9726 console apps. This actually applies to Emacs in both console and
9727 GUI modes, since we had to fool windows into thinking emacs is a
9728 console application to get console mode to work. */
9729 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9731 /* "None" is the default group name on standalone workstations. */
9732 strcpy (dflt_group_name, "None");
9734 /* Reset, in case it has some value inherited from dump time. */
9735 w32_stat_get_owner_group = 0;
9737 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9738 (a.k.a. "wide") APIs to invoke functions that accept file
9739 names. */
9740 if (is_windows_9x ())
9741 w32_unicode_filenames = 0;
9742 else
9743 w32_unicode_filenames = 1;
9745 #ifdef HAVE_MODULES
9746 dynlib_reset_last_error ();
9747 #endif
9749 w32_crypto_hprov = (HCRYPTPROV)0;
9752 /* For make-serial-process */
9754 serial_open (Lisp_Object port_obj)
9756 char *port = SSDATA (port_obj);
9757 HANDLE hnd;
9758 child_process *cp;
9759 int fd = -1;
9761 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9762 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9763 if (hnd == INVALID_HANDLE_VALUE)
9764 error ("Could not open %s", port);
9765 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9766 if (fd == -1)
9767 error ("Could not open %s", port);
9769 cp = new_child ();
9770 if (!cp)
9771 error ("Could not create child process");
9772 cp->fd = fd;
9773 cp->status = STATUS_READ_ACKNOWLEDGED;
9774 fd_info[ fd ].hnd = hnd;
9775 fd_info[ fd ].flags |=
9776 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9777 if (fd_info[ fd ].cp != NULL)
9779 error ("fd_info[fd = %d] is already in use", fd);
9781 fd_info[ fd ].cp = cp;
9782 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9783 if (cp->ovl_read.hEvent == NULL)
9784 error ("Could not create read event");
9785 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9786 if (cp->ovl_write.hEvent == NULL)
9787 error ("Could not create write event");
9789 return fd;
9792 /* For serial-process-configure */
9793 void
9794 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9796 Lisp_Object childp2 = Qnil;
9797 Lisp_Object tem = Qnil;
9798 HANDLE hnd;
9799 DCB dcb;
9800 COMMTIMEOUTS ct;
9801 char summary[4] = "???"; /* This usually becomes "8N1". */
9803 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9804 error ("Not a serial process");
9805 hnd = fd_info[ p->outfd ].hnd;
9807 childp2 = Fcopy_sequence (p->childp);
9809 /* Initialize timeouts for blocking read and blocking write. */
9810 if (!GetCommTimeouts (hnd, &ct))
9811 error ("GetCommTimeouts() failed");
9812 ct.ReadIntervalTimeout = 0;
9813 ct.ReadTotalTimeoutMultiplier = 0;
9814 ct.ReadTotalTimeoutConstant = 0;
9815 ct.WriteTotalTimeoutMultiplier = 0;
9816 ct.WriteTotalTimeoutConstant = 0;
9817 if (!SetCommTimeouts (hnd, &ct))
9818 error ("SetCommTimeouts() failed");
9819 /* Read port attributes and prepare default configuration. */
9820 memset (&dcb, 0, sizeof (dcb));
9821 dcb.DCBlength = sizeof (DCB);
9822 if (!GetCommState (hnd, &dcb))
9823 error ("GetCommState() failed");
9824 dcb.fBinary = TRUE;
9825 dcb.fNull = FALSE;
9826 dcb.fAbortOnError = FALSE;
9827 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9828 dcb.ErrorChar = 0;
9829 dcb.EofChar = 0;
9830 dcb.EvtChar = 0;
9832 /* Configure speed. */
9833 if (!NILP (Fplist_member (contact, QCspeed)))
9834 tem = Fplist_get (contact, QCspeed);
9835 else
9836 tem = Fplist_get (p->childp, QCspeed);
9837 CHECK_NUMBER (tem);
9838 dcb.BaudRate = XINT (tem);
9839 childp2 = Fplist_put (childp2, QCspeed, tem);
9841 /* Configure bytesize. */
9842 if (!NILP (Fplist_member (contact, QCbytesize)))
9843 tem = Fplist_get (contact, QCbytesize);
9844 else
9845 tem = Fplist_get (p->childp, QCbytesize);
9846 if (NILP (tem))
9847 tem = make_number (8);
9848 CHECK_NUMBER (tem);
9849 if (XINT (tem) != 7 && XINT (tem) != 8)
9850 error (":bytesize must be nil (8), 7, or 8");
9851 dcb.ByteSize = XINT (tem);
9852 summary[0] = XINT (tem) + '0';
9853 childp2 = Fplist_put (childp2, QCbytesize, tem);
9855 /* Configure parity. */
9856 if (!NILP (Fplist_member (contact, QCparity)))
9857 tem = Fplist_get (contact, QCparity);
9858 else
9859 tem = Fplist_get (p->childp, QCparity);
9860 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9861 error (":parity must be nil (no parity), `even', or `odd'");
9862 dcb.fParity = FALSE;
9863 dcb.Parity = NOPARITY;
9864 dcb.fErrorChar = FALSE;
9865 if (NILP (tem))
9867 summary[1] = 'N';
9869 else if (EQ (tem, Qeven))
9871 summary[1] = 'E';
9872 dcb.fParity = TRUE;
9873 dcb.Parity = EVENPARITY;
9874 dcb.fErrorChar = TRUE;
9876 else if (EQ (tem, Qodd))
9878 summary[1] = 'O';
9879 dcb.fParity = TRUE;
9880 dcb.Parity = ODDPARITY;
9881 dcb.fErrorChar = TRUE;
9883 childp2 = Fplist_put (childp2, QCparity, tem);
9885 /* Configure stopbits. */
9886 if (!NILP (Fplist_member (contact, QCstopbits)))
9887 tem = Fplist_get (contact, QCstopbits);
9888 else
9889 tem = Fplist_get (p->childp, QCstopbits);
9890 if (NILP (tem))
9891 tem = make_number (1);
9892 CHECK_NUMBER (tem);
9893 if (XINT (tem) != 1 && XINT (tem) != 2)
9894 error (":stopbits must be nil (1 stopbit), 1, or 2");
9895 summary[2] = XINT (tem) + '0';
9896 if (XINT (tem) == 1)
9897 dcb.StopBits = ONESTOPBIT;
9898 else if (XINT (tem) == 2)
9899 dcb.StopBits = TWOSTOPBITS;
9900 childp2 = Fplist_put (childp2, QCstopbits, tem);
9902 /* Configure flowcontrol. */
9903 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9904 tem = Fplist_get (contact, QCflowcontrol);
9905 else
9906 tem = Fplist_get (p->childp, QCflowcontrol);
9907 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9908 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9909 dcb.fOutxCtsFlow = FALSE;
9910 dcb.fOutxDsrFlow = FALSE;
9911 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9912 dcb.fDsrSensitivity = FALSE;
9913 dcb.fTXContinueOnXoff = FALSE;
9914 dcb.fOutX = FALSE;
9915 dcb.fInX = FALSE;
9916 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9917 dcb.XonChar = 17; /* Control-Q */
9918 dcb.XoffChar = 19; /* Control-S */
9919 if (NILP (tem))
9921 /* Already configured. */
9923 else if (EQ (tem, Qhw))
9925 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9926 dcb.fOutxCtsFlow = TRUE;
9928 else if (EQ (tem, Qsw))
9930 dcb.fOutX = TRUE;
9931 dcb.fInX = TRUE;
9933 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9935 /* Activate configuration. */
9936 if (!SetCommState (hnd, &dcb))
9937 error ("SetCommState() failed");
9939 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9940 pset_childp (p, childp2);
9943 /* For make-pipe-process */
9944 void
9945 register_aux_fd (int infd)
9947 child_process *cp;
9949 cp = new_child ();
9950 if (!cp)
9951 error ("Could not create child process");
9952 cp->fd = infd;
9953 cp->status = STATUS_READ_ACKNOWLEDGED;
9955 if (fd_info[ infd ].cp != NULL)
9957 error ("fd_info[fd = %d] is already in use", infd);
9959 fd_info[ infd ].cp = cp;
9960 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9963 #ifdef HAVE_GNUTLS
9965 ssize_t
9966 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9968 int n, err;
9969 struct Lisp_Process *process = (struct Lisp_Process *)p;
9970 int fd = process->infd;
9972 n = sys_read (fd, (char*)buf, sz);
9974 if (n >= 0)
9975 return n;
9977 err = errno;
9979 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9980 if (err == EWOULDBLOCK)
9981 err = EAGAIN;
9983 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9985 return -1;
9988 ssize_t
9989 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9991 struct Lisp_Process *process = (struct Lisp_Process *)p;
9992 int fd = process->outfd;
9993 ssize_t n = sys_write (fd, buf, sz);
9995 /* 0 or more bytes written means everything went fine. */
9996 if (n >= 0)
9997 return n;
9999 /* Negative bytes written means we got an error in errno.
10000 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
10001 emacs_gnutls_transport_set_errno (process->gnutls_state,
10002 errno == EWOULDBLOCK ? EAGAIN : errno);
10004 return -1;
10006 #endif /* HAVE_GNUTLS */
10008 /* end of w32.c */