Warn about incomplete untarring of link files
[emacs.git] / src / w32.c
blob30aced9d9ffa102a79bfa84821294e8536fe3b18
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;
6411 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6412 have a fixed max size for file names, so we don't need the kind of
6413 alloc/malloc/realloc dance the gnulib version does. We also don't
6414 support FD-relative symlinks. */
6415 char *
6416 careadlinkat (int fd, char const *filename,
6417 char *buffer, size_t buffer_size,
6418 struct allocator const *alloc,
6419 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6421 char linkname[MAX_UTF8_PATH];
6422 ssize_t link_size;
6424 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6426 if (link_size > 0)
6428 char *retval = buffer;
6430 linkname[link_size++] = '\0';
6431 if (link_size > buffer_size)
6432 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6433 if (retval)
6434 memcpy (retval, linkname, link_size);
6436 return retval;
6438 return NULL;
6442 w32_copy_file (const char *from, const char *to,
6443 int keep_time, int preserve_ownership, int copy_acls)
6445 acl_t acl = NULL;
6446 BOOL copy_result;
6447 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6448 char from_a[MAX_PATH], to_a[MAX_PATH];
6450 /* We ignore preserve_ownership for now. */
6451 preserve_ownership = preserve_ownership;
6453 if (copy_acls)
6455 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6456 if (acl == NULL && acl_errno_valid (errno))
6457 return -2;
6459 if (w32_unicode_filenames)
6461 filename_to_utf16 (from, from_w);
6462 filename_to_utf16 (to, to_w);
6463 copy_result = CopyFileW (from_w, to_w, FALSE);
6465 else
6467 filename_to_ansi (from, from_a);
6468 filename_to_ansi (to, to_a);
6469 copy_result = CopyFileA (from_a, to_a, FALSE);
6471 if (!copy_result)
6473 /* CopyFile doesn't set errno when it fails. By far the most
6474 "popular" reason is that the target is read-only. */
6475 DWORD err = GetLastError ();
6477 switch (err)
6479 case ERROR_FILE_NOT_FOUND:
6480 errno = ENOENT;
6481 break;
6482 case ERROR_ACCESS_DENIED:
6483 errno = EACCES;
6484 break;
6485 case ERROR_ENCRYPTION_FAILED:
6486 errno = EIO;
6487 break;
6488 default:
6489 errno = EPERM;
6490 break;
6493 if (acl)
6494 acl_free (acl);
6495 return -1;
6497 /* CopyFile retains the timestamp by default. However, see
6498 "Community Additions" for CopyFile: it sounds like that is not
6499 entirely true. Testing on Windows XP confirms that modified time
6500 is copied, but creation and last-access times are not.
6501 FIXME? */
6502 else if (!keep_time)
6504 struct timespec now;
6505 DWORD attributes;
6507 if (w32_unicode_filenames)
6509 /* Ensure file is writable while its times are set. */
6510 attributes = GetFileAttributesW (to_w);
6511 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6512 now = current_timespec ();
6513 if (set_file_times (-1, to, now, now))
6515 /* Restore original attributes. */
6516 SetFileAttributesW (to_w, attributes);
6517 if (acl)
6518 acl_free (acl);
6519 return -3;
6521 /* Restore original attributes. */
6522 SetFileAttributesW (to_w, attributes);
6524 else
6526 attributes = GetFileAttributesA (to_a);
6527 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6528 now = current_timespec ();
6529 if (set_file_times (-1, to, now, now))
6531 SetFileAttributesA (to_a, attributes);
6532 if (acl)
6533 acl_free (acl);
6534 return -3;
6536 SetFileAttributesA (to_a, attributes);
6539 if (acl != NULL)
6541 bool fail =
6542 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6543 acl_free (acl);
6544 if (fail && acl_errno_valid (errno))
6545 return -4;
6548 return 0;
6552 /* Support for browsing other processes and their attributes. See
6553 process.c for the Lisp bindings. */
6555 /* Helper wrapper functions. */
6557 static HANDLE WINAPI
6558 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6560 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6562 if (g_b_init_create_toolhelp32_snapshot == 0)
6564 g_b_init_create_toolhelp32_snapshot = 1;
6565 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6566 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6567 "CreateToolhelp32Snapshot");
6569 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6571 return INVALID_HANDLE_VALUE;
6573 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6576 static BOOL WINAPI
6577 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6579 static Process32First_Proc s_pfn_Process32_First = NULL;
6581 if (g_b_init_process32_first == 0)
6583 g_b_init_process32_first = 1;
6584 s_pfn_Process32_First = (Process32First_Proc)
6585 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6586 "Process32First");
6588 if (s_pfn_Process32_First == NULL)
6590 return FALSE;
6592 return (s_pfn_Process32_First (hSnapshot, lppe));
6595 static BOOL WINAPI
6596 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6598 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6600 if (g_b_init_process32_next == 0)
6602 g_b_init_process32_next = 1;
6603 s_pfn_Process32_Next = (Process32Next_Proc)
6604 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6605 "Process32Next");
6607 if (s_pfn_Process32_Next == NULL)
6609 return FALSE;
6611 return (s_pfn_Process32_Next (hSnapshot, lppe));
6614 static BOOL WINAPI
6615 open_thread_token (HANDLE ThreadHandle,
6616 DWORD DesiredAccess,
6617 BOOL OpenAsSelf,
6618 PHANDLE TokenHandle)
6620 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6621 HMODULE hm_advapi32 = NULL;
6622 if (is_windows_9x () == TRUE)
6624 SetLastError (ERROR_NOT_SUPPORTED);
6625 return FALSE;
6627 if (g_b_init_open_thread_token == 0)
6629 g_b_init_open_thread_token = 1;
6630 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6631 s_pfn_Open_Thread_Token =
6632 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6634 if (s_pfn_Open_Thread_Token == NULL)
6636 SetLastError (ERROR_NOT_SUPPORTED);
6637 return FALSE;
6639 return (
6640 s_pfn_Open_Thread_Token (
6641 ThreadHandle,
6642 DesiredAccess,
6643 OpenAsSelf,
6644 TokenHandle)
6648 static BOOL WINAPI
6649 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6651 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6652 HMODULE hm_advapi32 = NULL;
6653 if (is_windows_9x () == TRUE)
6655 return FALSE;
6657 if (g_b_init_impersonate_self == 0)
6659 g_b_init_impersonate_self = 1;
6660 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6661 s_pfn_Impersonate_Self =
6662 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6664 if (s_pfn_Impersonate_Self == NULL)
6666 return FALSE;
6668 return s_pfn_Impersonate_Self (ImpersonationLevel);
6671 static BOOL WINAPI
6672 revert_to_self (void)
6674 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6675 HMODULE hm_advapi32 = NULL;
6676 if (is_windows_9x () == TRUE)
6678 return FALSE;
6680 if (g_b_init_revert_to_self == 0)
6682 g_b_init_revert_to_self = 1;
6683 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6684 s_pfn_Revert_To_Self =
6685 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6687 if (s_pfn_Revert_To_Self == NULL)
6689 return FALSE;
6691 return s_pfn_Revert_To_Self ();
6694 static BOOL WINAPI
6695 get_process_memory_info (HANDLE h_proc,
6696 PPROCESS_MEMORY_COUNTERS mem_counters,
6697 DWORD bufsize)
6699 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6700 HMODULE hm_psapi = NULL;
6701 if (is_windows_9x () == TRUE)
6703 return FALSE;
6705 if (g_b_init_get_process_memory_info == 0)
6707 g_b_init_get_process_memory_info = 1;
6708 hm_psapi = LoadLibrary ("Psapi.dll");
6709 if (hm_psapi)
6710 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6711 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6713 if (s_pfn_Get_Process_Memory_Info == NULL)
6715 return FALSE;
6717 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6720 static BOOL WINAPI
6721 get_process_working_set_size (HANDLE h_proc,
6722 PSIZE_T minrss,
6723 PSIZE_T maxrss)
6725 static GetProcessWorkingSetSize_Proc
6726 s_pfn_Get_Process_Working_Set_Size = NULL;
6728 if (is_windows_9x () == TRUE)
6730 return FALSE;
6732 if (g_b_init_get_process_working_set_size == 0)
6734 g_b_init_get_process_working_set_size = 1;
6735 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6736 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6737 "GetProcessWorkingSetSize");
6739 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6741 return FALSE;
6743 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6746 static BOOL WINAPI
6747 global_memory_status (MEMORYSTATUS *buf)
6749 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6751 if (is_windows_9x () == TRUE)
6753 return FALSE;
6755 if (g_b_init_global_memory_status == 0)
6757 g_b_init_global_memory_status = 1;
6758 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6759 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6760 "GlobalMemoryStatus");
6762 if (s_pfn_Global_Memory_Status == NULL)
6764 return FALSE;
6766 return s_pfn_Global_Memory_Status (buf);
6769 static BOOL WINAPI
6770 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6772 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6774 if (is_windows_9x () == TRUE)
6776 return FALSE;
6778 if (g_b_init_global_memory_status_ex == 0)
6780 g_b_init_global_memory_status_ex = 1;
6781 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6782 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6783 "GlobalMemoryStatusEx");
6785 if (s_pfn_Global_Memory_Status_Ex == NULL)
6787 return FALSE;
6789 return s_pfn_Global_Memory_Status_Ex (buf);
6792 Lisp_Object
6793 list_system_processes (void)
6795 Lisp_Object proclist = Qnil;
6796 HANDLE h_snapshot;
6798 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6800 if (h_snapshot != INVALID_HANDLE_VALUE)
6802 PROCESSENTRY32 proc_entry;
6803 DWORD proc_id;
6804 BOOL res;
6806 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6807 for (res = process32_first (h_snapshot, &proc_entry); res;
6808 res = process32_next (h_snapshot, &proc_entry))
6810 proc_id = proc_entry.th32ProcessID;
6811 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6814 CloseHandle (h_snapshot);
6815 proclist = Fnreverse (proclist);
6818 return proclist;
6821 static int
6822 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6824 TOKEN_PRIVILEGES priv;
6825 DWORD priv_size = sizeof (priv);
6826 DWORD opriv_size = sizeof (*old_priv);
6827 HANDLE h_token = NULL;
6828 HANDLE h_thread = GetCurrentThread ();
6829 int ret_val = 0;
6830 BOOL res;
6832 res = open_thread_token (h_thread,
6833 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6834 FALSE, &h_token);
6835 if (!res && GetLastError () == ERROR_NO_TOKEN)
6837 if (impersonate_self (SecurityImpersonation))
6838 res = open_thread_token (h_thread,
6839 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6840 FALSE, &h_token);
6842 if (res)
6844 priv.PrivilegeCount = 1;
6845 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6846 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6847 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6848 old_priv, &opriv_size)
6849 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6850 ret_val = 1;
6852 if (h_token)
6853 CloseHandle (h_token);
6855 return ret_val;
6858 static int
6859 restore_privilege (TOKEN_PRIVILEGES *priv)
6861 DWORD priv_size = sizeof (*priv);
6862 HANDLE h_token = NULL;
6863 int ret_val = 0;
6865 if (open_thread_token (GetCurrentThread (),
6866 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6867 FALSE, &h_token))
6869 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6870 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6871 ret_val = 1;
6873 if (h_token)
6874 CloseHandle (h_token);
6876 return ret_val;
6879 static Lisp_Object
6880 ltime (ULONGLONG time_100ns)
6882 ULONGLONG time_sec = time_100ns / 10000000;
6883 int subsec = time_100ns % 10000000;
6884 return list4i (time_sec >> 16, time_sec & 0xffff,
6885 subsec / 10, subsec % 10 * 100000);
6888 #define U64_TO_LISP_TIME(time) ltime (time)
6890 static int
6891 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6892 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6893 double *pcpu)
6895 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6896 ULONGLONG tem1, tem2, tem3, tem;
6898 if (!h_proc
6899 || !get_process_times_fn
6900 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6901 &ft_kernel, &ft_user))
6902 return 0;
6904 GetSystemTimeAsFileTime (&ft_current);
6906 FILETIME_TO_U64 (tem1, ft_kernel);
6907 *stime = U64_TO_LISP_TIME (tem1);
6909 FILETIME_TO_U64 (tem2, ft_user);
6910 *utime = U64_TO_LISP_TIME (tem2);
6912 tem3 = tem1 + tem2;
6913 *ttime = U64_TO_LISP_TIME (tem3);
6915 FILETIME_TO_U64 (tem, ft_creation);
6916 /* Process no 4 (System) returns zero creation time. */
6917 if (tem)
6918 tem -= utc_base;
6919 *ctime = U64_TO_LISP_TIME (tem);
6921 if (tem)
6923 FILETIME_TO_U64 (tem3, ft_current);
6924 tem = (tem3 - utc_base) - tem;
6926 *etime = U64_TO_LISP_TIME (tem);
6928 if (tem)
6930 *pcpu = 100.0 * (tem1 + tem2) / tem;
6931 if (*pcpu > 100)
6932 *pcpu = 100.0;
6934 else
6935 *pcpu = 0;
6937 return 1;
6940 Lisp_Object
6941 system_process_attributes (Lisp_Object pid)
6943 Lisp_Object attrs = Qnil;
6944 Lisp_Object cmd_str, decoded_cmd, tem;
6945 HANDLE h_snapshot, h_proc;
6946 DWORD proc_id;
6947 int found_proc = 0;
6948 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6949 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6950 DWORD glength = sizeof (gname);
6951 HANDLE token = NULL;
6952 SID_NAME_USE user_type;
6953 unsigned char *buf = NULL;
6954 DWORD blen = 0;
6955 TOKEN_USER user_token;
6956 TOKEN_PRIMARY_GROUP group_token;
6957 unsigned euid;
6958 unsigned egid;
6959 PROCESS_MEMORY_COUNTERS mem;
6960 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6961 SIZE_T minrss, maxrss;
6962 MEMORYSTATUS memst;
6963 MEMORY_STATUS_EX memstex;
6964 double totphys = 0.0;
6965 Lisp_Object ctime, stime, utime, etime, ttime;
6966 double pcpu;
6967 BOOL result = FALSE;
6969 CHECK_NUMBER_OR_FLOAT (pid);
6970 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6972 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6974 if (h_snapshot != INVALID_HANDLE_VALUE)
6976 PROCESSENTRY32 pe;
6977 BOOL res;
6979 pe.dwSize = sizeof (PROCESSENTRY32);
6980 for (res = process32_first (h_snapshot, &pe); res;
6981 res = process32_next (h_snapshot, &pe))
6983 if (proc_id == pe.th32ProcessID)
6985 if (proc_id == 0)
6986 decoded_cmd = build_string ("Idle");
6987 else
6989 /* Decode the command name from locale-specific
6990 encoding. */
6991 cmd_str = build_unibyte_string (pe.szExeFile);
6993 decoded_cmd =
6994 code_convert_string_norecord (cmd_str,
6995 Vlocale_coding_system, 0);
6997 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6998 attrs = Fcons (Fcons (Qppid,
6999 make_fixnum_or_float (pe.th32ParentProcessID)),
7000 attrs);
7001 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
7002 attrs);
7003 attrs = Fcons (Fcons (Qthcount,
7004 make_fixnum_or_float (pe.cntThreads)),
7005 attrs);
7006 found_proc = 1;
7007 break;
7011 CloseHandle (h_snapshot);
7014 if (!found_proc)
7015 return Qnil;
7017 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7018 FALSE, proc_id);
7019 /* If we were denied a handle to the process, try again after
7020 enabling the SeDebugPrivilege in our process. */
7021 if (!h_proc)
7023 TOKEN_PRIVILEGES priv_current;
7025 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
7027 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
7028 FALSE, proc_id);
7029 restore_privilege (&priv_current);
7030 revert_to_self ();
7033 if (h_proc)
7035 result = open_process_token (h_proc, TOKEN_QUERY, &token);
7036 if (result)
7038 result = get_token_information (token, TokenUser, NULL, 0, &blen);
7039 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7041 buf = xmalloc (blen);
7042 result = get_token_information (token, TokenUser,
7043 (LPVOID)buf, blen, &needed);
7044 if (result)
7046 memcpy (&user_token, buf, sizeof (user_token));
7047 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
7049 euid = get_rid (user_token.User.Sid);
7050 result = lookup_account_sid (NULL, user_token.User.Sid,
7051 uname, &ulength,
7052 domain, &dlength,
7053 &user_type);
7054 if (result)
7055 w32_add_to_cache (user_token.User.Sid, euid, uname);
7056 else
7058 strcpy (uname, "unknown");
7059 result = TRUE;
7062 ulength = strlen (uname);
7066 if (result)
7068 /* Determine a reasonable euid and gid values. */
7069 if (xstrcasecmp ("administrator", uname) == 0)
7071 euid = 500; /* well-known Administrator uid */
7072 egid = 513; /* well-known None gid */
7074 else
7076 /* Get group id and name. */
7077 result = get_token_information (token, TokenPrimaryGroup,
7078 (LPVOID)buf, blen, &needed);
7079 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7081 buf = xrealloc (buf, blen = needed);
7082 result = get_token_information (token, TokenPrimaryGroup,
7083 (LPVOID)buf, blen, &needed);
7085 if (result)
7087 memcpy (&group_token, buf, sizeof (group_token));
7088 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7090 egid = get_rid (group_token.PrimaryGroup);
7091 dlength = sizeof (domain);
7092 result =
7093 lookup_account_sid (NULL, group_token.PrimaryGroup,
7094 gname, &glength, NULL, &dlength,
7095 &user_type);
7096 if (result)
7097 w32_add_to_cache (group_token.PrimaryGroup,
7098 egid, gname);
7099 else
7101 strcpy (gname, "None");
7102 result = TRUE;
7105 glength = strlen (gname);
7109 xfree (buf);
7111 if (!result)
7113 if (!is_windows_9x ())
7115 /* We couldn't open the process token, presumably because of
7116 insufficient access rights. Assume this process is run
7117 by the system. */
7118 strcpy (uname, "SYSTEM");
7119 strcpy (gname, "None");
7120 euid = 18; /* SYSTEM */
7121 egid = 513; /* None */
7122 glength = strlen (gname);
7123 ulength = strlen (uname);
7125 /* If we are running under Windows 9X, where security calls are
7126 not supported, we assume all processes are run by the current
7127 user. */
7128 else if (GetUserName (uname, &ulength))
7130 if (xstrcasecmp ("administrator", uname) == 0)
7131 euid = 0;
7132 else
7133 euid = 123;
7134 egid = euid;
7135 strcpy (gname, "None");
7136 glength = strlen (gname);
7137 ulength = strlen (uname);
7139 else
7141 euid = 123;
7142 egid = 123;
7143 strcpy (uname, "administrator");
7144 ulength = strlen (uname);
7145 strcpy (gname, "None");
7146 glength = strlen (gname);
7148 if (token)
7149 CloseHandle (token);
7152 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7153 tem = make_unibyte_string (uname, ulength);
7154 attrs = Fcons (Fcons (Quser,
7155 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7156 attrs);
7157 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7158 tem = make_unibyte_string (gname, glength);
7159 attrs = Fcons (Fcons (Qgroup,
7160 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7161 attrs);
7163 if (global_memory_status_ex (&memstex))
7164 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7165 totphys = memstex.ullTotalPhys / 1024.0;
7166 #else
7167 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7168 double, so we need to do this for it... */
7170 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7171 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7172 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7174 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7176 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7177 else if (global_memory_status (&memst))
7178 totphys = memst.dwTotalPhys / 1024.0;
7180 if (h_proc
7181 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7182 sizeof (mem_ex)))
7184 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7186 attrs = Fcons (Fcons (Qmajflt,
7187 make_fixnum_or_float (mem_ex.PageFaultCount)),
7188 attrs);
7189 attrs = Fcons (Fcons (Qvsize,
7190 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7191 attrs);
7192 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7193 if (totphys)
7194 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7196 else if (h_proc
7197 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7199 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7201 attrs = Fcons (Fcons (Qmajflt,
7202 make_fixnum_or_float (mem.PageFaultCount)),
7203 attrs);
7204 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7205 if (totphys)
7206 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7208 else if (h_proc
7209 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7211 DWORD rss = maxrss / 1024;
7213 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7214 if (totphys)
7215 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7218 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7220 attrs = Fcons (Fcons (Qutime, utime), attrs);
7221 attrs = Fcons (Fcons (Qstime, stime), attrs);
7222 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7223 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7224 attrs = Fcons (Fcons (Qetime, etime), attrs);
7225 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7228 /* FIXME: Retrieve command line by walking the PEB of the process. */
7230 if (h_proc)
7231 CloseHandle (h_proc);
7232 return attrs;
7236 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7237 unsigned long long *totalswap, unsigned long long *freeswap)
7239 MEMORYSTATUS memst;
7240 MEMORY_STATUS_EX memstex;
7242 /* Use GlobalMemoryStatusEx if available, as it can report more than
7243 2GB of memory. */
7244 if (global_memory_status_ex (&memstex))
7246 *totalram = memstex.ullTotalPhys;
7247 *freeram = memstex.ullAvailPhys;
7248 *totalswap = memstex.ullTotalPageFile;
7249 *freeswap = memstex.ullAvailPageFile;
7250 return 0;
7252 else if (global_memory_status (&memst))
7254 *totalram = memst.dwTotalPhys;
7255 *freeram = memst.dwAvailPhys;
7256 *totalswap = memst.dwTotalPageFile;
7257 *freeswap = memst.dwAvailPageFile;
7258 return 0;
7260 else
7261 return -1;
7265 /* Wrappers for winsock functions to map between our file descriptors
7266 and winsock's handles; also set h_errno for convenience.
7268 To allow Emacs to run on systems which don't have winsock support
7269 installed, we dynamically link to winsock on startup if present, and
7270 otherwise provide the minimum necessary functionality
7271 (eg. gethostname). */
7273 /* function pointers for relevant socket functions */
7274 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7275 void (PASCAL *pfn_WSASetLastError) (int iError);
7276 int (PASCAL *pfn_WSAGetLastError) (void);
7277 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7278 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7279 WSANETWORKEVENTS *NetworkEvents);
7281 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7282 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7283 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7284 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7285 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7286 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7287 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7288 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7289 int (PASCAL *pfn_closesocket) (SOCKET s);
7290 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7291 int (PASCAL *pfn_WSACleanup) (void);
7293 u_short (PASCAL *pfn_htons) (u_short hostshort);
7294 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7295 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7296 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7297 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7298 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7299 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7300 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7301 const char * optval, int optlen);
7302 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7303 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7304 int * namelen);
7305 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7306 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7307 struct sockaddr * from, int * fromlen);
7308 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7309 const struct sockaddr * to, int tolen);
7311 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7312 const struct addrinfo *, struct addrinfo **);
7313 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7315 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7316 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7317 #ifndef HANDLE_FLAG_INHERIT
7318 #define HANDLE_FLAG_INHERIT 1
7319 #endif
7321 HANDLE winsock_lib;
7322 static int winsock_inuse;
7324 BOOL term_winsock (void);
7326 BOOL
7327 term_winsock (void)
7329 if (winsock_lib != NULL && winsock_inuse == 0)
7331 release_listen_threads ();
7332 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7333 after WSAStartup returns successfully, but it seems reasonable
7334 to allow unloading winsock anyway in that case. */
7335 if (pfn_WSACleanup () == 0 ||
7336 pfn_WSAGetLastError () == WSAENETDOWN)
7338 if (FreeLibrary (winsock_lib))
7339 winsock_lib = NULL;
7340 return TRUE;
7343 return FALSE;
7346 BOOL
7347 init_winsock (int load_now)
7349 WSADATA winsockData;
7351 if (winsock_lib != NULL)
7352 return TRUE;
7354 pfn_SetHandleInformation
7355 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7356 "SetHandleInformation");
7358 winsock_lib = LoadLibrary ("Ws2_32.dll");
7360 if (winsock_lib != NULL)
7362 /* dynamically link to socket functions */
7364 #define LOAD_PROC(fn) \
7365 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7366 goto fail;
7368 LOAD_PROC (WSAStartup);
7369 LOAD_PROC (WSASetLastError);
7370 LOAD_PROC (WSAGetLastError);
7371 LOAD_PROC (WSAEventSelect);
7372 LOAD_PROC (WSAEnumNetworkEvents);
7373 LOAD_PROC (WSACreateEvent);
7374 LOAD_PROC (WSACloseEvent);
7375 LOAD_PROC (socket);
7376 LOAD_PROC (bind);
7377 LOAD_PROC (connect);
7378 LOAD_PROC (ioctlsocket);
7379 LOAD_PROC (recv);
7380 LOAD_PROC (send);
7381 LOAD_PROC (closesocket);
7382 LOAD_PROC (shutdown);
7383 LOAD_PROC (htons);
7384 LOAD_PROC (ntohs);
7385 LOAD_PROC (inet_addr);
7386 LOAD_PROC (gethostname);
7387 LOAD_PROC (gethostbyname);
7388 LOAD_PROC (getservbyname);
7389 LOAD_PROC (getpeername);
7390 LOAD_PROC (WSACleanup);
7391 LOAD_PROC (setsockopt);
7392 LOAD_PROC (listen);
7393 LOAD_PROC (getsockname);
7394 LOAD_PROC (accept);
7395 LOAD_PROC (recvfrom);
7396 LOAD_PROC (sendto);
7397 #undef LOAD_PROC
7399 /* Try loading functions not available before XP. */
7400 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7401 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7402 /* Paranoia: these two functions should go together, so if one
7403 is absent, we cannot use the other. */
7404 if (pfn_getaddrinfo == NULL)
7405 pfn_freeaddrinfo = NULL;
7406 else if (pfn_freeaddrinfo == NULL)
7407 pfn_getaddrinfo = NULL;
7409 /* specify version 1.1 of winsock */
7410 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7412 if (winsockData.wVersion != 0x101)
7413 goto fail;
7415 if (!load_now)
7417 /* Report that winsock exists and is usable, but leave
7418 socket functions disabled. I am assuming that calling
7419 WSAStartup does not require any network interaction,
7420 and in particular does not cause or require a dial-up
7421 connection to be established. */
7423 pfn_WSACleanup ();
7424 FreeLibrary (winsock_lib);
7425 winsock_lib = NULL;
7427 winsock_inuse = 0;
7428 return TRUE;
7431 fail:
7432 FreeLibrary (winsock_lib);
7433 winsock_lib = NULL;
7436 return FALSE;
7440 int h_errno = 0;
7442 /* Function to map winsock error codes to errno codes for those errno
7443 code defined in errno.h (errno values not defined by errno.h are
7444 already in nt/inc/sys/socket.h). */
7445 static void
7446 set_errno (void)
7448 int wsa_err;
7450 h_errno = 0;
7451 if (winsock_lib == NULL)
7452 wsa_err = EINVAL;
7453 else
7454 wsa_err = pfn_WSAGetLastError ();
7456 switch (wsa_err)
7458 case WSAEACCES: errno = EACCES; break;
7459 case WSAEBADF: errno = EBADF; break;
7460 case WSAEFAULT: errno = EFAULT; break;
7461 case WSAEINTR: errno = EINTR; break;
7462 case WSAEINVAL: errno = EINVAL; break;
7463 case WSAEMFILE: errno = EMFILE; break;
7464 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7465 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7466 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7467 case WSAENOTCONN: errno = ENOTCONN; break;
7468 default: errno = wsa_err; break;
7472 static void
7473 check_errno (void)
7475 h_errno = 0;
7476 if (winsock_lib != NULL)
7477 pfn_WSASetLastError (0);
7480 /* Extend strerror to handle the winsock-specific error codes. */
7481 struct {
7482 int errnum;
7483 const char * msg;
7484 } _wsa_errlist[] = {
7485 {WSAEINTR , "Interrupted function call"},
7486 {WSAEBADF , "Bad file descriptor"},
7487 {WSAEACCES , "Permission denied"},
7488 {WSAEFAULT , "Bad address"},
7489 {WSAEINVAL , "Invalid argument"},
7490 {WSAEMFILE , "Too many open files"},
7492 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7493 {WSAEINPROGRESS , "Operation now in progress"},
7494 {WSAEALREADY , "Operation already in progress"},
7495 {WSAENOTSOCK , "Socket operation on non-socket"},
7496 {WSAEDESTADDRREQ , "Destination address required"},
7497 {WSAEMSGSIZE , "Message too long"},
7498 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7499 {WSAENOPROTOOPT , "Bad protocol option"},
7500 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7501 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7502 {WSAEOPNOTSUPP , "Operation not supported"},
7503 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7504 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7505 {WSAEADDRINUSE , "Address already in use"},
7506 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7507 {WSAENETDOWN , "Network is down"},
7508 {WSAENETUNREACH , "Network is unreachable"},
7509 {WSAENETRESET , "Network dropped connection on reset"},
7510 {WSAECONNABORTED , "Software caused connection abort"},
7511 {WSAECONNRESET , "Connection reset by peer"},
7512 {WSAENOBUFS , "No buffer space available"},
7513 {WSAEISCONN , "Socket is already connected"},
7514 {WSAENOTCONN , "Socket is not connected"},
7515 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7516 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7517 {WSAETIMEDOUT , "Connection timed out"},
7518 {WSAECONNREFUSED , "Connection refused"},
7519 {WSAELOOP , "Network loop"}, /* not sure */
7520 {WSAENAMETOOLONG , "Name is too long"},
7521 {WSAEHOSTDOWN , "Host is down"},
7522 {WSAEHOSTUNREACH , "No route to host"},
7523 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7524 {WSAEPROCLIM , "Too many processes"},
7525 {WSAEUSERS , "Too many users"}, /* not sure */
7526 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7527 {WSAESTALE , "Data is stale"}, /* not sure */
7528 {WSAEREMOTE , "Remote error"}, /* not sure */
7530 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7531 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7532 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7533 {WSAEDISCON , "Graceful shutdown in progress"},
7534 #ifdef WSAENOMORE
7535 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7536 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7537 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7538 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7539 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7540 {WSASYSCALLFAILURE , "System call failure"},
7541 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7542 {WSATYPE_NOT_FOUND , "Class type not found"},
7543 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7544 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7545 {WSAEREFUSED , "Operation refused"}, /* not sure */
7546 #endif
7548 {WSAHOST_NOT_FOUND , "Host not found"},
7549 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7550 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7551 {WSANO_DATA , "Valid name, no data record of requested type"},
7553 {-1, NULL}
7556 char *
7557 sys_strerror (int error_no)
7559 int i;
7560 static char unknown_msg[40];
7562 if (error_no >= 0 && error_no < sys_nerr)
7563 return sys_errlist[error_no];
7565 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7566 if (_wsa_errlist[i].errnum == error_no)
7567 return (char *)_wsa_errlist[i].msg;
7569 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7570 return unknown_msg;
7573 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7574 but I believe the method of keeping the socket handle separate (and
7575 insuring it is not inheritable) is the correct one. */
7577 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7579 static int socket_to_fd (SOCKET s);
7582 sys_socket (int af, int type, int protocol)
7584 SOCKET s;
7586 if (winsock_lib == NULL)
7588 errno = ENETDOWN;
7589 return -1;
7592 check_errno ();
7594 /* call the real socket function */
7595 s = pfn_socket (af, type, protocol);
7597 if (s != INVALID_SOCKET)
7598 return socket_to_fd (s);
7600 set_errno ();
7601 return -1;
7604 /* Convert a SOCKET to a file descriptor. */
7605 static int
7606 socket_to_fd (SOCKET s)
7608 int fd;
7609 child_process * cp;
7611 /* Although under NT 3.5 _open_osfhandle will accept a socket
7612 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7613 that does not work under NT 3.1. However, we can get the same
7614 effect by using a backdoor function to replace an existing
7615 descriptor handle with the one we want. */
7617 /* allocate a file descriptor (with appropriate flags) */
7618 fd = _open ("NUL:", _O_RDWR);
7619 if (fd >= 0)
7621 /* Make a non-inheritable copy of the socket handle. Note
7622 that it is possible that sockets aren't actually kernel
7623 handles, which appears to be the case on Windows 9x when
7624 the MS Proxy winsock client is installed. */
7626 /* Apparently there is a bug in NT 3.51 with some service
7627 packs, which prevents using DuplicateHandle to make a
7628 socket handle non-inheritable (causes WSACleanup to
7629 hang). The work-around is to use SetHandleInformation
7630 instead if it is available and implemented. */
7631 if (pfn_SetHandleInformation)
7633 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7635 else
7637 HANDLE parent = GetCurrentProcess ();
7638 HANDLE new_s = INVALID_HANDLE_VALUE;
7640 if (DuplicateHandle (parent,
7641 (HANDLE) s,
7642 parent,
7643 &new_s,
7645 FALSE,
7646 DUPLICATE_SAME_ACCESS))
7648 /* It is possible that DuplicateHandle succeeds even
7649 though the socket wasn't really a kernel handle,
7650 because a real handle has the same value. So
7651 test whether the new handle really is a socket. */
7652 unsigned long nonblocking = 0;
7653 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7655 pfn_closesocket (s);
7656 s = (SOCKET) new_s;
7658 else
7660 CloseHandle (new_s);
7665 eassert (fd < MAXDESC);
7666 fd_info[fd].hnd = (HANDLE) s;
7668 /* set our own internal flags */
7669 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7671 cp = new_child ();
7672 if (cp)
7674 cp->fd = fd;
7675 cp->status = STATUS_READ_ACKNOWLEDGED;
7677 /* attach child_process to fd_info */
7678 if (fd_info[ fd ].cp != NULL)
7680 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7681 emacs_abort ();
7684 fd_info[ fd ].cp = cp;
7686 /* success! */
7687 winsock_inuse++; /* count open sockets */
7688 return fd;
7691 /* clean up */
7692 _close (fd);
7694 else
7695 pfn_closesocket (s);
7696 errno = EMFILE;
7697 return -1;
7701 sys_bind (int s, const struct sockaddr * addr, int namelen)
7703 if (winsock_lib == NULL)
7705 errno = ENOTSOCK;
7706 return SOCKET_ERROR;
7709 check_errno ();
7710 if (fd_info[s].flags & FILE_SOCKET)
7712 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7713 if (rc == SOCKET_ERROR)
7714 set_errno ();
7715 return rc;
7717 errno = ENOTSOCK;
7718 return SOCKET_ERROR;
7722 sys_connect (int s, const struct sockaddr * name, int namelen)
7724 if (winsock_lib == NULL)
7726 errno = ENOTSOCK;
7727 return SOCKET_ERROR;
7730 check_errno ();
7731 if (fd_info[s].flags & FILE_SOCKET)
7733 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7734 if (rc == SOCKET_ERROR)
7736 set_errno ();
7737 /* If this is a non-blocking 'connect', set the bit in flags
7738 that will tell reader_thread to wait for connection
7739 before trying to read. */
7740 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7742 errno = EINPROGRESS; /* that's what process.c expects */
7743 fd_info[s].flags |= FILE_CONNECT;
7746 return rc;
7748 errno = ENOTSOCK;
7749 return SOCKET_ERROR;
7752 u_short
7753 sys_htons (u_short hostshort)
7755 return (winsock_lib != NULL) ?
7756 pfn_htons (hostshort) : hostshort;
7759 u_short
7760 sys_ntohs (u_short netshort)
7762 return (winsock_lib != NULL) ?
7763 pfn_ntohs (netshort) : netshort;
7766 unsigned long
7767 sys_inet_addr (const char * cp)
7769 return (winsock_lib != NULL) ?
7770 pfn_inet_addr (cp) : INADDR_NONE;
7774 sys_gethostname (char * name, int namelen)
7776 if (winsock_lib != NULL)
7778 int retval;
7780 check_errno ();
7781 retval = pfn_gethostname (name, namelen);
7782 if (retval == SOCKET_ERROR)
7783 set_errno ();
7784 return retval;
7787 if (namelen > MAX_COMPUTERNAME_LENGTH)
7788 return !GetComputerName (name, (DWORD *)&namelen);
7790 errno = EFAULT;
7791 return SOCKET_ERROR;
7794 struct hostent *
7795 sys_gethostbyname (const char * name)
7797 struct hostent * host;
7798 int h_err = h_errno;
7800 if (winsock_lib == NULL)
7802 h_errno = NO_RECOVERY;
7803 errno = ENETDOWN;
7804 return NULL;
7807 check_errno ();
7808 host = pfn_gethostbyname (name);
7809 if (!host)
7811 set_errno ();
7812 h_errno = errno;
7814 else
7815 h_errno = h_err;
7816 return host;
7819 struct servent *
7820 sys_getservbyname (const char * name, const char * proto)
7822 struct servent * serv;
7824 if (winsock_lib == NULL)
7826 errno = ENETDOWN;
7827 return NULL;
7830 check_errno ();
7831 serv = pfn_getservbyname (name, proto);
7832 if (!serv)
7833 set_errno ();
7834 return serv;
7838 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7840 if (winsock_lib == NULL)
7842 errno = ENETDOWN;
7843 return SOCKET_ERROR;
7846 check_errno ();
7847 if (fd_info[s].flags & FILE_SOCKET)
7849 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7850 if (rc == SOCKET_ERROR)
7851 set_errno ();
7852 return rc;
7854 errno = ENOTSOCK;
7855 return SOCKET_ERROR;
7859 sys_getaddrinfo (const char *node, const char *service,
7860 const struct addrinfo *hints, struct addrinfo **res)
7862 int rc;
7864 if (winsock_lib == NULL)
7866 errno = ENETDOWN;
7867 return SOCKET_ERROR;
7870 check_errno ();
7871 if (pfn_getaddrinfo)
7872 rc = pfn_getaddrinfo (node, service, hints, res);
7873 else
7875 int port = 0;
7876 struct hostent *host_info;
7877 struct gai_storage {
7878 struct addrinfo addrinfo;
7879 struct sockaddr_in sockaddr_in;
7880 } *gai_storage;
7882 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7883 if (hints && hints->ai_flags != 0)
7884 return WSAEINVAL;
7885 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7886 if (!node)
7887 return WSAHOST_NOT_FOUND;
7889 if (service)
7891 const char *protocol =
7892 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7893 struct servent *srv = sys_getservbyname (service, protocol);
7895 if (srv)
7896 port = srv->s_port;
7897 else if (*service >= '0' && *service <= '9')
7899 char *endp;
7901 port = strtoul (service, &endp, 10);
7902 if (*endp || port > 65536)
7903 return WSAHOST_NOT_FOUND;
7904 port = sys_htons ((unsigned short) port);
7906 else
7907 return WSAHOST_NOT_FOUND;
7910 gai_storage = xzalloc (sizeof *gai_storage);
7911 gai_storage->sockaddr_in.sin_port = port;
7912 host_info = sys_gethostbyname (node);
7913 if (host_info)
7915 memcpy (&gai_storage->sockaddr_in.sin_addr,
7916 host_info->h_addr, host_info->h_length);
7917 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7919 else
7921 /* Attempt to interpret host as numeric inet address. */
7922 unsigned long numeric_addr = sys_inet_addr (node);
7924 if (numeric_addr == -1)
7926 free (gai_storage);
7927 return WSAHOST_NOT_FOUND;
7930 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7931 sizeof (gai_storage->sockaddr_in.sin_addr));
7932 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7935 gai_storage->addrinfo.ai_addr =
7936 (struct sockaddr *)&gai_storage->sockaddr_in;
7937 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7938 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7939 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7940 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7941 gai_storage->addrinfo.ai_next = NULL;
7943 *res = &gai_storage->addrinfo;
7944 rc = 0;
7947 return rc;
7950 void
7951 sys_freeaddrinfo (struct addrinfo *ai)
7953 if (winsock_lib == NULL)
7955 errno = ENETDOWN;
7956 return;
7959 check_errno ();
7960 if (pfn_freeaddrinfo)
7961 pfn_freeaddrinfo (ai);
7962 else
7964 eassert (ai->ai_next == NULL);
7965 xfree (ai);
7970 sys_shutdown (int s, int how)
7972 if (winsock_lib == NULL)
7974 errno = ENETDOWN;
7975 return SOCKET_ERROR;
7978 check_errno ();
7979 if (fd_info[s].flags & FILE_SOCKET)
7981 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7982 if (rc == SOCKET_ERROR)
7983 set_errno ();
7984 return rc;
7986 errno = ENOTSOCK;
7987 return SOCKET_ERROR;
7991 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7993 if (winsock_lib == NULL)
7995 errno = ENETDOWN;
7996 return SOCKET_ERROR;
7999 check_errno ();
8000 if (fd_info[s].flags & FILE_SOCKET)
8002 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
8003 (const char *)optval, optlen);
8004 if (rc == SOCKET_ERROR)
8005 set_errno ();
8006 return rc;
8008 errno = ENOTSOCK;
8009 return SOCKET_ERROR;
8013 sys_listen (int s, int backlog)
8015 if (winsock_lib == NULL)
8017 errno = ENETDOWN;
8018 return SOCKET_ERROR;
8021 check_errno ();
8022 if (fd_info[s].flags & FILE_SOCKET)
8024 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
8025 if (rc == SOCKET_ERROR)
8026 set_errno ();
8027 else
8028 fd_info[s].flags |= FILE_LISTEN;
8029 return rc;
8031 errno = ENOTSOCK;
8032 return SOCKET_ERROR;
8036 sys_getsockname (int s, struct sockaddr * name, int * namelen)
8038 if (winsock_lib == NULL)
8040 errno = ENETDOWN;
8041 return SOCKET_ERROR;
8044 check_errno ();
8045 if (fd_info[s].flags & FILE_SOCKET)
8047 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
8048 if (rc == SOCKET_ERROR)
8049 set_errno ();
8050 return rc;
8052 errno = ENOTSOCK;
8053 return SOCKET_ERROR;
8057 sys_accept (int s, struct sockaddr * addr, int * addrlen)
8059 if (winsock_lib == NULL)
8061 errno = ENETDOWN;
8062 return -1;
8065 check_errno ();
8066 if (fd_info[s].flags & FILE_LISTEN)
8068 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
8069 int fd = -1;
8070 if (t == INVALID_SOCKET)
8071 set_errno ();
8072 else
8073 fd = socket_to_fd (t);
8075 if (fd >= 0)
8077 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
8078 ResetEvent (fd_info[s].cp->char_avail);
8080 return fd;
8082 errno = ENOTSOCK;
8083 return -1;
8087 sys_recvfrom (int s, char * buf, int len, int flags,
8088 struct sockaddr * from, int * fromlen)
8090 if (winsock_lib == NULL)
8092 errno = ENETDOWN;
8093 return SOCKET_ERROR;
8096 check_errno ();
8097 if (fd_info[s].flags & FILE_SOCKET)
8099 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8100 if (rc == SOCKET_ERROR)
8101 set_errno ();
8102 return rc;
8104 errno = ENOTSOCK;
8105 return SOCKET_ERROR;
8109 sys_sendto (int s, const char * buf, int len, int flags,
8110 const struct sockaddr * to, int tolen)
8112 if (winsock_lib == NULL)
8114 errno = ENETDOWN;
8115 return SOCKET_ERROR;
8118 check_errno ();
8119 if (fd_info[s].flags & FILE_SOCKET)
8121 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8122 if (rc == SOCKET_ERROR)
8123 set_errno ();
8124 return rc;
8126 errno = ENOTSOCK;
8127 return SOCKET_ERROR;
8130 /* Windows does not have an fcntl function. Provide an implementation
8131 good enough for Emacs. */
8133 fcntl (int s, int cmd, int options)
8135 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8136 invoked in a context where fd1 is closed and all descriptors less
8137 than fd1 are open, so sys_dup is an adequate implementation. */
8138 if (cmd == F_DUPFD_CLOEXEC)
8139 return sys_dup (s);
8141 check_errno ();
8142 if (fd_info[s].flags & FILE_SOCKET)
8144 if (winsock_lib == NULL)
8146 errno = ENETDOWN;
8147 return -1;
8150 if (cmd == F_SETFL && options == O_NONBLOCK)
8152 unsigned long nblock = 1;
8153 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8154 if (rc == SOCKET_ERROR)
8155 set_errno ();
8156 /* Keep track of the fact that we set this to non-blocking. */
8157 fd_info[s].flags |= FILE_NDELAY;
8158 return rc;
8160 else
8162 errno = EINVAL;
8163 return SOCKET_ERROR;
8166 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8167 == (FILE_PIPE | FILE_WRITE))
8169 /* Force our writes to pipes be non-blocking. */
8170 if (cmd == F_SETFL && options == O_NONBLOCK)
8172 HANDLE h = (HANDLE)_get_osfhandle (s);
8173 DWORD pipe_mode = PIPE_NOWAIT;
8175 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8177 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8178 return SOCKET_ERROR;
8180 fd_info[s].flags |= FILE_NDELAY;
8181 return 0;
8183 else
8185 errno = EINVAL;
8186 return SOCKET_ERROR;
8189 errno = ENOTSOCK;
8190 return SOCKET_ERROR;
8194 /* Shadow main io functions: we need to handle pipes and sockets more
8195 intelligently. */
8198 sys_close (int fd)
8200 int rc;
8202 if (fd < 0)
8204 errno = EBADF;
8205 return -1;
8208 if (fd < MAXDESC && fd_info[fd].cp)
8210 child_process * cp = fd_info[fd].cp;
8212 fd_info[fd].cp = NULL;
8214 if (CHILD_ACTIVE (cp))
8216 /* if last descriptor to active child_process then cleanup */
8217 int i;
8218 for (i = 0; i < MAXDESC; i++)
8220 if (i == fd)
8221 continue;
8222 if (fd_info[i].cp == cp)
8223 break;
8225 if (i == MAXDESC)
8227 if (fd_info[fd].flags & FILE_SOCKET)
8229 if (winsock_lib == NULL) emacs_abort ();
8231 pfn_shutdown (SOCK_HANDLE (fd), 2);
8232 rc = pfn_closesocket (SOCK_HANDLE (fd));
8234 winsock_inuse--; /* count open sockets */
8236 /* If the process handle is NULL, it's either a socket
8237 or serial connection, or a subprocess that was
8238 already reaped by reap_subprocess, but whose
8239 resources were not yet freed, because its output was
8240 not fully read yet by the time it was reaped. (This
8241 usually happens with async subprocesses whose output
8242 is being read by Emacs.) Otherwise, this process was
8243 not reaped yet, so we set its FD to a negative value
8244 to make sure sys_select will eventually get to
8245 calling the SIGCHLD handler for it, which will then
8246 invoke waitpid and reap_subprocess. */
8247 if (cp->procinfo.hProcess == NULL)
8248 delete_child (cp);
8249 else
8250 cp->fd = -1;
8255 if (fd >= 0 && fd < MAXDESC)
8256 fd_info[fd].flags = 0;
8258 /* Note that sockets do not need special treatment here (at least on
8259 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8260 closesocket is equivalent to CloseHandle, which is to be expected
8261 because socket handles are fully fledged kernel handles. */
8262 rc = _close (fd);
8264 return rc;
8268 sys_dup (int fd)
8270 int new_fd;
8272 new_fd = _dup (fd);
8273 if (new_fd >= 0 && new_fd < MAXDESC)
8275 /* duplicate our internal info as well */
8276 fd_info[new_fd] = fd_info[fd];
8278 return new_fd;
8282 sys_dup2 (int src, int dst)
8284 int rc;
8286 if (dst < 0 || dst >= MAXDESC)
8288 errno = EBADF;
8289 return -1;
8292 /* MS _dup2 seems to have weird side effect when invoked with 2
8293 identical arguments: an attempt to fclose the corresponding stdio
8294 stream after that hangs (we do close standard streams in
8295 init_ntproc). Attempt to avoid that by not calling _dup2 that
8296 way: if SRC is valid, we know that dup2 should be a no-op, so do
8297 nothing and return DST. */
8298 if (src == dst)
8300 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8302 errno = EBADF;
8303 return -1;
8305 return dst;
8308 /* Make sure we close the destination first if it's a pipe or socket. */
8309 if (fd_info[dst].flags != 0)
8310 sys_close (dst);
8312 rc = _dup2 (src, dst);
8313 if (rc == 0)
8315 /* Duplicate our internal info as well. */
8316 fd_info[dst] = fd_info[src];
8318 return rc == 0 ? dst : rc;
8322 pipe2 (int * phandles, int pipe2_flags)
8324 int rc;
8325 unsigned flags;
8326 unsigned pipe_size = 0;
8328 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8330 /* Allow Lisp to override the default buffer size of the pipe. */
8331 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8332 pipe_size = w32_pipe_buffer_size;
8334 /* make pipe handles non-inheritable; when we spawn a child, we
8335 replace the relevant handle with an inheritable one. Also put
8336 pipes into binary mode; we will do text mode translation ourselves
8337 if required. */
8338 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8340 if (rc == 0)
8342 /* Protect against overflow, since Windows can open more handles than
8343 our fd_info array has room for. */
8344 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8346 _close (phandles[0]);
8347 _close (phandles[1]);
8348 errno = EMFILE;
8349 rc = -1;
8351 else
8353 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8354 fd_info[phandles[0]].flags = flags;
8356 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8357 fd_info[phandles[1]].flags = flags;
8361 return rc;
8364 /* Function to do blocking read of one byte, needed to implement
8365 select. It is only allowed on communication ports, sockets, or
8366 pipes. */
8368 _sys_read_ahead (int fd)
8370 child_process * cp;
8371 int rc;
8373 if (fd < 0 || fd >= MAXDESC)
8374 return STATUS_READ_ERROR;
8376 cp = fd_info[fd].cp;
8378 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8379 return STATUS_READ_ERROR;
8381 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8382 || (fd_info[fd].flags & FILE_READ) == 0)
8384 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8385 emacs_abort ();
8388 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8389 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8390 cp->status = STATUS_READ_IN_PROGRESS;
8392 if (fd_info[fd].flags & FILE_PIPE)
8394 rc = _read (fd, &cp->chr, sizeof (char));
8396 /* Give subprocess time to buffer some more output for us before
8397 reporting that input is available; we need this because Windows 95
8398 connects DOS programs to pipes by making the pipe appear to be
8399 the normal console stdout - as a result most DOS programs will
8400 write to stdout without buffering, ie. one character at a
8401 time. Even some W32 programs do this - "dir" in a command
8402 shell on NT is very slow if we don't do this. */
8403 if (rc > 0)
8405 int wait = w32_pipe_read_delay;
8407 if (wait > 0)
8408 Sleep (wait);
8409 else if (wait < 0)
8410 while (++wait <= 0)
8411 /* Yield remainder of our time slice, effectively giving a
8412 temporary priority boost to the child process. */
8413 Sleep (0);
8416 else if (fd_info[fd].flags & FILE_SERIAL)
8418 HANDLE hnd = fd_info[fd].hnd;
8419 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8420 COMMTIMEOUTS ct;
8422 /* Configure timeouts for blocking read. */
8423 if (!GetCommTimeouts (hnd, &ct))
8425 cp->status = STATUS_READ_ERROR;
8426 return STATUS_READ_ERROR;
8428 ct.ReadIntervalTimeout = 0;
8429 ct.ReadTotalTimeoutMultiplier = 0;
8430 ct.ReadTotalTimeoutConstant = 0;
8431 if (!SetCommTimeouts (hnd, &ct))
8433 cp->status = STATUS_READ_ERROR;
8434 return STATUS_READ_ERROR;
8437 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8439 if (GetLastError () != ERROR_IO_PENDING)
8441 cp->status = STATUS_READ_ERROR;
8442 return STATUS_READ_ERROR;
8444 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8446 cp->status = STATUS_READ_ERROR;
8447 return STATUS_READ_ERROR;
8451 else if (fd_info[fd].flags & FILE_SOCKET)
8453 unsigned long nblock = 0;
8454 /* We always want this to block, so temporarily disable NDELAY. */
8455 if (fd_info[fd].flags & FILE_NDELAY)
8456 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8458 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8460 if (fd_info[fd].flags & FILE_NDELAY)
8462 nblock = 1;
8463 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8467 if (rc == sizeof (char))
8468 cp->status = STATUS_READ_SUCCEEDED;
8469 else
8470 cp->status = STATUS_READ_FAILED;
8472 return cp->status;
8476 _sys_wait_accept (int fd)
8478 HANDLE hEv;
8479 child_process * cp;
8480 int rc;
8482 if (fd < 0 || fd >= MAXDESC)
8483 return STATUS_READ_ERROR;
8485 cp = fd_info[fd].cp;
8487 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8488 return STATUS_READ_ERROR;
8490 cp->status = STATUS_READ_FAILED;
8492 hEv = pfn_WSACreateEvent ();
8493 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8494 if (rc != SOCKET_ERROR)
8496 do {
8497 rc = WaitForSingleObject (hEv, 500);
8498 Sleep (5);
8499 } while (rc == WAIT_TIMEOUT
8500 && cp->status != STATUS_READ_ERROR
8501 && cp->char_avail);
8502 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8503 if (rc == WAIT_OBJECT_0)
8504 cp->status = STATUS_READ_SUCCEEDED;
8506 pfn_WSACloseEvent (hEv);
8508 return cp->status;
8512 _sys_wait_connect (int fd)
8514 HANDLE hEv;
8515 child_process * cp;
8516 int rc;
8518 if (fd < 0 || fd >= MAXDESC)
8519 return STATUS_READ_ERROR;
8521 cp = fd_info[fd].cp;
8522 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8523 return STATUS_READ_ERROR;
8525 cp->status = STATUS_READ_FAILED;
8527 hEv = pfn_WSACreateEvent ();
8528 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8529 if (rc != SOCKET_ERROR)
8531 do {
8532 rc = WaitForSingleObject (hEv, 500);
8533 Sleep (5);
8534 } while (rc == WAIT_TIMEOUT
8535 && cp->status != STATUS_READ_ERROR
8536 && cp->char_avail);
8537 if (rc == WAIT_OBJECT_0)
8539 /* We've got an event, but it could be a successful
8540 connection, or it could be a failure. Find out
8541 which one is it. */
8542 WSANETWORKEVENTS events;
8544 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8545 if ((events.lNetworkEvents & FD_CONNECT) != 0
8546 && events.iErrorCode[FD_CONNECT_BIT])
8548 cp->status = STATUS_CONNECT_FAILED;
8549 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8551 else
8553 cp->status = STATUS_READ_SUCCEEDED;
8554 cp->errcode = 0;
8557 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8559 else
8560 pfn_WSACloseEvent (hEv);
8562 return cp->status;
8566 sys_read (int fd, char * buffer, unsigned int count)
8568 int nchars;
8569 int to_read;
8570 DWORD waiting;
8571 char * orig_buffer = buffer;
8573 if (fd < 0)
8575 errno = EBADF;
8576 return -1;
8579 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8581 child_process *cp = fd_info[fd].cp;
8583 if ((fd_info[fd].flags & FILE_READ) == 0)
8585 errno = EBADF;
8586 return -1;
8589 nchars = 0;
8591 /* re-read CR carried over from last read */
8592 if (fd_info[fd].flags & FILE_LAST_CR)
8594 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8595 *buffer++ = 0x0d;
8596 count--;
8597 nchars++;
8598 fd_info[fd].flags &= ~FILE_LAST_CR;
8601 /* presence of a child_process structure means we are operating in
8602 non-blocking mode - otherwise we just call _read directly.
8603 Note that the child_process structure might be missing because
8604 reap_subprocess has been called; in this case the pipe is
8605 already broken, so calling _read on it is okay. */
8606 if (cp)
8608 int current_status = cp->status;
8610 switch (current_status)
8612 case STATUS_READ_FAILED:
8613 case STATUS_READ_ERROR:
8614 /* report normal EOF if nothing in buffer */
8615 if (nchars <= 0)
8616 fd_info[fd].flags |= FILE_AT_EOF;
8617 return nchars;
8619 case STATUS_READ_READY:
8620 case STATUS_READ_IN_PROGRESS:
8621 #if 0
8622 /* This happens all the time during GnuTLS handshake
8623 with the remote, evidently because GnuTLS waits for
8624 the read to complete by retrying the read operation
8625 upon EAGAIN. So I'm disabling the DebPrint to avoid
8626 wasting cycles on something that is not a real
8627 problem. Enable if you need to debug something that
8628 bumps into this. */
8629 DebPrint (("sys_read called when read is in progress %d\n",
8630 current_status));
8631 #endif
8632 errno = EWOULDBLOCK;
8633 return -1;
8635 case STATUS_READ_SUCCEEDED:
8636 /* consume read-ahead char */
8637 *buffer++ = cp->chr;
8638 count--;
8639 nchars++;
8640 cp->status = STATUS_READ_ACKNOWLEDGED;
8641 ResetEvent (cp->char_avail);
8643 case STATUS_READ_ACKNOWLEDGED:
8644 case STATUS_CONNECT_FAILED:
8645 break;
8647 default:
8648 DebPrint (("sys_read: bad status %d\n", current_status));
8649 errno = EBADF;
8650 return -1;
8653 if (fd_info[fd].flags & FILE_PIPE)
8655 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8656 to_read = min (waiting, (DWORD) count);
8658 if (to_read > 0)
8659 nchars += _read (fd, buffer, to_read);
8661 else if (fd_info[fd].flags & FILE_SERIAL)
8663 HANDLE hnd = fd_info[fd].hnd;
8664 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8665 int rc = 0;
8666 COMMTIMEOUTS ct;
8668 if (count > 0)
8670 /* Configure timeouts for non-blocking read. */
8671 if (!GetCommTimeouts (hnd, &ct))
8673 errno = EIO;
8674 return -1;
8676 ct.ReadIntervalTimeout = MAXDWORD;
8677 ct.ReadTotalTimeoutMultiplier = 0;
8678 ct.ReadTotalTimeoutConstant = 0;
8679 if (!SetCommTimeouts (hnd, &ct))
8681 errno = EIO;
8682 return -1;
8685 if (!ResetEvent (ovl->hEvent))
8687 errno = EIO;
8688 return -1;
8690 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8692 if (GetLastError () != ERROR_IO_PENDING)
8694 errno = EIO;
8695 return -1;
8697 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8699 errno = EIO;
8700 return -1;
8703 nchars += rc;
8706 else /* FILE_SOCKET */
8708 if (winsock_lib == NULL) emacs_abort ();
8710 /* When a non-blocking 'connect' call fails,
8711 wait_reading_process_output detects this by calling
8712 'getpeername', and then attempts to obtain the connection
8713 error code by trying to read 1 byte from the socket. If
8714 we try to serve that read by calling 'recv' below, the
8715 error we get is a generic WSAENOTCONN, not the actual
8716 connection error. So instead, we use the actual error
8717 code stashed by '_sys_wait_connect' in cp->errcode.
8718 Alternatively, we could have used 'getsockopt', like on
8719 GNU/Linux, but: (a) I have no idea whether the winsock
8720 version could hang, as it does "on some systems" (see the
8721 comment in process.c); and (b) 'getsockopt' on Windows is
8722 documented to clear the socket error for the entire
8723 process, which I'm not sure is TRT; FIXME. */
8724 if (current_status == STATUS_CONNECT_FAILED
8725 && (fd_info[fd].flags & FILE_CONNECT) != 0
8726 && cp->errcode != 0)
8728 pfn_WSASetLastError (cp->errcode);
8729 set_errno ();
8730 return -1;
8732 /* Do the equivalent of a non-blocking read. */
8733 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8734 if (waiting == 0 && nchars == 0)
8736 errno = EWOULDBLOCK;
8737 return -1;
8740 if (waiting)
8742 /* always use binary mode for sockets */
8743 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8744 if (res == SOCKET_ERROR)
8746 set_errno ();
8747 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8748 errno, SOCK_HANDLE (fd)));
8749 return -1;
8751 nchars += res;
8755 else
8757 int nread = _read (fd, buffer, count);
8758 if (nread >= 0)
8759 nchars += nread;
8760 else if (nchars == 0)
8761 nchars = nread;
8764 if (nchars <= 0)
8765 fd_info[fd].flags |= FILE_AT_EOF;
8766 /* Perform text mode translation if required. */
8767 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8769 nchars = crlf_to_lf (nchars, orig_buffer);
8770 /* If buffer contains only CR, return that. To be absolutely
8771 sure we should attempt to read the next char, but in
8772 practice a CR to be followed by LF would not appear by
8773 itself in the buffer. */
8774 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8776 fd_info[fd].flags |= FILE_LAST_CR;
8777 nchars--;
8781 else
8782 nchars = _read (fd, buffer, count);
8784 return nchars;
8787 /* From w32xfns.c */
8788 extern HANDLE interrupt_handle;
8791 sys_write (int fd, const void * buffer, unsigned int count)
8793 int nchars;
8794 USE_SAFE_ALLOCA;
8796 if (fd < 0)
8798 errno = EBADF;
8799 return -1;
8802 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8804 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8806 errno = EBADF;
8807 return -1;
8810 /* Perform text mode translation if required. */
8811 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8813 char * tmpbuf;
8814 const unsigned char * src = buffer;
8815 unsigned char * dst;
8816 int nbytes = count;
8818 SAFE_NALLOCA (tmpbuf, 2, count);
8819 dst = (unsigned char *)tmpbuf;
8821 while (1)
8823 unsigned char *next;
8824 /* Copy next line or remaining bytes. */
8825 next = _memccpy (dst, src, '\n', nbytes);
8826 if (next)
8828 /* Copied one line ending with '\n'. */
8829 int copied = next - dst;
8830 nbytes -= copied;
8831 src += copied;
8832 /* Insert '\r' before '\n'. */
8833 next[-1] = '\r';
8834 next[0] = '\n';
8835 dst = next + 1;
8836 count++;
8838 else
8839 /* Copied remaining partial line -> now finished. */
8840 break;
8842 buffer = tmpbuf;
8846 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8848 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8849 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8850 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8851 DWORD active = 0;
8853 /* This is async (a.k.a. "overlapped") I/O, so the return value
8854 of FALSE from WriteFile means either an error or the output
8855 will be completed asynchronously (ERROR_IO_PENDING). */
8856 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8858 if (GetLastError () != ERROR_IO_PENDING)
8860 errno = EIO;
8861 nchars = -1;
8863 else
8865 /* Wait for the write to complete, and watch C-g while
8866 at that. */
8867 if (detect_input_pending ())
8868 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8869 INFINITE, QS_ALLINPUT);
8870 else
8871 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8872 switch (active)
8874 case WAIT_OBJECT_0:
8875 /* User pressed C-g, cancel write, then leave.
8876 Don't bother cleaning up as we may only get stuck
8877 in buggy drivers. */
8878 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8879 CancelIo (hnd);
8880 errno = EIO; /* Why not EINTR? */
8881 nchars = -1;
8882 break;
8883 case WAIT_OBJECT_0 + 1:
8884 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8886 errno = EIO;
8887 nchars = -1;
8889 break;
8894 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8896 unsigned long nblock = 0;
8897 if (winsock_lib == NULL) emacs_abort ();
8899 child_process *cp = fd_info[fd].cp;
8901 /* If this is a non-blocking socket whose connection is in
8902 progress or terminated with an error already, return the
8903 proper error code to the caller. */
8904 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8906 /* In case connection is in progress, ENOTCONN that would
8907 result from calling pfn_send is not what callers expect. */
8908 if (cp->status != STATUS_CONNECT_FAILED)
8910 errno = EWOULDBLOCK;
8911 return -1;
8913 /* In case connection failed, use the actual error code
8914 stashed by '_sys_wait_connect' in cp->errcode. */
8915 else if (cp->errcode != 0)
8917 pfn_WSASetLastError (cp->errcode);
8918 set_errno ();
8919 return -1;
8923 /* TODO: implement select() properly so non-blocking I/O works. */
8924 /* For now, make sure the write blocks. */
8925 if (fd_info[fd].flags & FILE_NDELAY)
8926 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8928 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8930 if (nchars == SOCKET_ERROR)
8932 set_errno ();
8933 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8934 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8937 /* Set the socket back to non-blocking if it was before,
8938 for other operations that support it. */
8939 if (fd_info[fd].flags & FILE_NDELAY)
8941 nblock = 1;
8942 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8945 else
8947 /* Some networked filesystems don't like too large writes, so
8948 break them into smaller chunks. See the Comments section of
8949 the MSDN documentation of WriteFile for details behind the
8950 choice of the value of CHUNK below. See also the thread
8951 http://thread.gmane.org/gmane.comp.version-control.git/145294
8952 in the git mailing list. */
8953 const unsigned char *p = buffer;
8954 const bool is_pipe = (fd < MAXDESC
8955 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8956 == (FILE_PIPE | FILE_NDELAY)));
8957 /* Some programs, notably Node.js's node.exe, seem to never
8958 completely empty the pipe, so writing more than the size of
8959 the pipe's buffer always returns ENOSPC, and we loop forever
8960 between send_process and here. As a workaround, write no
8961 more than the pipe's buffer can hold. */
8962 DWORD pipe_buffer_size;
8963 if (is_pipe)
8965 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8966 NULL, &pipe_buffer_size, NULL, NULL))
8968 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8969 pipe_buffer_size = 4096;
8972 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8974 nchars = 0;
8975 errno = 0;
8976 while (count > 0)
8978 unsigned this_chunk = count < chunk ? count : chunk;
8979 int n = _write (fd, p, this_chunk);
8981 if (n > 0)
8982 nchars += n;
8983 if (n < 0)
8985 /* When there's no buffer space in a pipe that is in the
8986 non-blocking mode, _write returns ENOSPC. We return
8987 EAGAIN instead, which should trigger the logic in
8988 send_process that enters waiting loop and calls
8989 wait_reading_process_output to allow process input to
8990 be accepted during the wait. Those calls to
8991 wait_reading_process_output allow sys_select to
8992 notice when process input becomes available, thus
8993 avoiding deadlock whereby each side of the pipe is
8994 blocked on write, waiting for the other party to read
8995 its end of the pipe. */
8996 if (errno == ENOSPC && is_pipe)
8997 errno = EAGAIN;
8998 if (nchars == 0)
8999 nchars = -1;
9000 break;
9002 else if (n < this_chunk)
9003 break;
9004 count -= n;
9005 p += n;
9009 SAFE_FREE ();
9010 return nchars;
9014 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
9016 /* Return information about network interface IFNAME, or about all
9017 interfaces (if IFNAME is nil). */
9018 static Lisp_Object
9019 network_interface_get_info (Lisp_Object ifname)
9021 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
9022 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
9023 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
9024 Lisp_Object res = Qnil;
9026 if (retval == ERROR_BUFFER_OVERFLOW)
9028 ainfo = xrealloc (ainfo, ainfo_len);
9029 retval = get_adapters_info (ainfo, &ainfo_len);
9032 if (retval == ERROR_SUCCESS)
9034 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
9035 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
9036 int if_num;
9037 struct sockaddr_in sa;
9039 /* For the below, we need some winsock functions, so make sure
9040 the winsock DLL is loaded. If we cannot successfully load
9041 it, they will have no use of the information we provide,
9042 anyway, so punt. */
9043 if (!winsock_lib && !init_winsock (1))
9044 goto done;
9046 for (adapter = ainfo; adapter; adapter = adapter->Next)
9048 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
9049 u_long ip_addr;
9050 /* Present Unix-compatible interface names, instead of the
9051 Windows names, which are really GUIDs not readable by
9052 humans. */
9053 static const char *ifmt[] = {
9054 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
9055 "lo", "ifx%d"
9057 enum {
9058 NONE = -1,
9059 ETHERNET = 0,
9060 TOKENRING = 1,
9061 FDDI = 2,
9062 PPP = 3,
9063 SLIP = 4,
9064 WLAN = 5,
9065 LOOPBACK = 6,
9066 OTHER_IF = 7
9067 } ifmt_idx;
9069 switch (adapter->Type)
9071 case MIB_IF_TYPE_ETHERNET:
9072 /* Windows before Vista reports wireless adapters as
9073 Ethernet. Work around by looking at the Description
9074 string. */
9075 if (strstr (adapter->Description, "Wireless "))
9077 ifmt_idx = WLAN;
9078 if_num = wlan_count++;
9080 else
9082 ifmt_idx = ETHERNET;
9083 if_num = eth_count++;
9085 break;
9086 case MIB_IF_TYPE_TOKENRING:
9087 ifmt_idx = TOKENRING;
9088 if_num = tr_count++;
9089 break;
9090 case MIB_IF_TYPE_FDDI:
9091 ifmt_idx = FDDI;
9092 if_num = fddi_count++;
9093 break;
9094 case MIB_IF_TYPE_PPP:
9095 ifmt_idx = PPP;
9096 if_num = ppp_count++;
9097 break;
9098 case MIB_IF_TYPE_SLIP:
9099 ifmt_idx = SLIP;
9100 if_num = sl_count++;
9101 break;
9102 case IF_TYPE_IEEE80211:
9103 ifmt_idx = WLAN;
9104 if_num = wlan_count++;
9105 break;
9106 case MIB_IF_TYPE_LOOPBACK:
9107 if (lo_count < 0)
9109 ifmt_idx = LOOPBACK;
9110 if_num = lo_count++;
9112 else
9113 ifmt_idx = NONE;
9114 break;
9115 default:
9116 ifmt_idx = OTHER_IF;
9117 if_num = ifx_count++;
9118 break;
9120 if (ifmt_idx == NONE)
9121 continue;
9122 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9124 sa.sin_family = AF_INET;
9125 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9126 if (ip_addr == INADDR_NONE)
9128 /* Bogus address, skip this interface. */
9129 continue;
9131 sa.sin_addr.s_addr = ip_addr;
9132 sa.sin_port = 0;
9133 if (NILP (ifname))
9134 res = Fcons (Fcons (build_string (namebuf),
9135 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9136 sizeof (struct sockaddr))),
9137 res);
9138 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9140 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9141 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9142 Lisp_Object flags = Qnil;
9143 int n;
9144 u_long net_mask;
9146 /* Flags. We guess most of them by type, since the
9147 Windows flags are different and hard to get by. */
9148 flags = Fcons (intern ("up"), flags);
9149 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9151 flags = Fcons (intern ("broadcast"), flags);
9152 flags = Fcons (intern ("multicast"), flags);
9154 flags = Fcons (intern ("running"), flags);
9155 if (ifmt_idx == PPP)
9157 flags = Fcons (intern ("pointopoint"), flags);
9158 flags = Fcons (intern ("noarp"), flags);
9160 if (adapter->HaveWins)
9161 flags = Fcons (intern ("WINS"), flags);
9162 if (adapter->DhcpEnabled)
9163 flags = Fcons (intern ("dynamic"), flags);
9165 res = Fcons (flags, res);
9167 /* Hardware address and its family. */
9168 for (n = 0; n < adapter->AddressLength; n++)
9169 p->contents[n] = make_number ((int) adapter->Address[n]);
9170 /* Windows does not support AF_LINK or AF_PACKET family
9171 of addresses. Use an arbitrary family number that is
9172 identical to what GNU/Linux returns. */
9173 res = Fcons (Fcons (make_number (1), hwaddr), res);
9175 /* Network mask. */
9176 sa.sin_family = AF_INET;
9177 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9178 if (net_mask != INADDR_NONE)
9180 sa.sin_addr.s_addr = net_mask;
9181 sa.sin_port = 0;
9182 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9183 sizeof (struct sockaddr)),
9184 res);
9186 else
9187 res = Fcons (Qnil, res);
9189 sa.sin_family = AF_INET;
9190 if (ip_addr != INADDR_NONE)
9192 /* Broadcast address is only reported by
9193 GetAdaptersAddresses, which is of limited
9194 availability. Generate it on our own. */
9195 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9197 sa.sin_addr.s_addr = bcast_addr;
9198 sa.sin_port = 0;
9199 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9200 sizeof (struct sockaddr)),
9201 res);
9203 /* IP address. */
9204 sa.sin_addr.s_addr = ip_addr;
9205 sa.sin_port = 0;
9206 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9207 sizeof (struct sockaddr)),
9208 res);
9210 else
9211 res = Fcons (Qnil, Fcons (Qnil, res));
9214 /* GetAdaptersInfo is documented to not report loopback
9215 interfaces, so we generate one out of thin air. */
9216 if (!lo_count)
9218 sa.sin_family = AF_INET;
9219 sa.sin_port = 0;
9220 if (NILP (ifname))
9222 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9223 res = Fcons (Fcons (build_string ("lo"),
9224 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9225 sizeof (struct sockaddr))),
9226 res);
9228 else if (strcmp (SSDATA (ifname), "lo") == 0)
9230 res = Fcons (Fcons (intern ("running"),
9231 Fcons (intern ("loopback"),
9232 Fcons (intern ("up"), Qnil))), Qnil);
9233 /* 772 is what 3 different GNU/Linux systems report for
9234 the loopback interface. */
9235 res = Fcons (Fcons (make_number (772),
9236 Fmake_vector (make_number (6),
9237 make_number (0))),
9238 res);
9239 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9240 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9241 sizeof (struct sockaddr)),
9242 res);
9243 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
9244 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9245 sizeof (struct sockaddr)),
9246 res);
9247 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9248 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9249 sizeof (struct sockaddr)),
9250 res);
9256 done:
9257 xfree (ainfo);
9258 return res;
9261 Lisp_Object
9262 network_interface_list (void)
9264 return network_interface_get_info (Qnil);
9267 Lisp_Object
9268 network_interface_info (Lisp_Object ifname)
9270 CHECK_STRING (ifname);
9271 return network_interface_get_info (ifname);
9275 /* The Windows CRT functions are "optimized for speed", so they don't
9276 check for timezone and DST changes if they were last called less
9277 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9278 all Emacs features that repeatedly call time functions (e.g.,
9279 display-time) are in real danger of missing timezone and DST
9280 changes. Calling tzset before each localtime call fixes that. */
9281 struct tm *
9282 sys_localtime (const time_t *t)
9284 tzset ();
9285 return localtime (t);
9290 /* Try loading LIBRARY_ID from the file(s) specified in
9291 Vdynamic_library_alist. If the library is loaded successfully,
9292 return the handle of the DLL, and record the filename in the
9293 property :loaded-from of LIBRARY_ID. If the library could not be
9294 found, or when it was already loaded (because the handle is not
9295 recorded anywhere, and so is lost after use), return NULL.
9297 We could also save the handle in :loaded-from, but currently
9298 there's no use case for it. */
9299 HMODULE
9300 w32_delayed_load (Lisp_Object library_id)
9302 HMODULE dll_handle = NULL;
9304 CHECK_SYMBOL (library_id);
9306 if (CONSP (Vdynamic_library_alist)
9307 && NILP (Fassq (library_id, Vlibrary_cache)))
9309 Lisp_Object found = Qnil;
9310 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9312 if (CONSP (dlls))
9313 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9315 Lisp_Object dll = XCAR (dlls);
9316 char name[MAX_UTF8_PATH];
9317 DWORD res = -1;
9319 CHECK_STRING (dll);
9320 dll = ENCODE_FILE (dll);
9321 if (w32_unicode_filenames)
9323 wchar_t name_w[MAX_PATH];
9325 filename_to_utf16 (SSDATA (dll), name_w);
9326 dll_handle = LoadLibraryW (name_w);
9327 if (dll_handle)
9329 res = GetModuleFileNameW (dll_handle, name_w,
9330 sizeof (name_w));
9331 if (res > 0)
9332 filename_from_utf16 (name_w, name);
9335 else
9337 char name_a[MAX_PATH];
9339 filename_to_ansi (SSDATA (dll), name_a);
9340 dll_handle = LoadLibraryA (name_a);
9341 if (dll_handle)
9343 res = GetModuleFileNameA (dll_handle, name_a,
9344 sizeof (name_a));
9345 if (res > 0)
9346 filename_from_ansi (name_a, name);
9349 if (dll_handle)
9351 ptrdiff_t len = strlen (name);
9352 found = Fcons (dll,
9353 (res > 0)
9354 /* Possibly truncated */
9355 ? make_specified_string (name, -1, len, 1)
9356 : Qnil);
9357 /* This prevents thread start and end notifications
9358 from being sent to the DLL, for every thread we
9359 start. We don't need those notifications because
9360 threads we create never use any of these DLLs, only
9361 the main thread uses them. This is supposed to
9362 speed up thread creation. */
9363 DisableThreadLibraryCalls (dll_handle);
9364 break;
9368 Fput (library_id, QCloaded_from, found);
9371 return dll_handle;
9375 void
9376 check_windows_init_file (void)
9378 /* A common indication that Emacs is not installed properly is when
9379 it cannot find the Windows installation file. If this file does
9380 not exist in the expected place, tell the user. */
9382 if (!noninteractive && !inhibit_window_system
9383 /* Vload_path is not yet initialized when we are loading
9384 loadup.el. */
9385 && NILP (Vpurify_flag))
9387 Lisp_Object init_file;
9388 int fd;
9390 /* Implementation note: this function runs early during Emacs
9391 startup, before startup.el is run. So Vload_path is still in
9392 its initial unibyte form, but it holds UTF-8 encoded file
9393 names, since init_callproc was already called. So we do not
9394 need to ENCODE_FILE here, but we do need to convert the file
9395 names from UTF-8 to ANSI. */
9396 init_file = build_string ("term/w32-win");
9397 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9398 if (fd < 0)
9400 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9401 char *init_file_name = SSDATA (init_file);
9402 char *load_path = SSDATA (load_path_print);
9403 char *buffer = alloca (1024
9404 + strlen (init_file_name)
9405 + strlen (load_path));
9406 char *msg = buffer;
9407 int needed;
9409 sprintf (buffer,
9410 "The Emacs Windows initialization file \"%s.el\" "
9411 "could not be found in your Emacs installation. "
9412 "Emacs checked the following directories for this file:\n"
9413 "\n%s\n\n"
9414 "When Emacs cannot find this file, it usually means that it "
9415 "was not installed properly, or its distribution file was "
9416 "not unpacked properly.\nSee the README.W32 file in the "
9417 "top-level Emacs directory for more information.",
9418 init_file_name, load_path);
9419 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9420 buffer, -1, NULL, 0);
9421 if (needed > 0)
9423 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9425 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9426 -1, msg_w, needed);
9427 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9428 NULL, 0, NULL, NULL);
9429 if (needed > 0)
9431 char *msg_a = alloca (needed + 1);
9433 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9434 NULL, NULL);
9435 msg = msg_a;
9438 MessageBox (NULL,
9439 msg,
9440 "Emacs Abort Dialog",
9441 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9442 /* Use the low-level system abort. */
9443 abort ();
9445 else
9447 _close (fd);
9452 void
9453 term_ntproc (int ignored)
9455 (void)ignored;
9457 term_timers ();
9459 /* shutdown the socket interface if necessary */
9460 term_winsock ();
9462 term_w32select ();
9465 void
9466 init_ntproc (int dumping)
9468 sigset_t initial_mask = 0;
9470 /* Initialize the socket interface now if available and requested by
9471 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9472 delayed until open-network-stream is called (w32-has-winsock can
9473 also be used to dynamically load or reload winsock).
9475 Conveniently, init_environment is called before us, so
9476 PRELOAD_WINSOCK can be set in the registry. */
9478 /* Always initialize this correctly. */
9479 winsock_lib = NULL;
9481 if (getenv ("PRELOAD_WINSOCK") != NULL)
9482 init_winsock (TRUE);
9484 /* Initial preparation for subprocess support: replace our standard
9485 handles with non-inheritable versions. */
9487 HANDLE parent;
9488 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9489 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9490 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9492 parent = GetCurrentProcess ();
9494 /* ignore errors when duplicating and closing; typically the
9495 handles will be invalid when running as a gui program. */
9496 DuplicateHandle (parent,
9497 GetStdHandle (STD_INPUT_HANDLE),
9498 parent,
9499 &stdin_save,
9501 FALSE,
9502 DUPLICATE_SAME_ACCESS);
9504 DuplicateHandle (parent,
9505 GetStdHandle (STD_OUTPUT_HANDLE),
9506 parent,
9507 &stdout_save,
9509 FALSE,
9510 DUPLICATE_SAME_ACCESS);
9512 DuplicateHandle (parent,
9513 GetStdHandle (STD_ERROR_HANDLE),
9514 parent,
9515 &stderr_save,
9517 FALSE,
9518 DUPLICATE_SAME_ACCESS);
9520 fclose (stdin);
9521 fclose (stdout);
9522 fclose (stderr);
9524 if (stdin_save != INVALID_HANDLE_VALUE)
9525 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9526 else
9527 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9528 _fdopen (0, "r");
9530 if (stdout_save != INVALID_HANDLE_VALUE)
9531 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9532 else
9533 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9534 _fdopen (1, "w");
9536 if (stderr_save != INVALID_HANDLE_VALUE)
9537 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9538 else
9539 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9540 _fdopen (2, "w");
9543 /* unfortunately, atexit depends on implementation of malloc */
9544 /* atexit (term_ntproc); */
9545 if (!dumping)
9547 /* Make sure we start with all signals unblocked. */
9548 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9549 signal (SIGABRT, term_ntproc);
9551 init_timers ();
9553 /* determine which drives are fixed, for GetCachedVolumeInformation */
9555 /* GetDriveType must have trailing backslash. */
9556 char drive[] = "A:\\";
9558 /* Loop over all possible drive letters */
9559 while (*drive <= 'Z')
9561 /* Record if this drive letter refers to a fixed drive. */
9562 fixed_drives[DRIVE_INDEX (*drive)] =
9563 (GetDriveType (drive) == DRIVE_FIXED);
9565 (*drive)++;
9568 /* Reset the volume info cache. */
9569 volume_cache = NULL;
9574 shutdown_handler ensures that buffers' autosave files are
9575 up to date when the user logs off, or the system shuts down.
9577 static BOOL WINAPI
9578 shutdown_handler (DWORD type)
9580 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9581 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9582 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9583 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9585 /* Shut down cleanly, making sure autosave files are up to date. */
9586 shut_down_emacs (0, Qnil);
9589 /* Allow other handlers to handle this signal. */
9590 return FALSE;
9593 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9594 NT, return a handle to GDI32.DLL. */
9595 HANDLE
9596 maybe_load_unicows_dll (void)
9598 if (os_subtype == OS_9X)
9600 HANDLE ret = LoadLibrary ("Unicows.dll");
9601 if (ret)
9603 /* These two functions are present on Windows 9X as stubs
9604 that always fail. We need the real implementations from
9605 UNICOWS.DLL, so we must call these functions through
9606 pointers, and assign the correct addresses to these
9607 pointers at program startup (see emacs.c, which calls
9608 this function early on). */
9609 pMultiByteToWideChar =
9610 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9611 pWideCharToMultiByte =
9612 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9613 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9614 return ret;
9616 else
9618 int button;
9620 button = MessageBox (NULL,
9621 "Emacs cannot load the UNICOWS.DLL library.\n"
9622 "This library is essential for using Emacs\n"
9623 "on this system. You need to install it.\n\n"
9624 "Emacs will exit when you click OK.",
9625 "Emacs cannot load UNICOWS.DLL",
9626 MB_ICONERROR | MB_TASKMODAL
9627 | MB_SETFOREGROUND | MB_OK);
9628 switch (button)
9630 case IDOK:
9631 default:
9632 exit (1);
9636 else
9638 /* On NT family of Windows, these two functions are always
9639 linked in, so we just assign their addresses to the 2
9640 pointers; no need for the LoadLibrary dance. */
9641 pMultiByteToWideChar = MultiByteToWideChar;
9642 pWideCharToMultiByte = WideCharToMultiByte;
9643 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9644 if (w32_major_version < 5)
9645 multiByteToWideCharFlags = 0;
9646 else
9647 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9648 return LoadLibrary ("Gdi32.dll");
9653 globals_of_w32 is used to initialize those global variables that
9654 must always be initialized on startup even when the global variable
9655 initialized is non zero (see the function main in emacs.c).
9657 void
9658 globals_of_w32 (void)
9660 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9662 get_process_times_fn = (GetProcessTimes_Proc)
9663 GetProcAddress (kernel32, "GetProcessTimes");
9665 DEFSYM (QCloaded_from, ":loaded-from");
9667 g_b_init_is_windows_9x = 0;
9668 g_b_init_open_process_token = 0;
9669 g_b_init_get_token_information = 0;
9670 g_b_init_lookup_account_sid = 0;
9671 g_b_init_get_sid_sub_authority = 0;
9672 g_b_init_get_sid_sub_authority_count = 0;
9673 g_b_init_get_security_info = 0;
9674 g_b_init_get_file_security_w = 0;
9675 g_b_init_get_file_security_a = 0;
9676 g_b_init_get_security_descriptor_owner = 0;
9677 g_b_init_get_security_descriptor_group = 0;
9678 g_b_init_is_valid_sid = 0;
9679 g_b_init_create_toolhelp32_snapshot = 0;
9680 g_b_init_process32_first = 0;
9681 g_b_init_process32_next = 0;
9682 g_b_init_open_thread_token = 0;
9683 g_b_init_impersonate_self = 0;
9684 g_b_init_revert_to_self = 0;
9685 g_b_init_get_process_memory_info = 0;
9686 g_b_init_get_process_working_set_size = 0;
9687 g_b_init_global_memory_status = 0;
9688 g_b_init_global_memory_status_ex = 0;
9689 g_b_init_equal_sid = 0;
9690 g_b_init_copy_sid = 0;
9691 g_b_init_get_length_sid = 0;
9692 g_b_init_get_native_system_info = 0;
9693 g_b_init_get_system_times = 0;
9694 g_b_init_create_symbolic_link_w = 0;
9695 g_b_init_create_symbolic_link_a = 0;
9696 g_b_init_get_security_descriptor_dacl = 0;
9697 g_b_init_convert_sd_to_sddl = 0;
9698 g_b_init_convert_sddl_to_sd = 0;
9699 g_b_init_is_valid_security_descriptor = 0;
9700 g_b_init_set_file_security_w = 0;
9701 g_b_init_set_file_security_a = 0;
9702 g_b_init_set_named_security_info_w = 0;
9703 g_b_init_set_named_security_info_a = 0;
9704 g_b_init_get_adapters_info = 0;
9705 g_b_init_compare_string_w = 0;
9706 g_b_init_debug_break_process = 0;
9707 num_of_processors = 0;
9708 /* The following sets a handler for shutdown notifications for
9709 console apps. This actually applies to Emacs in both console and
9710 GUI modes, since we had to fool windows into thinking emacs is a
9711 console application to get console mode to work. */
9712 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9714 /* "None" is the default group name on standalone workstations. */
9715 strcpy (dflt_group_name, "None");
9717 /* Reset, in case it has some value inherited from dump time. */
9718 w32_stat_get_owner_group = 0;
9720 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9721 (a.k.a. "wide") APIs to invoke functions that accept file
9722 names. */
9723 if (is_windows_9x ())
9724 w32_unicode_filenames = 0;
9725 else
9726 w32_unicode_filenames = 1;
9728 #ifdef HAVE_MODULES
9729 dynlib_reset_last_error ();
9730 #endif
9732 w32_crypto_hprov = (HCRYPTPROV)0;
9735 /* For make-serial-process */
9737 serial_open (Lisp_Object port_obj)
9739 char *port = SSDATA (port_obj);
9740 HANDLE hnd;
9741 child_process *cp;
9742 int fd = -1;
9744 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9745 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9746 if (hnd == INVALID_HANDLE_VALUE)
9747 error ("Could not open %s", port);
9748 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9749 if (fd == -1)
9750 error ("Could not open %s", port);
9752 cp = new_child ();
9753 if (!cp)
9754 error ("Could not create child process");
9755 cp->fd = fd;
9756 cp->status = STATUS_READ_ACKNOWLEDGED;
9757 fd_info[ fd ].hnd = hnd;
9758 fd_info[ fd ].flags |=
9759 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9760 if (fd_info[ fd ].cp != NULL)
9762 error ("fd_info[fd = %d] is already in use", fd);
9764 fd_info[ fd ].cp = cp;
9765 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9766 if (cp->ovl_read.hEvent == NULL)
9767 error ("Could not create read event");
9768 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9769 if (cp->ovl_write.hEvent == NULL)
9770 error ("Could not create write event");
9772 return fd;
9775 /* For serial-process-configure */
9776 void
9777 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9779 Lisp_Object childp2 = Qnil;
9780 Lisp_Object tem = Qnil;
9781 HANDLE hnd;
9782 DCB dcb;
9783 COMMTIMEOUTS ct;
9784 char summary[4] = "???"; /* This usually becomes "8N1". */
9786 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9787 error ("Not a serial process");
9788 hnd = fd_info[ p->outfd ].hnd;
9790 childp2 = Fcopy_sequence (p->childp);
9792 /* Initialize timeouts for blocking read and blocking write. */
9793 if (!GetCommTimeouts (hnd, &ct))
9794 error ("GetCommTimeouts() failed");
9795 ct.ReadIntervalTimeout = 0;
9796 ct.ReadTotalTimeoutMultiplier = 0;
9797 ct.ReadTotalTimeoutConstant = 0;
9798 ct.WriteTotalTimeoutMultiplier = 0;
9799 ct.WriteTotalTimeoutConstant = 0;
9800 if (!SetCommTimeouts (hnd, &ct))
9801 error ("SetCommTimeouts() failed");
9802 /* Read port attributes and prepare default configuration. */
9803 memset (&dcb, 0, sizeof (dcb));
9804 dcb.DCBlength = sizeof (DCB);
9805 if (!GetCommState (hnd, &dcb))
9806 error ("GetCommState() failed");
9807 dcb.fBinary = TRUE;
9808 dcb.fNull = FALSE;
9809 dcb.fAbortOnError = FALSE;
9810 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9811 dcb.ErrorChar = 0;
9812 dcb.EofChar = 0;
9813 dcb.EvtChar = 0;
9815 /* Configure speed. */
9816 if (!NILP (Fplist_member (contact, QCspeed)))
9817 tem = Fplist_get (contact, QCspeed);
9818 else
9819 tem = Fplist_get (p->childp, QCspeed);
9820 CHECK_NUMBER (tem);
9821 dcb.BaudRate = XINT (tem);
9822 childp2 = Fplist_put (childp2, QCspeed, tem);
9824 /* Configure bytesize. */
9825 if (!NILP (Fplist_member (contact, QCbytesize)))
9826 tem = Fplist_get (contact, QCbytesize);
9827 else
9828 tem = Fplist_get (p->childp, QCbytesize);
9829 if (NILP (tem))
9830 tem = make_number (8);
9831 CHECK_NUMBER (tem);
9832 if (XINT (tem) != 7 && XINT (tem) != 8)
9833 error (":bytesize must be nil (8), 7, or 8");
9834 dcb.ByteSize = XINT (tem);
9835 summary[0] = XINT (tem) + '0';
9836 childp2 = Fplist_put (childp2, QCbytesize, tem);
9838 /* Configure parity. */
9839 if (!NILP (Fplist_member (contact, QCparity)))
9840 tem = Fplist_get (contact, QCparity);
9841 else
9842 tem = Fplist_get (p->childp, QCparity);
9843 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9844 error (":parity must be nil (no parity), `even', or `odd'");
9845 dcb.fParity = FALSE;
9846 dcb.Parity = NOPARITY;
9847 dcb.fErrorChar = FALSE;
9848 if (NILP (tem))
9850 summary[1] = 'N';
9852 else if (EQ (tem, Qeven))
9854 summary[1] = 'E';
9855 dcb.fParity = TRUE;
9856 dcb.Parity = EVENPARITY;
9857 dcb.fErrorChar = TRUE;
9859 else if (EQ (tem, Qodd))
9861 summary[1] = 'O';
9862 dcb.fParity = TRUE;
9863 dcb.Parity = ODDPARITY;
9864 dcb.fErrorChar = TRUE;
9866 childp2 = Fplist_put (childp2, QCparity, tem);
9868 /* Configure stopbits. */
9869 if (!NILP (Fplist_member (contact, QCstopbits)))
9870 tem = Fplist_get (contact, QCstopbits);
9871 else
9872 tem = Fplist_get (p->childp, QCstopbits);
9873 if (NILP (tem))
9874 tem = make_number (1);
9875 CHECK_NUMBER (tem);
9876 if (XINT (tem) != 1 && XINT (tem) != 2)
9877 error (":stopbits must be nil (1 stopbit), 1, or 2");
9878 summary[2] = XINT (tem) + '0';
9879 if (XINT (tem) == 1)
9880 dcb.StopBits = ONESTOPBIT;
9881 else if (XINT (tem) == 2)
9882 dcb.StopBits = TWOSTOPBITS;
9883 childp2 = Fplist_put (childp2, QCstopbits, tem);
9885 /* Configure flowcontrol. */
9886 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9887 tem = Fplist_get (contact, QCflowcontrol);
9888 else
9889 tem = Fplist_get (p->childp, QCflowcontrol);
9890 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9891 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9892 dcb.fOutxCtsFlow = FALSE;
9893 dcb.fOutxDsrFlow = FALSE;
9894 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9895 dcb.fDsrSensitivity = FALSE;
9896 dcb.fTXContinueOnXoff = FALSE;
9897 dcb.fOutX = FALSE;
9898 dcb.fInX = FALSE;
9899 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9900 dcb.XonChar = 17; /* Control-Q */
9901 dcb.XoffChar = 19; /* Control-S */
9902 if (NILP (tem))
9904 /* Already configured. */
9906 else if (EQ (tem, Qhw))
9908 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9909 dcb.fOutxCtsFlow = TRUE;
9911 else if (EQ (tem, Qsw))
9913 dcb.fOutX = TRUE;
9914 dcb.fInX = TRUE;
9916 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9918 /* Activate configuration. */
9919 if (!SetCommState (hnd, &dcb))
9920 error ("SetCommState() failed");
9922 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9923 pset_childp (p, childp2);
9926 /* For make-pipe-process */
9927 void
9928 register_aux_fd (int infd)
9930 child_process *cp;
9932 cp = new_child ();
9933 if (!cp)
9934 error ("Could not create child process");
9935 cp->fd = infd;
9936 cp->status = STATUS_READ_ACKNOWLEDGED;
9938 if (fd_info[ infd ].cp != NULL)
9940 error ("fd_info[fd = %d] is already in use", infd);
9942 fd_info[ infd ].cp = cp;
9943 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9946 #ifdef HAVE_GNUTLS
9948 ssize_t
9949 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9951 int n, err;
9952 struct Lisp_Process *process = (struct Lisp_Process *)p;
9953 int fd = process->infd;
9955 n = sys_read (fd, (char*)buf, sz);
9957 if (n >= 0)
9958 return n;
9960 err = errno;
9962 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9963 if (err == EWOULDBLOCK)
9964 err = EAGAIN;
9966 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9968 return -1;
9971 ssize_t
9972 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9974 struct Lisp_Process *process = (struct Lisp_Process *)p;
9975 int fd = process->outfd;
9976 ssize_t n = sys_write (fd, buf, sz);
9978 /* 0 or more bytes written means everything went fine. */
9979 if (n >= 0)
9980 return n;
9982 /* Negative bytes written means we got an error in errno.
9983 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9984 emacs_gnutls_transport_set_errno (process->gnutls_state,
9985 errno == EWOULDBLOCK ? EAGAIN : errno);
9987 return -1;
9989 #endif /* HAVE_GNUTLS */
9991 /* end of w32.c */