Assume !BROKEN_NON_BLOCKING_CONNECT
[emacs.git] / src / w32.c
blob1917fea343d01b326e2aee7814df42f293145bfd
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <float.h> /* for DBL_EPSILON */
29 #include <io.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <sys/file.h>
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
36 #include <sys/time.h>
37 #include <sys/utime.h>
38 #include <math.h>
40 /* must include CRT headers *before* config.h */
42 #include <config.h>
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
45 #undef access
46 #undef chdir
47 #undef chmod
48 #undef creat
49 #undef ctime
50 #undef fopen
51 #undef link
52 #undef mkdir
53 #undef open
54 #undef rename
55 #undef rmdir
56 #undef unlink
58 #undef close
59 #undef dup
60 #undef dup2
61 #undef pipe
62 #undef read
63 #undef write
65 #undef strerror
67 #undef localtime
69 #include "lisp.h"
70 #include "epaths.h" /* for SHELL */
72 #include <pwd.h>
73 #include <grp.h>
75 /* MinGW64 defines these in its _mingw.h. */
76 #ifndef _ANONYMOUS_UNION
77 # define _ANONYMOUS_UNION
78 #endif
79 #ifndef _ANONYMOUS_STRUCT
80 # define _ANONYMOUS_STRUCT
81 #endif
82 #include <windows.h>
83 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
84 use a different name to avoid compilation problems. */
85 typedef struct _MEMORY_STATUS_EX {
86 DWORD dwLength;
87 DWORD dwMemoryLoad;
88 DWORDLONG ullTotalPhys;
89 DWORDLONG ullAvailPhys;
90 DWORDLONG ullTotalPageFile;
91 DWORDLONG ullAvailPageFile;
92 DWORDLONG ullTotalVirtual;
93 DWORDLONG ullAvailVirtual;
94 DWORDLONG ullAvailExtendedVirtual;
95 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
97 /* These are here so that GDB would know about these data types. This
98 allows to attach GDB to Emacs when a fatal exception is triggered
99 and Windows pops up the "application needs to be closed" dialog.
100 At that point, _gnu_exception_handler, the top-level exception
101 handler installed by the MinGW startup code, is somewhere on the
102 call-stack of the main thread, so going to that call frame and
103 looking at the argument to _gnu_exception_handler, which is a
104 PEXCEPTION_POINTERS pointer, can reveal the exception code
105 (excptr->ExceptionRecord->ExceptionCode) and the address where the
106 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
107 well as some additional information specific to the exception. */
108 PEXCEPTION_POINTERS excptr;
109 PEXCEPTION_RECORD excprec;
110 PCONTEXT ctxrec;
112 #include <lmcons.h>
113 #include <shlobj.h>
115 #include <tlhelp32.h>
116 #include <psapi.h>
117 #ifndef _MSC_VER
118 #include <w32api.h>
119 #endif
120 #if _WIN32_WINNT < 0x0500
121 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
122 /* This either is not in psapi.h or guarded by higher value of
123 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
124 defines it in psapi.h */
125 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
126 DWORD cb;
127 DWORD PageFaultCount;
128 SIZE_T PeakWorkingSetSize;
129 SIZE_T WorkingSetSize;
130 SIZE_T QuotaPeakPagedPoolUsage;
131 SIZE_T QuotaPagedPoolUsage;
132 SIZE_T QuotaPeakNonPagedPoolUsage;
133 SIZE_T QuotaNonPagedPoolUsage;
134 SIZE_T PagefileUsage;
135 SIZE_T PeakPagefileUsage;
136 SIZE_T PrivateUsage;
137 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
138 #endif
139 #endif
141 #include <winioctl.h>
142 #include <aclapi.h>
143 #include <sddl.h>
145 #include <sys/acl.h>
146 #include <acl.h>
148 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
149 define them by hand if not already defined. */
150 #ifndef SDDL_REVISION_1
151 #define SDDL_REVISION_1 1
152 #endif /* SDDL_REVISION_1 */
154 #if defined(_MSC_VER) || defined(MINGW_W64)
155 /* MSVC and MinGW64 don't provide the definition of
156 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
157 which cannot be included because it triggers conflicts with other
158 Windows API headers. So we define it here by hand. */
160 typedef struct _REPARSE_DATA_BUFFER {
161 ULONG ReparseTag;
162 USHORT ReparseDataLength;
163 USHORT Reserved;
164 union {
165 struct {
166 USHORT SubstituteNameOffset;
167 USHORT SubstituteNameLength;
168 USHORT PrintNameOffset;
169 USHORT PrintNameLength;
170 ULONG Flags;
171 WCHAR PathBuffer[1];
172 } SymbolicLinkReparseBuffer;
173 struct {
174 USHORT SubstituteNameOffset;
175 USHORT SubstituteNameLength;
176 USHORT PrintNameOffset;
177 USHORT PrintNameLength;
178 WCHAR PathBuffer[1];
179 } MountPointReparseBuffer;
180 struct {
181 UCHAR DataBuffer[1];
182 } GenericReparseBuffer;
183 } DUMMYUNIONNAME;
184 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
186 #ifndef FILE_DEVICE_FILE_SYSTEM
187 #define FILE_DEVICE_FILE_SYSTEM 9
188 #endif
189 #ifndef METHOD_BUFFERED
190 #define METHOD_BUFFERED 0
191 #endif
192 #ifndef FILE_ANY_ACCESS
193 #define FILE_ANY_ACCESS 0x00000000
194 #endif
195 #ifndef CTL_CODE
196 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
197 #endif
198 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
199 #ifndef FSCTL_GET_REPARSE_POINT
200 #define FSCTL_GET_REPARSE_POINT \
201 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
202 #endif
203 #endif
205 /* TCP connection support. */
206 #include <sys/socket.h>
207 #undef socket
208 #undef bind
209 #undef connect
210 #undef htons
211 #undef ntohs
212 #undef inet_addr
213 #undef gethostname
214 #undef gethostbyname
215 #undef getservbyname
216 #undef getpeername
217 #undef shutdown
218 #undef setsockopt
219 #undef listen
220 #undef getsockname
221 #undef accept
222 #undef recvfrom
223 #undef sendto
225 #include <iphlpapi.h> /* should be after winsock2.h */
227 #include "w32.h"
228 #include <dirent.h>
229 #include "w32common.h"
230 #include "w32heap.h"
231 #include "w32select.h"
232 #include "systime.h"
233 #include "dispextern.h" /* for xstrcasecmp */
234 #include "coding.h" /* for Vlocale_coding_system */
236 #include "careadlinkat.h"
237 #include "allocator.h"
239 /* For serial_configure and serial_open. */
240 #include "process.h"
242 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
243 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
245 void globals_of_w32 (void);
246 static DWORD get_rid (PSID);
247 static int is_symlink (const char *);
248 static char * chase_symlinks (const char *);
249 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
250 static int restore_privilege (TOKEN_PRIVILEGES *);
251 static BOOL WINAPI revert_to_self (void);
253 static int sys_access (const char *, int);
254 extern void *e_malloc (size_t);
255 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
256 struct timespec *, void *);
257 extern int sys_dup (int);
262 /* Initialization states.
264 WARNING: If you add any more such variables for additional APIs,
265 you MUST add initialization for them to globals_of_w32
266 below. This is because these variables might get set
267 to non-NULL values during dumping, but the dumped Emacs
268 cannot reuse those values, because it could be run on a
269 different version of the OS, where API addresses are
270 different. */
271 static BOOL g_b_init_is_windows_9x;
272 static BOOL g_b_init_open_process_token;
273 static BOOL g_b_init_get_token_information;
274 static BOOL g_b_init_lookup_account_sid;
275 static BOOL g_b_init_get_sid_sub_authority;
276 static BOOL g_b_init_get_sid_sub_authority_count;
277 static BOOL g_b_init_get_security_info;
278 static BOOL g_b_init_get_file_security_w;
279 static BOOL g_b_init_get_file_security_a;
280 static BOOL g_b_init_get_security_descriptor_owner;
281 static BOOL g_b_init_get_security_descriptor_group;
282 static BOOL g_b_init_is_valid_sid;
283 static BOOL g_b_init_create_toolhelp32_snapshot;
284 static BOOL g_b_init_process32_first;
285 static BOOL g_b_init_process32_next;
286 static BOOL g_b_init_open_thread_token;
287 static BOOL g_b_init_impersonate_self;
288 static BOOL g_b_init_revert_to_self;
289 static BOOL g_b_init_get_process_memory_info;
290 static BOOL g_b_init_get_process_working_set_size;
291 static BOOL g_b_init_global_memory_status;
292 static BOOL g_b_init_global_memory_status_ex;
293 static BOOL g_b_init_get_length_sid;
294 static BOOL g_b_init_equal_sid;
295 static BOOL g_b_init_copy_sid;
296 static BOOL g_b_init_get_native_system_info;
297 static BOOL g_b_init_get_system_times;
298 static BOOL g_b_init_create_symbolic_link_w;
299 static BOOL g_b_init_create_symbolic_link_a;
300 static BOOL g_b_init_get_security_descriptor_dacl;
301 static BOOL g_b_init_convert_sd_to_sddl;
302 static BOOL g_b_init_convert_sddl_to_sd;
303 static BOOL g_b_init_is_valid_security_descriptor;
304 static BOOL g_b_init_set_file_security_w;
305 static BOOL g_b_init_set_file_security_a;
306 static BOOL g_b_init_set_named_security_info_w;
307 static BOOL g_b_init_set_named_security_info_a;
308 static BOOL g_b_init_get_adapters_info;
310 BOOL g_b_init_compare_string_w;
313 BEGIN: Wrapper functions around OpenProcessToken
314 and other functions in advapi32.dll that are only
315 supported in Windows NT / 2k / XP
317 /* ** Function pointer typedefs ** */
318 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
319 HANDLE ProcessHandle,
320 DWORD DesiredAccess,
321 PHANDLE TokenHandle);
322 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
323 HANDLE TokenHandle,
324 TOKEN_INFORMATION_CLASS TokenInformationClass,
325 LPVOID TokenInformation,
326 DWORD TokenInformationLength,
327 PDWORD ReturnLength);
328 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
329 HANDLE process_handle,
330 LPFILETIME creation_time,
331 LPFILETIME exit_time,
332 LPFILETIME kernel_time,
333 LPFILETIME user_time);
335 GetProcessTimes_Proc get_process_times_fn = NULL;
337 #ifdef _UNICODE
338 const char * const LookupAccountSid_Name = "LookupAccountSidW";
339 #else
340 const char * const LookupAccountSid_Name = "LookupAccountSidA";
341 #endif
342 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
343 LPCTSTR lpSystemName,
344 PSID Sid,
345 LPTSTR Name,
346 LPDWORD cbName,
347 LPTSTR DomainName,
348 LPDWORD cbDomainName,
349 PSID_NAME_USE peUse);
350 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
351 PSID pSid,
352 DWORD n);
353 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
354 PSID pSid);
355 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
356 HANDLE handle,
357 SE_OBJECT_TYPE ObjectType,
358 SECURITY_INFORMATION SecurityInfo,
359 PSID *ppsidOwner,
360 PSID *ppsidGroup,
361 PACL *ppDacl,
362 PACL *ppSacl,
363 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
364 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
365 LPCWSTR lpFileName,
366 SECURITY_INFORMATION RequestedInformation,
367 PSECURITY_DESCRIPTOR pSecurityDescriptor,
368 DWORD nLength,
369 LPDWORD lpnLengthNeeded);
370 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
371 LPCSTR lpFileName,
372 SECURITY_INFORMATION RequestedInformation,
373 PSECURITY_DESCRIPTOR pSecurityDescriptor,
374 DWORD nLength,
375 LPDWORD lpnLengthNeeded);
376 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
377 LPCWSTR lpFileName,
378 SECURITY_INFORMATION SecurityInformation,
379 PSECURITY_DESCRIPTOR pSecurityDescriptor);
380 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
381 LPCSTR lpFileName,
382 SECURITY_INFORMATION SecurityInformation,
383 PSECURITY_DESCRIPTOR pSecurityDescriptor);
384 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
385 LPCWSTR lpObjectName,
386 SE_OBJECT_TYPE ObjectType,
387 SECURITY_INFORMATION SecurityInformation,
388 PSID psidOwner,
389 PSID psidGroup,
390 PACL pDacl,
391 PACL pSacl);
392 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
393 LPCSTR lpObjectName,
394 SE_OBJECT_TYPE ObjectType,
395 SECURITY_INFORMATION SecurityInformation,
396 PSID psidOwner,
397 PSID psidGroup,
398 PACL pDacl,
399 PACL pSacl);
400 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
401 PSECURITY_DESCRIPTOR pSecurityDescriptor,
402 PSID *pOwner,
403 LPBOOL lpbOwnerDefaulted);
404 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
405 PSECURITY_DESCRIPTOR pSecurityDescriptor,
406 PSID *pGroup,
407 LPBOOL lpbGroupDefaulted);
408 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
409 PSECURITY_DESCRIPTOR pSecurityDescriptor,
410 LPBOOL lpbDaclPresent,
411 PACL *pDacl,
412 LPBOOL lpbDaclDefaulted);
413 typedef BOOL (WINAPI * IsValidSid_Proc) (
414 PSID sid);
415 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
416 DWORD dwFlags,
417 DWORD th32ProcessID);
418 typedef BOOL (WINAPI * Process32First_Proc) (
419 HANDLE hSnapshot,
420 LPPROCESSENTRY32 lppe);
421 typedef BOOL (WINAPI * Process32Next_Proc) (
422 HANDLE hSnapshot,
423 LPPROCESSENTRY32 lppe);
424 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
425 HANDLE ThreadHandle,
426 DWORD DesiredAccess,
427 BOOL OpenAsSelf,
428 PHANDLE TokenHandle);
429 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
430 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
431 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
432 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
433 HANDLE Process,
434 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
435 DWORD cb);
436 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
437 HANDLE hProcess,
438 PSIZE_T lpMinimumWorkingSetSize,
439 PSIZE_T lpMaximumWorkingSetSize);
440 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
441 LPMEMORYSTATUS lpBuffer);
442 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
443 LPMEMORY_STATUS_EX lpBuffer);
444 typedef BOOL (WINAPI * CopySid_Proc) (
445 DWORD nDestinationSidLength,
446 PSID pDestinationSid,
447 PSID pSourceSid);
448 typedef BOOL (WINAPI * EqualSid_Proc) (
449 PSID pSid1,
450 PSID pSid2);
451 typedef DWORD (WINAPI * GetLengthSid_Proc) (
452 PSID pSid);
453 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
454 LPSYSTEM_INFO lpSystemInfo);
455 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
456 LPFILETIME lpIdleTime,
457 LPFILETIME lpKernelTime,
458 LPFILETIME lpUserTime);
459 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
460 LPCWSTR lpSymlinkFileName,
461 LPCWSTR lpTargetFileName,
462 DWORD dwFlags);
463 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
464 LPCSTR lpSymlinkFileName,
465 LPCSTR lpTargetFileName,
466 DWORD dwFlags);
467 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
468 LPCTSTR StringSecurityDescriptor,
469 DWORD StringSDRevision,
470 PSECURITY_DESCRIPTOR *SecurityDescriptor,
471 PULONG SecurityDescriptorSize);
472 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
473 PSECURITY_DESCRIPTOR SecurityDescriptor,
474 DWORD RequestedStringSDRevision,
475 SECURITY_INFORMATION SecurityInformation,
476 LPTSTR *StringSecurityDescriptor,
477 PULONG StringSecurityDescriptorLen);
478 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
479 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
480 PIP_ADAPTER_INFO pAdapterInfo,
481 PULONG pOutBufLen);
483 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
484 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
486 /* ** A utility function ** */
487 static BOOL
488 is_windows_9x (void)
490 static BOOL s_b_ret = 0;
491 OSVERSIONINFO os_ver;
492 if (g_b_init_is_windows_9x == 0)
494 g_b_init_is_windows_9x = 1;
495 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
496 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
497 if (GetVersionEx (&os_ver))
499 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
502 return s_b_ret;
505 static Lisp_Object ltime (ULONGLONG);
507 /* Get total user and system times for get-internal-run-time.
508 Returns a list of integers if the times are provided by the OS
509 (NT derivatives), otherwise it returns the result of current-time. */
510 Lisp_Object
511 w32_get_internal_run_time (void)
513 if (get_process_times_fn)
515 FILETIME create, exit, kernel, user;
516 HANDLE proc = GetCurrentProcess ();
517 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
519 LARGE_INTEGER user_int, kernel_int, total;
520 user_int.LowPart = user.dwLowDateTime;
521 user_int.HighPart = user.dwHighDateTime;
522 kernel_int.LowPart = kernel.dwLowDateTime;
523 kernel_int.HighPart = kernel.dwHighDateTime;
524 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
525 return ltime (total.QuadPart);
529 return Fcurrent_time ();
532 /* ** The wrapper functions ** */
534 static BOOL WINAPI
535 open_process_token (HANDLE ProcessHandle,
536 DWORD DesiredAccess,
537 PHANDLE TokenHandle)
539 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
540 HMODULE hm_advapi32 = NULL;
541 if (is_windows_9x () == TRUE)
543 return FALSE;
545 if (g_b_init_open_process_token == 0)
547 g_b_init_open_process_token = 1;
548 hm_advapi32 = LoadLibrary ("Advapi32.dll");
549 s_pfn_Open_Process_Token =
550 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
552 if (s_pfn_Open_Process_Token == NULL)
554 return FALSE;
556 return (
557 s_pfn_Open_Process_Token (
558 ProcessHandle,
559 DesiredAccess,
560 TokenHandle)
564 static BOOL WINAPI
565 get_token_information (HANDLE TokenHandle,
566 TOKEN_INFORMATION_CLASS TokenInformationClass,
567 LPVOID TokenInformation,
568 DWORD TokenInformationLength,
569 PDWORD ReturnLength)
571 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
572 HMODULE hm_advapi32 = NULL;
573 if (is_windows_9x () == TRUE)
575 return FALSE;
577 if (g_b_init_get_token_information == 0)
579 g_b_init_get_token_information = 1;
580 hm_advapi32 = LoadLibrary ("Advapi32.dll");
581 s_pfn_Get_Token_Information =
582 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
584 if (s_pfn_Get_Token_Information == NULL)
586 return FALSE;
588 return (
589 s_pfn_Get_Token_Information (
590 TokenHandle,
591 TokenInformationClass,
592 TokenInformation,
593 TokenInformationLength,
594 ReturnLength)
598 static BOOL WINAPI
599 lookup_account_sid (LPCTSTR lpSystemName,
600 PSID Sid,
601 LPTSTR Name,
602 LPDWORD cbName,
603 LPTSTR DomainName,
604 LPDWORD cbDomainName,
605 PSID_NAME_USE peUse)
607 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
608 HMODULE hm_advapi32 = NULL;
609 if (is_windows_9x () == TRUE)
611 return FALSE;
613 if (g_b_init_lookup_account_sid == 0)
615 g_b_init_lookup_account_sid = 1;
616 hm_advapi32 = LoadLibrary ("Advapi32.dll");
617 s_pfn_Lookup_Account_Sid =
618 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
620 if (s_pfn_Lookup_Account_Sid == NULL)
622 return FALSE;
624 return (
625 s_pfn_Lookup_Account_Sid (
626 lpSystemName,
627 Sid,
628 Name,
629 cbName,
630 DomainName,
631 cbDomainName,
632 peUse)
636 static PDWORD WINAPI
637 get_sid_sub_authority (PSID pSid, DWORD n)
639 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
640 static DWORD zero = 0U;
641 HMODULE hm_advapi32 = NULL;
642 if (is_windows_9x () == TRUE)
644 return &zero;
646 if (g_b_init_get_sid_sub_authority == 0)
648 g_b_init_get_sid_sub_authority = 1;
649 hm_advapi32 = LoadLibrary ("Advapi32.dll");
650 s_pfn_Get_Sid_Sub_Authority =
651 (GetSidSubAuthority_Proc) GetProcAddress (
652 hm_advapi32, "GetSidSubAuthority");
654 if (s_pfn_Get_Sid_Sub_Authority == NULL)
656 return &zero;
658 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
661 static PUCHAR WINAPI
662 get_sid_sub_authority_count (PSID pSid)
664 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
665 static UCHAR zero = 0U;
666 HMODULE hm_advapi32 = NULL;
667 if (is_windows_9x () == TRUE)
669 return &zero;
671 if (g_b_init_get_sid_sub_authority_count == 0)
673 g_b_init_get_sid_sub_authority_count = 1;
674 hm_advapi32 = LoadLibrary ("Advapi32.dll");
675 s_pfn_Get_Sid_Sub_Authority_Count =
676 (GetSidSubAuthorityCount_Proc) GetProcAddress (
677 hm_advapi32, "GetSidSubAuthorityCount");
679 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
681 return &zero;
683 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
686 static DWORD WINAPI
687 get_security_info (HANDLE handle,
688 SE_OBJECT_TYPE ObjectType,
689 SECURITY_INFORMATION SecurityInfo,
690 PSID *ppsidOwner,
691 PSID *ppsidGroup,
692 PACL *ppDacl,
693 PACL *ppSacl,
694 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
696 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
697 HMODULE hm_advapi32 = NULL;
698 if (is_windows_9x () == TRUE)
700 return FALSE;
702 if (g_b_init_get_security_info == 0)
704 g_b_init_get_security_info = 1;
705 hm_advapi32 = LoadLibrary ("Advapi32.dll");
706 s_pfn_Get_Security_Info =
707 (GetSecurityInfo_Proc) GetProcAddress (
708 hm_advapi32, "GetSecurityInfo");
710 if (s_pfn_Get_Security_Info == NULL)
712 return FALSE;
714 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
715 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
716 ppSecurityDescriptor));
719 static BOOL WINAPI
720 get_file_security (const char *lpFileName,
721 SECURITY_INFORMATION RequestedInformation,
722 PSECURITY_DESCRIPTOR pSecurityDescriptor,
723 DWORD nLength,
724 LPDWORD lpnLengthNeeded)
726 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
727 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
728 HMODULE hm_advapi32 = NULL;
729 if (is_windows_9x () == TRUE)
731 errno = ENOTSUP;
732 return FALSE;
734 if (w32_unicode_filenames)
736 wchar_t filename_w[MAX_PATH];
738 if (g_b_init_get_file_security_w == 0)
740 g_b_init_get_file_security_w = 1;
741 hm_advapi32 = LoadLibrary ("Advapi32.dll");
742 s_pfn_Get_File_SecurityW =
743 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
744 "GetFileSecurityW");
746 if (s_pfn_Get_File_SecurityW == NULL)
748 errno = ENOTSUP;
749 return FALSE;
751 filename_to_utf16 (lpFileName, filename_w);
752 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
753 pSecurityDescriptor, nLength,
754 lpnLengthNeeded));
756 else
758 char filename_a[MAX_PATH];
760 if (g_b_init_get_file_security_a == 0)
762 g_b_init_get_file_security_a = 1;
763 hm_advapi32 = LoadLibrary ("Advapi32.dll");
764 s_pfn_Get_File_SecurityA =
765 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
766 "GetFileSecurityA");
768 if (s_pfn_Get_File_SecurityA == NULL)
770 errno = ENOTSUP;
771 return FALSE;
773 filename_to_ansi (lpFileName, filename_a);
774 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
775 pSecurityDescriptor, nLength,
776 lpnLengthNeeded));
780 static BOOL WINAPI
781 set_file_security (const char *lpFileName,
782 SECURITY_INFORMATION SecurityInformation,
783 PSECURITY_DESCRIPTOR pSecurityDescriptor)
785 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
786 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
787 HMODULE hm_advapi32 = NULL;
788 if (is_windows_9x () == TRUE)
790 errno = ENOTSUP;
791 return FALSE;
793 if (w32_unicode_filenames)
795 wchar_t filename_w[MAX_PATH];
797 if (g_b_init_set_file_security_w == 0)
799 g_b_init_set_file_security_w = 1;
800 hm_advapi32 = LoadLibrary ("Advapi32.dll");
801 s_pfn_Set_File_SecurityW =
802 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
803 "SetFileSecurityW");
805 if (s_pfn_Set_File_SecurityW == NULL)
807 errno = ENOTSUP;
808 return FALSE;
810 filename_to_utf16 (lpFileName, filename_w);
811 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
812 pSecurityDescriptor));
814 else
816 char filename_a[MAX_PATH];
818 if (g_b_init_set_file_security_a == 0)
820 g_b_init_set_file_security_a = 1;
821 hm_advapi32 = LoadLibrary ("Advapi32.dll");
822 s_pfn_Set_File_SecurityA =
823 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
824 "SetFileSecurityA");
826 if (s_pfn_Set_File_SecurityA == NULL)
828 errno = ENOTSUP;
829 return FALSE;
831 filename_to_ansi (lpFileName, filename_a);
832 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
833 pSecurityDescriptor));
837 static DWORD WINAPI
838 set_named_security_info (LPCTSTR lpObjectName,
839 SE_OBJECT_TYPE ObjectType,
840 SECURITY_INFORMATION SecurityInformation,
841 PSID psidOwner,
842 PSID psidGroup,
843 PACL pDacl,
844 PACL pSacl)
846 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
847 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
848 HMODULE hm_advapi32 = NULL;
849 if (is_windows_9x () == TRUE)
851 errno = ENOTSUP;
852 return ENOTSUP;
854 if (w32_unicode_filenames)
856 wchar_t filename_w[MAX_PATH];
858 if (g_b_init_set_named_security_info_w == 0)
860 g_b_init_set_named_security_info_w = 1;
861 hm_advapi32 = LoadLibrary ("Advapi32.dll");
862 s_pfn_Set_Named_Security_InfoW =
863 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
864 "SetNamedSecurityInfoW");
866 if (s_pfn_Set_Named_Security_InfoW == NULL)
868 errno = ENOTSUP;
869 return ENOTSUP;
871 filename_to_utf16 (lpObjectName, filename_w);
872 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
873 SecurityInformation, psidOwner,
874 psidGroup, pDacl, pSacl));
876 else
878 char filename_a[MAX_PATH];
880 if (g_b_init_set_named_security_info_a == 0)
882 g_b_init_set_named_security_info_a = 1;
883 hm_advapi32 = LoadLibrary ("Advapi32.dll");
884 s_pfn_Set_Named_Security_InfoA =
885 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
886 "SetNamedSecurityInfoA");
888 if (s_pfn_Set_Named_Security_InfoA == NULL)
890 errno = ENOTSUP;
891 return ENOTSUP;
893 filename_to_ansi (lpObjectName, filename_a);
894 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
895 SecurityInformation, psidOwner,
896 psidGroup, pDacl, pSacl));
900 static BOOL WINAPI
901 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
902 PSID *pOwner,
903 LPBOOL lpbOwnerDefaulted)
905 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
906 HMODULE hm_advapi32 = NULL;
907 if (is_windows_9x () == TRUE)
909 errno = ENOTSUP;
910 return FALSE;
912 if (g_b_init_get_security_descriptor_owner == 0)
914 g_b_init_get_security_descriptor_owner = 1;
915 hm_advapi32 = LoadLibrary ("Advapi32.dll");
916 s_pfn_Get_Security_Descriptor_Owner =
917 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
918 hm_advapi32, "GetSecurityDescriptorOwner");
920 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
922 errno = ENOTSUP;
923 return FALSE;
925 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
926 lpbOwnerDefaulted));
929 static BOOL WINAPI
930 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
931 PSID *pGroup,
932 LPBOOL lpbGroupDefaulted)
934 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
935 HMODULE hm_advapi32 = NULL;
936 if (is_windows_9x () == TRUE)
938 errno = ENOTSUP;
939 return FALSE;
941 if (g_b_init_get_security_descriptor_group == 0)
943 g_b_init_get_security_descriptor_group = 1;
944 hm_advapi32 = LoadLibrary ("Advapi32.dll");
945 s_pfn_Get_Security_Descriptor_Group =
946 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
947 hm_advapi32, "GetSecurityDescriptorGroup");
949 if (s_pfn_Get_Security_Descriptor_Group == NULL)
951 errno = ENOTSUP;
952 return FALSE;
954 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
955 lpbGroupDefaulted));
958 static BOOL WINAPI
959 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
960 LPBOOL lpbDaclPresent,
961 PACL *pDacl,
962 LPBOOL lpbDaclDefaulted)
964 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
965 HMODULE hm_advapi32 = NULL;
966 if (is_windows_9x () == TRUE)
968 errno = ENOTSUP;
969 return FALSE;
971 if (g_b_init_get_security_descriptor_dacl == 0)
973 g_b_init_get_security_descriptor_dacl = 1;
974 hm_advapi32 = LoadLibrary ("Advapi32.dll");
975 s_pfn_Get_Security_Descriptor_Dacl =
976 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
977 hm_advapi32, "GetSecurityDescriptorDacl");
979 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
981 errno = ENOTSUP;
982 return FALSE;
984 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
985 lpbDaclPresent, pDacl,
986 lpbDaclDefaulted));
989 static BOOL WINAPI
990 is_valid_sid (PSID sid)
992 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
993 HMODULE hm_advapi32 = NULL;
994 if (is_windows_9x () == TRUE)
996 return FALSE;
998 if (g_b_init_is_valid_sid == 0)
1000 g_b_init_is_valid_sid = 1;
1001 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1002 s_pfn_Is_Valid_Sid =
1003 (IsValidSid_Proc) GetProcAddress (
1004 hm_advapi32, "IsValidSid");
1006 if (s_pfn_Is_Valid_Sid == NULL)
1008 return FALSE;
1010 return (s_pfn_Is_Valid_Sid (sid));
1013 static BOOL WINAPI
1014 equal_sid (PSID sid1, PSID sid2)
1016 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1017 HMODULE hm_advapi32 = NULL;
1018 if (is_windows_9x () == TRUE)
1020 return FALSE;
1022 if (g_b_init_equal_sid == 0)
1024 g_b_init_equal_sid = 1;
1025 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1026 s_pfn_Equal_Sid =
1027 (EqualSid_Proc) GetProcAddress (
1028 hm_advapi32, "EqualSid");
1030 if (s_pfn_Equal_Sid == NULL)
1032 return FALSE;
1034 return (s_pfn_Equal_Sid (sid1, sid2));
1037 static DWORD WINAPI
1038 get_length_sid (PSID sid)
1040 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1041 HMODULE hm_advapi32 = NULL;
1042 if (is_windows_9x () == TRUE)
1044 return 0;
1046 if (g_b_init_get_length_sid == 0)
1048 g_b_init_get_length_sid = 1;
1049 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1050 s_pfn_Get_Length_Sid =
1051 (GetLengthSid_Proc) GetProcAddress (
1052 hm_advapi32, "GetLengthSid");
1054 if (s_pfn_Get_Length_Sid == NULL)
1056 return 0;
1058 return (s_pfn_Get_Length_Sid (sid));
1061 static BOOL WINAPI
1062 copy_sid (DWORD destlen, PSID dest, PSID src)
1064 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1065 HMODULE hm_advapi32 = NULL;
1066 if (is_windows_9x () == TRUE)
1068 return FALSE;
1070 if (g_b_init_copy_sid == 0)
1072 g_b_init_copy_sid = 1;
1073 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1074 s_pfn_Copy_Sid =
1075 (CopySid_Proc) GetProcAddress (
1076 hm_advapi32, "CopySid");
1078 if (s_pfn_Copy_Sid == NULL)
1080 return FALSE;
1082 return (s_pfn_Copy_Sid (destlen, dest, src));
1086 END: Wrapper functions around OpenProcessToken
1087 and other functions in advapi32.dll that are only
1088 supported in Windows NT / 2k / XP
1091 static void WINAPI
1092 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1094 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1095 if (is_windows_9x () != TRUE)
1097 if (g_b_init_get_native_system_info == 0)
1099 g_b_init_get_native_system_info = 1;
1100 s_pfn_Get_Native_System_Info =
1101 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1102 "GetNativeSystemInfo");
1104 if (s_pfn_Get_Native_System_Info != NULL)
1105 s_pfn_Get_Native_System_Info (lpSystemInfo);
1107 else
1108 lpSystemInfo->dwNumberOfProcessors = -1;
1111 static BOOL WINAPI
1112 get_system_times (LPFILETIME lpIdleTime,
1113 LPFILETIME lpKernelTime,
1114 LPFILETIME lpUserTime)
1116 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1117 if (is_windows_9x () == TRUE)
1119 return FALSE;
1121 if (g_b_init_get_system_times == 0)
1123 g_b_init_get_system_times = 1;
1124 s_pfn_Get_System_times =
1125 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1126 "GetSystemTimes");
1128 if (s_pfn_Get_System_times == NULL)
1129 return FALSE;
1130 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1133 static BOOLEAN WINAPI
1134 create_symbolic_link (LPCSTR lpSymlinkFilename,
1135 LPCSTR lpTargetFileName,
1136 DWORD dwFlags)
1138 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1139 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1140 BOOLEAN retval;
1142 if (is_windows_9x () == TRUE)
1144 errno = ENOSYS;
1145 return 0;
1147 if (w32_unicode_filenames)
1149 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1151 if (g_b_init_create_symbolic_link_w == 0)
1153 g_b_init_create_symbolic_link_w = 1;
1154 s_pfn_Create_Symbolic_LinkW =
1155 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1156 "CreateSymbolicLinkW");
1158 if (s_pfn_Create_Symbolic_LinkW == NULL)
1160 errno = ENOSYS;
1161 return 0;
1164 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1165 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1166 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1167 /* If we were denied creation of the symlink, try again after
1168 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1169 if (!retval)
1171 TOKEN_PRIVILEGES priv_current;
1173 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1174 &priv_current))
1176 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1177 restore_privilege (&priv_current);
1178 revert_to_self ();
1182 else
1184 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1186 if (g_b_init_create_symbolic_link_a == 0)
1188 g_b_init_create_symbolic_link_a = 1;
1189 s_pfn_Create_Symbolic_LinkA =
1190 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1191 "CreateSymbolicLinkA");
1193 if (s_pfn_Create_Symbolic_LinkA == NULL)
1195 errno = ENOSYS;
1196 return 0;
1199 filename_to_ansi (lpSymlinkFilename, symfn_a);
1200 filename_to_ansi (lpTargetFileName, tgtfn_a);
1201 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1202 /* If we were denied creation of the symlink, try again after
1203 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1204 if (!retval)
1206 TOKEN_PRIVILEGES priv_current;
1208 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1209 &priv_current))
1211 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1212 restore_privilege (&priv_current);
1213 revert_to_self ();
1217 return retval;
1220 static BOOL WINAPI
1221 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1223 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1225 if (is_windows_9x () == TRUE)
1227 errno = ENOTSUP;
1228 return FALSE;
1231 if (g_b_init_is_valid_security_descriptor == 0)
1233 g_b_init_is_valid_security_descriptor = 1;
1234 s_pfn_Is_Valid_Security_Descriptor_Proc =
1235 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1236 "IsValidSecurityDescriptor");
1238 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1240 errno = ENOTSUP;
1241 return FALSE;
1244 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1247 static BOOL WINAPI
1248 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1249 DWORD RequestedStringSDRevision,
1250 SECURITY_INFORMATION SecurityInformation,
1251 LPTSTR *StringSecurityDescriptor,
1252 PULONG StringSecurityDescriptorLen)
1254 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1255 BOOL retval;
1257 if (is_windows_9x () == TRUE)
1259 errno = ENOTSUP;
1260 return FALSE;
1263 if (g_b_init_convert_sd_to_sddl == 0)
1265 g_b_init_convert_sd_to_sddl = 1;
1266 #ifdef _UNICODE
1267 s_pfn_Convert_SD_To_SDDL =
1268 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1269 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1270 #else
1271 s_pfn_Convert_SD_To_SDDL =
1272 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1273 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1274 #endif
1276 if (s_pfn_Convert_SD_To_SDDL == NULL)
1278 errno = ENOTSUP;
1279 return FALSE;
1282 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1283 RequestedStringSDRevision,
1284 SecurityInformation,
1285 StringSecurityDescriptor,
1286 StringSecurityDescriptorLen);
1288 return retval;
1291 static BOOL WINAPI
1292 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1293 DWORD StringSDRevision,
1294 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1295 PULONG SecurityDescriptorSize)
1297 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1298 BOOL retval;
1300 if (is_windows_9x () == TRUE)
1302 errno = ENOTSUP;
1303 return FALSE;
1306 if (g_b_init_convert_sddl_to_sd == 0)
1308 g_b_init_convert_sddl_to_sd = 1;
1309 #ifdef _UNICODE
1310 s_pfn_Convert_SDDL_To_SD =
1311 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1312 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1313 #else
1314 s_pfn_Convert_SDDL_To_SD =
1315 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1316 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1317 #endif
1319 if (s_pfn_Convert_SDDL_To_SD == NULL)
1321 errno = ENOTSUP;
1322 return FALSE;
1325 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1326 StringSDRevision,
1327 SecurityDescriptor,
1328 SecurityDescriptorSize);
1330 return retval;
1333 static DWORD WINAPI
1334 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1336 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1337 HMODULE hm_iphlpapi = NULL;
1339 if (is_windows_9x () == TRUE)
1340 return ERROR_NOT_SUPPORTED;
1342 if (g_b_init_get_adapters_info == 0)
1344 g_b_init_get_adapters_info = 1;
1345 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1346 if (hm_iphlpapi)
1347 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1348 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1350 if (s_pfn_Get_Adapters_Info == NULL)
1351 return ERROR_NOT_SUPPORTED;
1352 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1357 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1358 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1360 This is called from alloc.c:valid_pointer_p. */
1362 w32_valid_pointer_p (void *p, int size)
1364 SIZE_T done;
1365 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1367 if (h)
1369 unsigned char *buf = alloca (size);
1370 int retval = ReadProcessMemory (h, p, buf, size, &done);
1372 CloseHandle (h);
1373 return retval;
1375 else
1376 return -1;
1381 /* Here's an overview of how the Windows build supports file names
1382 that cannot be encoded by the current system codepage.
1384 From the POV of Lisp and layers of C code above the functions here,
1385 Emacs on Windows pretends that its file names are encoded in UTF-8;
1386 see encode_file and decode_file on coding.c. Any file name that is
1387 passed as a unibyte string to C functions defined here is assumed
1388 to be in UTF-8 encoding. Any file name returned by functions
1389 defined here must be in UTF-8 encoding, with only a few exceptions
1390 reserved for a couple of special cases. (Be sure to use
1391 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1392 as they can be much longer than MAX_PATH!)
1394 The UTF-8 encoded file names cannot be passed to system APIs, as
1395 Windows does not support that. Therefore, they are converted
1396 either to UTF-16 or to the ANSI codepage, depending on the value of
1397 w32-unicode-filenames, before calling any system APIs or CRT library
1398 functions. The default value of that variable is determined by the
1399 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1400 user can change that default (although I don't see why would she
1401 want to).
1403 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1404 filename_from_utf16, and filename_from_ansi, are the workhorses of
1405 these conversions. They rely on Windows native APIs
1406 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1407 functions from coding.c here, because they allocate memory, which
1408 is a bad idea on the level of libc, which is what the functions
1409 here emulate. (If you worry about performance due to constant
1410 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1411 it was measured to take only a few microseconds on a not-so-fast
1412 machine, and second, that's exactly what the ANSI APIs we used
1413 before did anyway, because they are just thin wrappers around the
1414 Unicode APIs.)
1416 The variables file-name-coding-system and default-file-name-coding-system
1417 still exist, but are actually used only when a file name needs to
1418 be converted to the ANSI codepage. This happens all the time when
1419 w32-unicode-filenames is nil, but can also happen from time to time
1420 when it is t. Otherwise, these variables have no effect on file-name
1421 encoding when w32-unicode-filenames is t; this is similar to
1422 selection-coding-system.
1424 This arrangement works very well, but it has a few gotchas and
1425 limitations:
1427 . Lisp code that encodes or decodes file names manually should
1428 normally use 'utf-8' as the coding-system on Windows,
1429 disregarding file-name-coding-system. This is a somewhat
1430 unpleasant consequence, but it cannot be avoided. Fortunately,
1431 very few Lisp packages need to do that.
1433 More generally, passing to library functions (e.g., fopen or
1434 opendir) file names already encoded in the ANSI codepage is
1435 explicitly *verboten*, as all those functions, as shadowed and
1436 emulated here, assume they will receive UTF-8 encoded file names.
1438 For the same reasons, no CRT function or Win32 API can be called
1439 directly in Emacs sources, without either converting the file
1440 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1441 some shadowing function defined here.
1443 . Environment variables stored in Vprocess_environment are encoded
1444 in the ANSI codepage, so if getenv/egetenv is used for a variable
1445 whose value is a file name or a list of directories, it needs to
1446 be converted to UTF-8, before it is used as argument to functions
1447 or decoded into a Lisp string.
1449 . File names passed to external libraries, like the image libraries
1450 and GnuTLS, need special handling. These libraries generally
1451 don't support UTF-16 or UTF-8 file names, so they must get file
1452 names encoded in the ANSI codepage. To facilitate using these
1453 libraries with file names that are not encodable in the ANSI
1454 codepage, use the function ansi_encode_filename, which will try
1455 to use the short 8+3 alias of a file name if that file name is
1456 not encodable in the ANSI codepage. See image.c and gnutls.c for
1457 examples of how this should be done.
1459 . Running subprocesses in non-ASCII directories and with non-ASCII
1460 file arguments is limited to the current codepage (even though
1461 Emacs is perfectly capable of finding an executable program file
1462 in a directory whose name cannot be encoded in the current
1463 codepage). This is because the command-line arguments are
1464 encoded _before_ they get to the w32-specific level, and the
1465 encoding is not known in advance (it doesn't have to be the
1466 current ANSI codepage), so w32proc.c functions cannot re-encode
1467 them in UTF-16. This should be fixed, but will also require
1468 changes in cmdproxy. The current limitation is not terribly bad
1469 anyway, since very few, if any, Windows console programs that are
1470 likely to be invoked by Emacs support UTF-16 encoded command
1471 lines.
1473 . For similar reasons, server.el and emacsclient are also limited
1474 to the current ANSI codepage for now.
1476 . Emacs itself can only handle command-line arguments encoded in
1477 the current codepage.
1479 . Turning on w32-unicode-filename on Windows 9X (if it at all
1480 works) requires UNICOWS.DLL, which is thus a requirement even in
1481 non-GUI sessions, something the we previously avoided. */
1485 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1486 codepage defined by file-name-coding-system. */
1488 /* Current codepage for encoding file names. */
1489 static int file_name_codepage;
1491 /* Produce a Windows ANSI codepage suitable for encoding file names.
1492 Return the information about that codepage in CP_INFO. */
1493 static int
1494 codepage_for_filenames (CPINFO *cp_info)
1496 /* A simple cache to avoid calling GetCPInfo every time we need to
1497 encode/decode a file name. The file-name encoding is not
1498 supposed to be changed too frequently, if ever. */
1499 static Lisp_Object last_file_name_encoding;
1500 static CPINFO cp;
1501 Lisp_Object current_encoding;
1503 current_encoding = Vfile_name_coding_system;
1504 if (NILP (current_encoding))
1505 current_encoding = Vdefault_file_name_coding_system;
1507 if (!EQ (last_file_name_encoding, current_encoding))
1509 /* Default to the current ANSI codepage. */
1510 file_name_codepage = w32_ansi_code_page;
1512 if (NILP (current_encoding))
1514 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1515 char *cp = NULL, *end;
1516 int cpnum;
1518 if (strncmp (cpname, "cp", 2) == 0)
1519 cp = cpname + 2;
1520 else if (strncmp (cpname, "windows-", 8) == 0)
1521 cp = cpname + 8;
1523 if (cp)
1525 end = cp;
1526 cpnum = strtol (cp, &end, 10);
1527 if (cpnum && *end == '\0' && end - cp >= 2)
1528 file_name_codepage = cpnum;
1532 if (!file_name_codepage)
1533 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1535 if (!GetCPInfo (file_name_codepage, &cp))
1537 file_name_codepage = CP_ACP;
1538 if (!GetCPInfo (file_name_codepage, &cp))
1539 emacs_abort ();
1542 if (cp_info)
1543 *cp_info = cp;
1545 return file_name_codepage;
1549 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1551 int result = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, fn_in, -1,
1552 fn_out, MAX_PATH);
1554 if (!result)
1556 DWORD err = GetLastError ();
1558 switch (err)
1560 case ERROR_INVALID_FLAGS:
1561 case ERROR_INVALID_PARAMETER:
1562 errno = EINVAL;
1563 break;
1564 case ERROR_INSUFFICIENT_BUFFER:
1565 case ERROR_NO_UNICODE_TRANSLATION:
1566 default:
1567 errno = ENOENT;
1568 break;
1570 return -1;
1572 return 0;
1576 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1578 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1579 fn_out, MAX_UTF8_PATH, NULL, NULL);
1581 if (!result)
1583 DWORD err = GetLastError ();
1585 switch (err)
1587 case ERROR_INVALID_FLAGS:
1588 case ERROR_INVALID_PARAMETER:
1589 errno = EINVAL;
1590 break;
1591 case ERROR_INSUFFICIENT_BUFFER:
1592 case ERROR_NO_UNICODE_TRANSLATION:
1593 default:
1594 errno = ENOENT;
1595 break;
1597 return -1;
1599 return 0;
1603 filename_to_ansi (const char *fn_in, char *fn_out)
1605 wchar_t fn_utf16[MAX_PATH];
1607 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1609 int result;
1610 int codepage = codepage_for_filenames (NULL);
1612 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1613 fn_out, MAX_PATH, NULL, NULL);
1614 if (!result)
1616 DWORD err = GetLastError ();
1618 switch (err)
1620 case ERROR_INVALID_FLAGS:
1621 case ERROR_INVALID_PARAMETER:
1622 errno = EINVAL;
1623 break;
1624 case ERROR_INSUFFICIENT_BUFFER:
1625 case ERROR_NO_UNICODE_TRANSLATION:
1626 default:
1627 errno = ENOENT;
1628 break;
1630 return -1;
1632 return 0;
1634 return -1;
1638 filename_from_ansi (const char *fn_in, char *fn_out)
1640 wchar_t fn_utf16[MAX_PATH];
1641 int codepage = codepage_for_filenames (NULL);
1642 int result = pMultiByteToWideChar (codepage, MB_ERR_INVALID_CHARS, fn_in, -1,
1643 fn_utf16, MAX_PATH);
1645 if (!result)
1647 DWORD err = GetLastError ();
1649 switch (err)
1651 case ERROR_INVALID_FLAGS:
1652 case ERROR_INVALID_PARAMETER:
1653 errno = EINVAL;
1654 break;
1655 case ERROR_INSUFFICIENT_BUFFER:
1656 case ERROR_NO_UNICODE_TRANSLATION:
1657 default:
1658 errno = ENOENT;
1659 break;
1661 return -1;
1663 return filename_from_utf16 (fn_utf16, fn_out);
1668 /* The directory where we started, in UTF-8. */
1669 static char startup_dir[MAX_UTF8_PATH];
1671 /* Get the current working directory. */
1672 char *
1673 getcwd (char *dir, int dirsize)
1675 if (!dirsize)
1677 errno = EINVAL;
1678 return NULL;
1680 if (dirsize <= strlen (startup_dir))
1682 errno = ERANGE;
1683 return NULL;
1685 #if 0
1686 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1687 return dir;
1688 return NULL;
1689 #else
1690 /* Emacs doesn't actually change directory itself, it stays in the
1691 same directory where it was started. */
1692 strcpy (dir, startup_dir);
1693 return dir;
1694 #endif
1697 /* Emulate getloadavg. */
1699 struct load_sample {
1700 time_t sample_time;
1701 ULONGLONG idle;
1702 ULONGLONG kernel;
1703 ULONGLONG user;
1706 /* Number of processors on this machine. */
1707 static unsigned num_of_processors;
1709 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1710 static struct load_sample samples[16*60];
1711 static int first_idx = -1, last_idx = -1;
1712 static int max_idx = ARRAYELTS (samples);
1714 static int
1715 buf_next (int from)
1717 int next_idx = from + 1;
1719 if (next_idx >= max_idx)
1720 next_idx = 0;
1722 return next_idx;
1725 static int
1726 buf_prev (int from)
1728 int prev_idx = from - 1;
1730 if (prev_idx < 0)
1731 prev_idx = max_idx - 1;
1733 return prev_idx;
1736 static void
1737 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1739 SYSTEM_INFO sysinfo;
1740 FILETIME ft_idle, ft_user, ft_kernel;
1742 /* Initialize the number of processors on this machine. */
1743 if (num_of_processors <= 0)
1745 get_native_system_info (&sysinfo);
1746 num_of_processors = sysinfo.dwNumberOfProcessors;
1747 if (num_of_processors <= 0)
1749 GetSystemInfo (&sysinfo);
1750 num_of_processors = sysinfo.dwNumberOfProcessors;
1752 if (num_of_processors <= 0)
1753 num_of_processors = 1;
1756 /* TODO: Take into account threads that are ready to run, by
1757 sampling the "\System\Processor Queue Length" performance
1758 counter. The code below accounts only for threads that are
1759 actually running. */
1761 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1763 ULARGE_INTEGER uidle, ukernel, uuser;
1765 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1766 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1767 memcpy (&uuser, &ft_user, sizeof (ft_user));
1768 *idle = uidle.QuadPart;
1769 *kernel = ukernel.QuadPart;
1770 *user = uuser.QuadPart;
1772 else
1774 *idle = 0;
1775 *kernel = 0;
1776 *user = 0;
1780 /* Produce the load average for a given time interval, using the
1781 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1782 1-minute, 5-minute, or 15-minute average, respectively. */
1783 static double
1784 getavg (int which)
1786 double retval = -1.0;
1787 double tdiff;
1788 int idx;
1789 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1790 time_t now = samples[last_idx].sample_time;
1792 if (first_idx != last_idx)
1794 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1796 tdiff = difftime (now, samples[idx].sample_time);
1797 if (tdiff >= span - 2*DBL_EPSILON*now)
1799 long double sys =
1800 samples[last_idx].kernel + samples[last_idx].user
1801 - (samples[idx].kernel + samples[idx].user);
1802 long double idl = samples[last_idx].idle - samples[idx].idle;
1804 retval = (1.0 - idl / sys) * num_of_processors;
1805 break;
1807 if (idx == first_idx)
1808 break;
1812 return retval;
1816 getloadavg (double loadavg[], int nelem)
1818 int elem;
1819 ULONGLONG idle, kernel, user;
1820 time_t now = time (NULL);
1822 /* If system time jumped back for some reason, delete all samples
1823 whose time is later than the current wall-clock time. This
1824 prevents load average figures from becoming frozen for prolonged
1825 periods of time, when system time is reset backwards. */
1826 if (last_idx >= 0)
1828 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1830 if (last_idx == first_idx)
1832 first_idx = last_idx = -1;
1833 break;
1835 last_idx = buf_prev (last_idx);
1839 /* Store another sample. We ignore samples that are less than 1 sec
1840 apart. */
1841 if (last_idx < 0
1842 || (difftime (now, samples[last_idx].sample_time)
1843 >= 1.0 - 2*DBL_EPSILON*now))
1845 sample_system_load (&idle, &kernel, &user);
1846 last_idx = buf_next (last_idx);
1847 samples[last_idx].sample_time = now;
1848 samples[last_idx].idle = idle;
1849 samples[last_idx].kernel = kernel;
1850 samples[last_idx].user = user;
1851 /* If the buffer has more that 15 min worth of samples, discard
1852 the old ones. */
1853 if (first_idx == -1)
1854 first_idx = last_idx;
1855 while (first_idx != last_idx
1856 && (difftime (now, samples[first_idx].sample_time)
1857 >= 15.0*60 + 2*DBL_EPSILON*now))
1858 first_idx = buf_next (first_idx);
1861 for (elem = 0; elem < nelem; elem++)
1863 double avg = getavg (elem);
1865 if (avg < 0)
1866 break;
1867 loadavg[elem] = avg;
1870 return elem;
1873 /* Emulate getpwuid, getpwnam and others. */
1875 #define PASSWD_FIELD_SIZE 256
1877 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1878 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1879 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1880 static char dflt_passwd_dir[MAX_UTF8_PATH];
1881 static char dflt_passwd_shell[MAX_UTF8_PATH];
1883 static struct passwd dflt_passwd =
1885 dflt_passwd_name,
1886 dflt_passwd_passwd,
1890 dflt_passwd_gecos,
1891 dflt_passwd_dir,
1892 dflt_passwd_shell,
1895 static char dflt_group_name[GNLEN+1];
1897 static struct group dflt_group =
1899 /* When group information is not available, we return this as the
1900 group for all files. */
1901 dflt_group_name,
1905 unsigned
1906 getuid (void)
1908 return dflt_passwd.pw_uid;
1911 unsigned
1912 geteuid (void)
1914 /* I could imagine arguing for checking to see whether the user is
1915 in the Administrators group and returning a UID of 0 for that
1916 case, but I don't know how wise that would be in the long run. */
1917 return getuid ();
1920 unsigned
1921 getgid (void)
1923 return dflt_passwd.pw_gid;
1926 unsigned
1927 getegid (void)
1929 return getgid ();
1932 struct passwd *
1933 getpwuid (unsigned uid)
1935 if (uid == dflt_passwd.pw_uid)
1936 return &dflt_passwd;
1937 return NULL;
1940 struct group *
1941 getgrgid (gid_t gid)
1943 return &dflt_group;
1946 struct passwd *
1947 getpwnam (char *name)
1949 struct passwd *pw;
1951 pw = getpwuid (getuid ());
1952 if (!pw)
1953 return pw;
1955 if (xstrcasecmp (name, pw->pw_name))
1956 return NULL;
1958 return pw;
1961 static void
1962 init_user_info (void)
1964 /* Find the user's real name by opening the process token and
1965 looking up the name associated with the user-sid in that token.
1967 Use the relative portion of the identifier authority value from
1968 the user-sid as the user id value (same for group id using the
1969 primary group sid from the process token). */
1971 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1972 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1973 DWORD glength = sizeof (gname);
1974 HANDLE token = NULL;
1975 SID_NAME_USE user_type;
1976 unsigned char *buf = NULL;
1977 DWORD blen = 0;
1978 TOKEN_USER user_token;
1979 TOKEN_PRIMARY_GROUP group_token;
1980 BOOL result;
1982 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1983 if (result)
1985 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1986 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1988 buf = xmalloc (blen);
1989 result = get_token_information (token, TokenUser,
1990 (LPVOID)buf, blen, &needed);
1991 if (result)
1993 memcpy (&user_token, buf, sizeof (user_token));
1994 result = lookup_account_sid (NULL, user_token.User.Sid,
1995 uname, &ulength,
1996 domain, &dlength, &user_type);
1999 else
2000 result = FALSE;
2002 if (result)
2004 strcpy (dflt_passwd.pw_name, uname);
2005 /* Determine a reasonable uid value. */
2006 if (xstrcasecmp ("administrator", uname) == 0)
2008 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2009 dflt_passwd.pw_gid = 513; /* well-known None gid */
2011 else
2013 /* Use the last sub-authority value of the RID, the relative
2014 portion of the SID, as user/group ID. */
2015 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2017 /* Get group id and name. */
2018 result = get_token_information (token, TokenPrimaryGroup,
2019 (LPVOID)buf, blen, &needed);
2020 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2022 buf = xrealloc (buf, blen = needed);
2023 result = get_token_information (token, TokenPrimaryGroup,
2024 (LPVOID)buf, blen, &needed);
2026 if (result)
2028 memcpy (&group_token, buf, sizeof (group_token));
2029 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2030 dlength = sizeof (domain);
2031 /* If we can get at the real Primary Group name, use that.
2032 Otherwise, the default group name was already set to
2033 "None" in globals_of_w32. */
2034 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2035 gname, &glength, NULL, &dlength,
2036 &user_type))
2037 strcpy (dflt_group_name, gname);
2039 else
2040 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2043 /* If security calls are not supported (presumably because we
2044 are running under Windows 9X), fallback to this: */
2045 else if (GetUserName (uname, &ulength))
2047 strcpy (dflt_passwd.pw_name, uname);
2048 if (xstrcasecmp ("administrator", uname) == 0)
2049 dflt_passwd.pw_uid = 0;
2050 else
2051 dflt_passwd.pw_uid = 123;
2052 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2054 else
2056 strcpy (dflt_passwd.pw_name, "unknown");
2057 dflt_passwd.pw_uid = 123;
2058 dflt_passwd.pw_gid = 123;
2060 dflt_group.gr_gid = dflt_passwd.pw_gid;
2062 /* Set dir and shell from environment variables. */
2063 if (w32_unicode_filenames)
2065 wchar_t *home = _wgetenv (L"HOME");
2066 wchar_t *shell = _wgetenv (L"SHELL");
2068 /* Ensure HOME and SHELL are defined. */
2069 if (home == NULL)
2070 emacs_abort ();
2071 if (shell == NULL)
2072 emacs_abort ();
2073 filename_from_utf16 (home, dflt_passwd.pw_dir);
2074 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2076 else
2078 char *home = getenv ("HOME");
2079 char *shell = getenv ("SHELL");
2081 if (home == NULL)
2082 emacs_abort ();
2083 if (shell == NULL)
2084 emacs_abort ();
2085 filename_from_ansi (home, dflt_passwd.pw_dir);
2086 filename_from_ansi (shell, dflt_passwd.pw_shell);
2089 xfree (buf);
2090 if (token)
2091 CloseHandle (token);
2095 random (void)
2097 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2098 return ((rand () << 15) | rand ());
2101 void
2102 srandom (int seed)
2104 srand (seed);
2107 /* Return the maximum length in bytes of a multibyte character
2108 sequence encoded in the current ANSI codepage. This is required to
2109 correctly walk the encoded file names one character at a time. */
2110 static int
2111 max_filename_mbslen (void)
2113 CPINFO cp_info;
2115 codepage_for_filenames (&cp_info);
2116 return cp_info.MaxCharSize;
2119 /* Normalize filename by converting in-place all of its path
2120 separators to the separator specified by PATH_SEP. */
2122 static void
2123 normalize_filename (register char *fp, char path_sep)
2125 char *p2;
2127 /* Always lower-case drive letters a-z, even if the filesystem
2128 preserves case in filenames.
2129 This is so filenames can be compared by string comparison
2130 functions that are case-sensitive. Even case-preserving filesystems
2131 do not distinguish case in drive letters. */
2132 p2 = fp + 1;
2134 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2136 *fp += 'a' - 'A';
2137 fp += 2;
2140 while (*fp)
2142 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2143 *fp = path_sep;
2144 fp++;
2148 /* Destructively turn backslashes into slashes. */
2149 void
2150 dostounix_filename (register char *p)
2152 normalize_filename (p, '/');
2155 /* Destructively turn slashes into backslashes. */
2156 void
2157 unixtodos_filename (register char *p)
2159 normalize_filename (p, '\\');
2162 /* Remove all CR's that are followed by a LF.
2163 (From msdos.c...probably should figure out a way to share it,
2164 although this code isn't going to ever change.) */
2165 static int
2166 crlf_to_lf (register int n, register unsigned char *buf)
2168 unsigned char *np = buf;
2169 unsigned char *startp = buf;
2170 unsigned char *endp = buf + n;
2172 if (n == 0)
2173 return n;
2174 while (buf < endp - 1)
2176 if (*buf == 0x0d)
2178 if (*(++buf) != 0x0a)
2179 *np++ = 0x0d;
2181 else
2182 *np++ = *buf++;
2184 if (buf < endp)
2185 *np++ = *buf++;
2186 return np - startp;
2189 /* Parse the root part of file name, if present. Return length and
2190 optionally store pointer to char after root. */
2191 static int
2192 parse_root (const char * name, const char ** pPath)
2194 const char * start = name;
2196 if (name == NULL)
2197 return 0;
2199 /* find the root name of the volume if given */
2200 if (isalpha (name[0]) && name[1] == ':')
2202 /* skip past drive specifier */
2203 name += 2;
2204 if (IS_DIRECTORY_SEP (name[0]))
2205 name++;
2207 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2209 int slashes = 2;
2211 name += 2;
2214 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2215 break;
2216 name++;
2218 while ( *name );
2219 if (IS_DIRECTORY_SEP (name[0]))
2220 name++;
2223 if (pPath)
2224 *pPath = name;
2226 return name - start;
2229 /* Get long base name for name; name is assumed to be absolute. */
2230 static int
2231 get_long_basename (char * name, char * buf, int size)
2233 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2234 char fname_utf8[MAX_UTF8_PATH];
2235 int len = 0;
2236 int cstatus = -1;
2238 /* Must be valid filename, no wild cards or other invalid characters. */
2239 if (strpbrk (name, "*?|<>\""))
2240 return 0;
2242 if (w32_unicode_filenames)
2244 wchar_t fname_utf16[MAX_PATH];
2245 WIN32_FIND_DATAW find_data_wide;
2247 filename_to_utf16 (name, fname_utf16);
2248 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2249 if (dir_handle != INVALID_HANDLE_VALUE)
2250 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2252 else
2254 char fname_ansi[MAX_PATH];
2255 WIN32_FIND_DATAA find_data_ansi;
2257 filename_to_ansi (name, fname_ansi);
2258 /* If the ANSI name includes ? characters, it is not encodable
2259 in the ANSI codepage. In that case, we deliver the question
2260 marks to the caller; calling FindFirstFileA in this case
2261 could return some unrelated file name in the same
2262 directory. */
2263 if (_mbspbrk (fname_ansi, "?"))
2265 /* Find the basename of fname_ansi. */
2266 char *p = strrchr (fname_ansi, '\\');
2268 if (!p)
2269 p = fname_ansi;
2270 else
2271 p++;
2272 cstatus = filename_from_ansi (p, fname_utf8);
2274 else
2276 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2277 if (dir_handle != INVALID_HANDLE_VALUE)
2278 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2282 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2283 memcpy (buf, fname_utf8, len + 1);
2284 else
2285 len = 0;
2287 if (dir_handle != INVALID_HANDLE_VALUE)
2288 FindClose (dir_handle);
2290 return len;
2293 /* Get long name for file, if possible (assumed to be absolute). */
2294 BOOL
2295 w32_get_long_filename (const char * name, char * buf, int size)
2297 char * o = buf;
2298 char * p;
2299 const char * q;
2300 char full[ MAX_UTF8_PATH ];
2301 int len;
2303 len = strlen (name);
2304 if (len >= MAX_UTF8_PATH)
2305 return FALSE;
2307 /* Use local copy for destructive modification. */
2308 memcpy (full, name, len+1);
2309 unixtodos_filename (full);
2311 /* Copy root part verbatim. */
2312 len = parse_root (full, (const char **)&p);
2313 memcpy (o, full, len);
2314 o += len;
2315 *o = '\0';
2316 size -= len;
2318 while (p != NULL && *p)
2320 q = p;
2321 p = strchr (q, '\\');
2322 if (p) *p = '\0';
2323 len = get_long_basename (full, o, size);
2324 if (len > 0)
2326 o += len;
2327 size -= len;
2328 if (p != NULL)
2330 *p++ = '\\';
2331 if (size < 2)
2332 return FALSE;
2333 *o++ = '\\';
2334 size--;
2335 *o = '\0';
2338 else
2339 return FALSE;
2342 return TRUE;
2345 unsigned int
2346 w32_get_short_filename (const char * name, char * buf, int size)
2348 if (w32_unicode_filenames)
2350 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2351 unsigned int retval;
2353 filename_to_utf16 (name, name_utf16);
2354 retval = GetShortPathNameW (name_utf16, short_name, size);
2355 if (retval && retval < size)
2356 filename_from_utf16 (short_name, buf);
2357 return retval;
2359 else
2361 char name_ansi[MAX_PATH];
2363 filename_to_ansi (name, name_ansi);
2364 return GetShortPathNameA (name_ansi, buf, size);
2368 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2369 MS-Windows ANSI codepage. If FILENAME includes characters not
2370 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2371 if it exists. This is needed because the w32 build wants to
2372 support file names outside of the system locale, but image
2373 libraries typically don't support wide (a.k.a. "Unicode") APIs
2374 required for that. */
2376 Lisp_Object
2377 ansi_encode_filename (Lisp_Object filename)
2379 Lisp_Object encoded_filename;
2380 char fname[MAX_PATH];
2382 filename_to_ansi (SSDATA (filename), fname);
2383 if (_mbspbrk (fname, "?"))
2385 char shortname[MAX_PATH];
2387 if (w32_get_short_filename (SDATA (filename), shortname, MAX_PATH))
2389 dostounix_filename (shortname);
2390 encoded_filename = build_string (shortname);
2392 else
2393 encoded_filename = build_unibyte_string (fname);
2395 else
2396 encoded_filename = build_unibyte_string (fname);
2397 return encoded_filename;
2400 static int
2401 is_unc_volume (const char *filename)
2403 const char *ptr = filename;
2405 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2406 return 0;
2408 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2409 return 0;
2411 return 1;
2414 /* Emulate the Posix unsetenv. */
2416 unsetenv (const char *name)
2418 char *var;
2419 size_t name_len;
2421 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2423 errno = EINVAL;
2424 return -1;
2426 name_len = strlen (name);
2427 /* MS docs says an environment variable cannot be longer than 32K. */
2428 if (name_len > 32767)
2430 errno = ENOMEM;
2431 return 0;
2433 /* It is safe to use 'alloca' with 32K size, since the stack is at
2434 least 2MB, and we set it to 8MB in the link command line. */
2435 var = alloca (name_len + 2);
2436 strncpy (var, name, name_len);
2437 var[name_len++] = '=';
2438 var[name_len] = '\0';
2439 return _putenv (var);
2442 /* MS _putenv doesn't support removing a variable when the argument
2443 does not include the '=' character, so we fix that here. */
2445 sys_putenv (char *str)
2447 const char *const name_end = strchr (str, '=');
2449 if (name_end == NULL)
2451 /* Remove the variable from the environment. */
2452 return unsetenv (str);
2455 return _putenv (str);
2458 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2460 LPBYTE
2461 w32_get_resource (char *key, LPDWORD lpdwtype)
2463 LPBYTE lpvalue;
2464 HKEY hrootkey = NULL;
2465 DWORD cbData;
2467 /* Check both the current user and the local machine to see if
2468 we have any resources. */
2470 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2472 lpvalue = NULL;
2474 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2475 && (lpvalue = xmalloc (cbData)) != NULL
2476 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2478 RegCloseKey (hrootkey);
2479 return (lpvalue);
2482 xfree (lpvalue);
2484 RegCloseKey (hrootkey);
2487 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2489 lpvalue = NULL;
2491 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2492 && (lpvalue = xmalloc (cbData)) != NULL
2493 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2495 RegCloseKey (hrootkey);
2496 return (lpvalue);
2499 xfree (lpvalue);
2501 RegCloseKey (hrootkey);
2504 return (NULL);
2507 /* The argv[] array holds ANSI-encoded strings, and so this function
2508 works with ANS_encoded strings. */
2509 void
2510 init_environment (char ** argv)
2512 static const char * const tempdirs[] = {
2513 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2516 int i;
2518 const int imax = ARRAYELTS (tempdirs);
2520 /* Implementation note: This function explicitly works with ANSI
2521 file names, not with UTF-8 encoded file names. This is because
2522 this function pushes variables into the Emacs's environment, and
2523 the environment variables are always assumed to be in the
2524 locale-specific encoding. Do NOT call any functions that accept
2525 UTF-8 file names from this function! */
2527 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2528 temporary files and assume "/tmp" if $TMPDIR is unset, which
2529 will break on DOS/Windows. Refuse to work if we cannot find
2530 a directory, not even "c:/", usable for that purpose. */
2531 for (i = 0; i < imax ; i++)
2533 const char *tmp = tempdirs[i];
2535 if (*tmp == '$')
2536 tmp = getenv (tmp + 1);
2537 /* Note that `access' can lie to us if the directory resides on a
2538 read-only filesystem, like CD-ROM or a write-protected floppy.
2539 The only way to be really sure is to actually create a file and
2540 see if it succeeds. But I think that's too much to ask. */
2542 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2543 if (tmp && sys_access (tmp, D_OK) == 0)
2545 char * var = alloca (strlen (tmp) + 8);
2546 sprintf (var, "TMPDIR=%s", tmp);
2547 _putenv (strdup (var));
2548 break;
2551 if (i >= imax)
2552 cmd_error_internal
2553 (Fcons (Qerror,
2554 Fcons (build_string ("no usable temporary directories found!!"),
2555 Qnil)),
2556 "While setting TMPDIR: ");
2558 /* Check for environment variables and use registry settings if they
2559 don't exist. Fallback on default values where applicable. */
2561 int i;
2562 LPBYTE lpval;
2563 DWORD dwType;
2564 char locale_name[32];
2565 char default_home[MAX_PATH];
2566 int appdata = 0;
2568 static const struct env_entry
2570 char * name;
2571 char * def_value;
2572 } dflt_envvars[] =
2574 /* If the default value is NULL, we will use the value from the
2575 outside environment or the Registry, but will not push the
2576 variable into the Emacs environment if it is defined neither
2577 in the Registry nor in the outside environment. */
2578 {"HOME", "C:/"},
2579 {"PRELOAD_WINSOCK", NULL},
2580 {"emacs_dir", "C:/emacs"},
2581 {"EMACSLOADPATH", NULL},
2582 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2583 {"EMACSDATA", NULL},
2584 {"EMACSPATH", NULL},
2585 {"INFOPATH", NULL},
2586 {"EMACSDOC", NULL},
2587 {"TERM", "cmd"},
2588 {"LANG", NULL},
2591 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2593 /* We need to copy dflt_envvars[] and work on the copy because we
2594 don't want the dumped Emacs to inherit the values of
2595 environment variables we saw during dumping (which could be on
2596 a different system). The defaults above must be left intact. */
2597 struct env_entry env_vars[N_ENV_VARS];
2599 for (i = 0; i < N_ENV_VARS; i++)
2600 env_vars[i] = dflt_envvars[i];
2602 /* For backwards compatibility, check if a .emacs file exists in C:/
2603 If not, then we can try to default to the appdata directory under the
2604 user's profile, which is more likely to be writable. */
2605 if (sys_access ("C:/.emacs", F_OK) != 0)
2607 HRESULT profile_result;
2608 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2609 of Windows 95 and NT4 that have not been updated to include
2610 MSIE 5. */
2611 ShGetFolderPath_fn get_folder_path;
2612 get_folder_path = (ShGetFolderPath_fn)
2613 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2615 if (get_folder_path != NULL)
2617 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2618 0, default_home);
2620 /* If we can't get the appdata dir, revert to old behavior. */
2621 if (profile_result == S_OK)
2623 env_vars[0].def_value = default_home;
2624 appdata = 1;
2629 /* Get default locale info and use it for LANG. */
2630 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2631 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2632 locale_name, sizeof (locale_name)))
2634 for (i = 0; i < N_ENV_VARS; i++)
2636 if (strcmp (env_vars[i].name, "LANG") == 0)
2638 env_vars[i].def_value = locale_name;
2639 break;
2644 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2646 /* Treat emacs_dir specially: set it unconditionally based on our
2647 location. */
2649 char *p;
2650 char modname[MAX_PATH];
2652 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2653 emacs_abort ();
2654 if ((p = _mbsrchr (modname, '\\')) == NULL)
2655 emacs_abort ();
2656 *p = 0;
2658 if ((p = _mbsrchr (modname, '\\'))
2659 /* From bin means installed Emacs, from src means uninstalled. */
2660 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2662 char buf[SET_ENV_BUF_SIZE];
2663 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2665 *p = 0;
2666 for (p = modname; *p; p = CharNext (p))
2667 if (*p == '\\') *p = '/';
2669 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2670 _putenv (strdup (buf));
2671 /* If we are running from the Posix-like build tree, define
2672 SHELL to point to our own cmdproxy. The loop below will
2673 then disregard PATH_EXEC and the default value. */
2674 if (within_build_tree)
2676 _snprintf (buf, sizeof (buf) - 1,
2677 "SHELL=%s/nt/cmdproxy.exe", modname);
2678 _putenv (strdup (buf));
2683 for (i = 0; i < N_ENV_VARS; i++)
2685 if (!getenv (env_vars[i].name))
2687 int dont_free = 0;
2688 char bufc[SET_ENV_BUF_SIZE];
2690 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2691 /* Also ignore empty environment variables. */
2692 || *lpval == 0)
2694 xfree (lpval);
2695 dont_free = 1;
2696 if (strcmp (env_vars[i].name, "SHELL") == 0)
2698 /* Look for cmdproxy.exe in every directory in
2699 PATH_EXEC. FIXME: This does not find cmdproxy
2700 in nt/ when we run uninstalled. */
2701 char fname[MAX_PATH];
2702 const char *pstart = PATH_EXEC, *pend;
2704 do {
2705 pend = _mbschr (pstart, ';');
2706 if (!pend)
2707 pend = pstart + strlen (pstart);
2708 /* Be defensive against series of ;;; characters. */
2709 if (pend > pstart)
2711 strncpy (fname, pstart, pend - pstart);
2712 fname[pend - pstart] = '/';
2713 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2714 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2715 sizeof (bufc));
2716 if (sys_access (bufc, F_OK) == 0)
2718 lpval = bufc;
2719 dwType = REG_SZ;
2720 break;
2723 if (*pend)
2724 pstart = pend + 1;
2725 else
2726 pstart = pend;
2727 if (!*pstart)
2729 /* If not found in any directory, use the
2730 default as the last resort. */
2731 lpval = env_vars[i].def_value;
2732 dwType = REG_EXPAND_SZ;
2734 } while (*pstart);
2736 else
2738 lpval = env_vars[i].def_value;
2739 dwType = REG_EXPAND_SZ;
2741 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2742 Vdelayed_warnings_list
2743 = Fcons (listn (CONSTYPE_HEAP, 2,
2744 intern ("initialization"),
2745 build_string ("Setting HOME to C:\\ by default is deprecated")),
2746 Vdelayed_warnings_list);
2749 if (lpval)
2751 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2753 if (dwType == REG_EXPAND_SZ)
2754 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2755 else if (dwType == REG_SZ)
2756 strcpy (buf1, lpval);
2757 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2759 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2760 buf1);
2761 _putenv (strdup (buf2));
2764 if (!dont_free)
2765 xfree (lpval);
2771 /* Rebuild system configuration to reflect invoking system. */
2772 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2774 /* Another special case: on NT, the PATH variable is actually named
2775 "Path" although cmd.exe (perhaps NT itself) arranges for
2776 environment variable lookup and setting to be case insensitive.
2777 However, Emacs assumes a fully case sensitive environment, so we
2778 need to change "Path" to "PATH" to match the expectations of
2779 various elisp packages. We do this by the sneaky method of
2780 modifying the string in the C runtime environ entry.
2782 The same applies to COMSPEC. */
2784 char ** envp;
2786 for (envp = environ; *envp; envp++)
2787 if (_strnicmp (*envp, "PATH=", 5) == 0)
2788 memcpy (*envp, "PATH=", 5);
2789 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2790 memcpy (*envp, "COMSPEC=", 8);
2793 /* Remember the initial working directory for getcwd. */
2794 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2795 Does it matter anywhere in Emacs? */
2796 if (w32_unicode_filenames)
2798 wchar_t wstartup_dir[MAX_PATH];
2800 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2801 emacs_abort ();
2802 filename_from_utf16 (wstartup_dir, startup_dir);
2804 else
2806 char astartup_dir[MAX_PATH];
2808 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2809 emacs_abort ();
2810 filename_from_ansi (astartup_dir, startup_dir);
2814 static char modname[MAX_PATH];
2816 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2817 emacs_abort ();
2818 argv[0] = modname;
2821 /* Determine if there is a middle mouse button, to allow parse_button
2822 to decide whether right mouse events should be mouse-2 or
2823 mouse-3. */
2824 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2826 init_user_info ();
2829 /* Called from expand-file-name when default-directory is not a string. */
2831 char *
2832 emacs_root_dir (void)
2834 static char root_dir[MAX_UTF8_PATH];
2835 const char *p;
2837 p = getenv ("emacs_dir");
2838 if (p == NULL)
2839 emacs_abort ();
2840 filename_from_ansi (p, root_dir);
2841 root_dir[parse_root (root_dir, NULL)] = '\0';
2842 dostounix_filename (root_dir);
2843 return root_dir;
2846 #include <sys/timeb.h>
2848 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2850 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2852 struct _timeb tb;
2853 _ftime (&tb);
2855 tv->tv_sec = tb.time;
2856 tv->tv_usec = tb.millitm * 1000L;
2857 /* Implementation note: _ftime sometimes doesn't update the dstflag
2858 according to the new timezone when the system timezone is
2859 changed. We could fix that by using GetSystemTime and
2860 GetTimeZoneInformation, but that doesn't seem necessary, since
2861 Emacs always calls gettimeofday with the 2nd argument NULL (see
2862 current_emacs_time). */
2863 if (tz)
2865 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2866 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2868 return 0;
2871 /* Emulate fdutimens. */
2873 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2874 TIMESPEC[0] and TIMESPEC[1], respectively.
2875 FD must be either negative -- in which case it is ignored --
2876 or a file descriptor that is open on FILE.
2877 If FD is nonnegative, then FILE can be NULL, which means
2878 use just futimes instead of utimes.
2879 If TIMESPEC is null, FAIL.
2880 Return 0 on success, -1 (setting errno) on failure. */
2883 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2885 if (!timespec)
2887 errno = ENOSYS;
2888 return -1;
2890 if (fd < 0 && !file)
2892 errno = EBADF;
2893 return -1;
2895 /* _futime's prototype defines 2nd arg as having the type 'struct
2896 _utimbuf', while utime needs to accept 'struct utimbuf' for
2897 compatibility with Posix. So we need to use 2 different (but
2898 equivalent) types to avoid compiler warnings, sigh. */
2899 if (fd >= 0)
2901 struct _utimbuf _ut;
2903 _ut.actime = timespec[0].tv_sec;
2904 _ut.modtime = timespec[1].tv_sec;
2905 return _futime (fd, &_ut);
2907 else
2909 struct utimbuf ut;
2911 ut.actime = timespec[0].tv_sec;
2912 ut.modtime = timespec[1].tv_sec;
2913 /* Call 'utime', which is implemented below, not the MS library
2914 function, which fails on directories. */
2915 return utime (file, &ut);
2920 /* ------------------------------------------------------------------------- */
2921 /* IO support and wrapper functions for the Windows API. */
2922 /* ------------------------------------------------------------------------- */
2924 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2925 on network directories, so we handle that case here.
2926 (Ulrich Leodolter, 1/11/95). */
2927 char *
2928 sys_ctime (const time_t *t)
2930 char *str = (char *) ctime (t);
2931 return (str ? str : "Sun Jan 01 00:00:00 1970");
2934 /* Emulate sleep...we could have done this with a define, but that
2935 would necessitate including windows.h in the files that used it.
2936 This is much easier. */
2937 void
2938 sys_sleep (int seconds)
2940 Sleep (seconds * 1000);
2943 /* Internal MSVC functions for low-level descriptor munging */
2944 extern int __cdecl _set_osfhnd (int fd, long h);
2945 extern int __cdecl _free_osfhnd (int fd);
2947 /* parallel array of private info on file handles */
2948 filedesc fd_info [ MAXDESC ];
2950 typedef struct volume_info_data {
2951 struct volume_info_data * next;
2953 /* time when info was obtained */
2954 DWORD timestamp;
2956 /* actual volume info */
2957 char * root_dir;
2958 DWORD serialnum;
2959 DWORD maxcomp;
2960 DWORD flags;
2961 char * name;
2962 char * type;
2963 } volume_info_data;
2965 /* Global referenced by various functions. */
2966 static volume_info_data volume_info;
2968 /* Vector to indicate which drives are local and fixed (for which cached
2969 data never expires). */
2970 static BOOL fixed_drives[26];
2972 /* Consider cached volume information to be stale if older than 10s,
2973 at least for non-local drives. Info for fixed drives is never stale. */
2974 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2975 #define VOLINFO_STILL_VALID( root_dir, info ) \
2976 ( ( isalpha (root_dir[0]) && \
2977 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2978 || GetTickCount () - info->timestamp < 10000 )
2980 /* Cache support functions. */
2982 /* Simple linked list with linear search is sufficient. */
2983 static volume_info_data *volume_cache = NULL;
2985 static volume_info_data *
2986 lookup_volume_info (char * root_dir)
2988 volume_info_data * info;
2990 for (info = volume_cache; info; info = info->next)
2991 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2992 break;
2993 return info;
2996 static void
2997 add_volume_info (char * root_dir, volume_info_data * info)
2999 info->root_dir = xstrdup (root_dir);
3000 unixtodos_filename (info->root_dir);
3001 info->next = volume_cache;
3002 volume_cache = info;
3006 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3007 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3008 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3009 static volume_info_data *
3010 GetCachedVolumeInformation (char * root_dir)
3012 volume_info_data * info;
3013 char default_root[ MAX_UTF8_PATH ];
3014 char name[MAX_PATH+1];
3015 char type[MAX_PATH+1];
3017 /* NULL for root_dir means use root from current directory. */
3018 if (root_dir == NULL)
3020 if (w32_unicode_filenames)
3022 wchar_t curdirw[MAX_PATH];
3024 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3025 return NULL;
3026 filename_from_utf16 (curdirw, default_root);
3028 else
3030 char curdira[MAX_PATH];
3032 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3033 return NULL;
3034 filename_from_ansi (curdira, default_root);
3036 parse_root (default_root, (const char **)&root_dir);
3037 *root_dir = 0;
3038 root_dir = default_root;
3041 /* Local fixed drives can be cached permanently. Removable drives
3042 cannot be cached permanently, since the volume name and serial
3043 number (if nothing else) can change. Remote drives should be
3044 treated as if they are removable, since there is no sure way to
3045 tell whether they are or not. Also, the UNC association of drive
3046 letters mapped to remote volumes can be changed at any time (even
3047 by other processes) without notice.
3049 As a compromise, so we can benefit from caching info for remote
3050 volumes, we use a simple expiry mechanism to invalidate cache
3051 entries that are more than ten seconds old. */
3053 #if 0
3054 /* No point doing this, because WNetGetConnection is even slower than
3055 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3056 GetDriveType is about the only call of this type which does not
3057 involve network access, and so is extremely quick). */
3059 /* Map drive letter to UNC if remote. */
3060 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3062 char remote_name[ 256 ];
3063 char drive[3] = { root_dir[0], ':' };
3065 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3066 == NO_ERROR)
3067 /* do something */ ;
3069 #endif
3071 info = lookup_volume_info (root_dir);
3073 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3075 DWORD serialnum;
3076 DWORD maxcomp;
3077 DWORD flags;
3079 /* Info is not cached, or is stale. */
3080 if (w32_unicode_filenames)
3082 wchar_t root_w[MAX_PATH];
3083 wchar_t name_w[MAX_PATH+1];
3084 wchar_t type_w[MAX_PATH+1];
3086 filename_to_utf16 (root_dir, root_w);
3087 if (!GetVolumeInformationW (root_w,
3088 name_w, sizeof (name_w),
3089 &serialnum,
3090 &maxcomp,
3091 &flags,
3092 type_w, sizeof (type_w)))
3093 return NULL;
3094 /* Hmm... not really 100% correct, as these 2 are not file
3095 names... */
3096 filename_from_utf16 (name_w, name);
3097 filename_from_utf16 (type_w, type);
3099 else
3101 char root_a[MAX_PATH];
3102 char name_a[MAX_PATH+1];
3103 char type_a[MAX_PATH+1];
3105 filename_to_ansi (root_dir, root_a);
3106 if (!GetVolumeInformationA (root_a,
3107 name_a, sizeof (name_a),
3108 &serialnum,
3109 &maxcomp,
3110 &flags,
3111 type_a, sizeof (type_a)))
3112 return NULL;
3113 filename_from_ansi (name_a, name);
3114 filename_from_ansi (type_a, type);
3117 /* Cache the volume information for future use, overwriting existing
3118 entry if present. */
3119 if (info == NULL)
3121 info = xmalloc (sizeof (volume_info_data));
3122 add_volume_info (root_dir, info);
3124 else
3126 xfree (info->name);
3127 xfree (info->type);
3130 info->name = xstrdup (name);
3131 unixtodos_filename (info->name);
3132 info->serialnum = serialnum;
3133 info->maxcomp = maxcomp;
3134 info->flags = flags;
3135 info->type = xstrdup (type);
3136 info->timestamp = GetTickCount ();
3139 return info;
3142 /* Get information on the volume where NAME is held; set path pointer to
3143 start of pathname in NAME (past UNC header\volume header if present),
3144 if pPath is non-NULL.
3146 Note: if NAME includes symlinks, the information is for the volume
3147 of the symlink, not of its target. That's because, even though
3148 GetVolumeInformation returns information about the symlink target
3149 of its argument, we only pass the root directory to
3150 GetVolumeInformation, not the full NAME. */
3151 static int
3152 get_volume_info (const char * name, const char ** pPath)
3154 char temp[MAX_UTF8_PATH];
3155 char *rootname = NULL; /* default to current volume */
3156 volume_info_data * info;
3157 int root_len = parse_root (name, pPath);
3159 if (name == NULL)
3160 return FALSE;
3162 /* Copy the root name of the volume, if given. */
3163 if (root_len)
3165 strncpy (temp, name, root_len);
3166 temp[root_len] = '\0';
3167 unixtodos_filename (temp);
3168 rootname = temp;
3171 info = GetCachedVolumeInformation (rootname);
3172 if (info != NULL)
3174 /* Set global referenced by other functions. */
3175 volume_info = *info;
3176 return TRUE;
3178 return FALSE;
3181 /* Determine if volume is FAT format (ie. only supports short 8.3
3182 names); also set path pointer to start of pathname in name, if
3183 pPath is non-NULL. */
3184 static int
3185 is_fat_volume (const char * name, const char ** pPath)
3187 if (get_volume_info (name, pPath))
3188 return (volume_info.maxcomp == 12);
3189 return FALSE;
3192 /* Convert all slashes in a filename to backslashes, and map filename
3193 to a valid 8.3 name if necessary. The result is a pointer to a
3194 static buffer, so CAVEAT EMPTOR! */
3195 const char *
3196 map_w32_filename (const char * name, const char ** pPath)
3198 static char shortname[MAX_UTF8_PATH];
3199 char * str = shortname;
3200 char c;
3201 char * path;
3202 const char * save_name = name;
3204 if (strlen (name) >= sizeof (shortname))
3206 /* Return a filename which will cause callers to fail. */
3207 strcpy (shortname, "?");
3208 return shortname;
3211 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3213 register int left = 8; /* maximum number of chars in part */
3214 register int extn = 0; /* extension added? */
3215 register int dots = 2; /* maximum number of dots allowed */
3217 while (name < path)
3218 *str++ = *name++; /* skip past UNC header */
3220 while ((c = *name++))
3222 switch ( c )
3224 case ':':
3225 case '\\':
3226 case '/':
3227 *str++ = (c == ':' ? ':' : '\\');
3228 extn = 0; /* reset extension flags */
3229 dots = 2; /* max 2 dots */
3230 left = 8; /* max length 8 for main part */
3231 break;
3232 case '.':
3233 if ( dots )
3235 /* Convert path components of the form .xxx to _xxx,
3236 but leave . and .. as they are. This allows .emacs
3237 to be read as _emacs, for example. */
3239 if (! *name ||
3240 *name == '.' ||
3241 IS_DIRECTORY_SEP (*name))
3243 *str++ = '.';
3244 dots--;
3246 else
3248 *str++ = '_';
3249 left--;
3250 dots = 0;
3253 else if ( !extn )
3255 *str++ = '.';
3256 extn = 1; /* we've got an extension */
3257 left = 3; /* 3 chars in extension */
3259 else
3261 /* any embedded dots after the first are converted to _ */
3262 *str++ = '_';
3264 break;
3265 case '~':
3266 case '#': /* don't lose these, they're important */
3267 if ( ! left )
3268 str[-1] = c; /* replace last character of part */
3269 /* FALLTHRU */
3270 default:
3271 if ( left && 'A' <= c && c <= 'Z' )
3273 *str++ = tolower (c); /* map to lower case (looks nicer) */
3274 left--;
3275 dots = 0; /* started a path component */
3277 break;
3280 *str = '\0';
3282 else
3284 strcpy (shortname, name);
3285 unixtodos_filename (shortname);
3288 if (pPath)
3289 *pPath = shortname + (path - save_name);
3291 return shortname;
3294 static int
3295 is_exec (const char * name)
3297 char * p = strrchr (name, '.');
3298 return
3299 (p != NULL
3300 && (xstrcasecmp (p, ".exe") == 0 ||
3301 xstrcasecmp (p, ".com") == 0 ||
3302 xstrcasecmp (p, ".bat") == 0 ||
3303 xstrcasecmp (p, ".cmd") == 0));
3306 /* Emulate the Unix directory procedures opendir, closedir, and
3307 readdir. We rename them to sys_* names because some versions of
3308 MinGW startup code call opendir and readdir to glob wildcards, and
3309 the code that calls them doesn't grok UTF-8 encoded file names we
3310 produce in dirent->d_name[]. */
3312 struct dirent dir_static; /* simulated directory contents */
3313 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3314 static int dir_is_fat;
3315 static char dir_pathname[MAX_UTF8_PATH];
3316 static WIN32_FIND_DATAW dir_find_data_w;
3317 static WIN32_FIND_DATAA dir_find_data_a;
3318 #define DIR_FIND_DATA_W 1
3319 #define DIR_FIND_DATA_A 2
3320 static int last_dir_find_data = -1;
3322 /* Support shares on a network resource as subdirectories of a read-only
3323 root directory. */
3324 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3325 static HANDLE open_unc_volume (const char *);
3326 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3327 static void close_unc_volume (HANDLE);
3329 DIR *
3330 sys_opendir (const char *filename)
3332 DIR *dirp;
3334 /* Opening is done by FindFirstFile. However, a read is inherent to
3335 this operation, so we defer the open until read time. */
3337 if (dir_find_handle != INVALID_HANDLE_VALUE)
3338 return NULL;
3339 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3340 return NULL;
3342 /* Note: We don't support traversal of UNC volumes via symlinks.
3343 Doing so would mean punishing 99.99% of use cases by resolving
3344 all the possible symlinks in FILENAME, recursively. */
3345 if (is_unc_volume (filename))
3347 wnet_enum_handle = open_unc_volume (filename);
3348 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3349 return NULL;
3352 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3353 return NULL;
3355 dirp->dd_fd = 0;
3356 dirp->dd_loc = 0;
3357 dirp->dd_size = 0;
3359 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3360 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3361 /* Note: We don't support symlinks to file names on FAT volumes.
3362 Doing so would mean punishing 99.99% of use cases by resolving
3363 all the possible symlinks in FILENAME, recursively. */
3364 dir_is_fat = is_fat_volume (filename, NULL);
3366 return dirp;
3369 void
3370 sys_closedir (DIR *dirp)
3372 /* If we have a find-handle open, close it. */
3373 if (dir_find_handle != INVALID_HANDLE_VALUE)
3375 FindClose (dir_find_handle);
3376 dir_find_handle = INVALID_HANDLE_VALUE;
3378 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3380 close_unc_volume (wnet_enum_handle);
3381 wnet_enum_handle = INVALID_HANDLE_VALUE;
3383 xfree ((char *) dirp);
3386 struct dirent *
3387 sys_readdir (DIR *dirp)
3389 int downcase = !NILP (Vw32_downcase_file_names);
3391 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3393 if (!read_unc_volume (wnet_enum_handle,
3394 dir_find_data_w.cFileName,
3395 dir_find_data_a.cFileName,
3396 MAX_PATH))
3397 return NULL;
3399 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3400 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3402 char filename[MAX_UTF8_PATH + 2];
3403 int ln;
3405 strcpy (filename, dir_pathname);
3406 ln = strlen (filename);
3407 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3408 filename[ln++] = '\\';
3409 strcpy (filename + ln, "*");
3411 /* Note: No need to resolve symlinks in FILENAME, because
3412 FindFirst opens the directory that is the target of a
3413 symlink. */
3414 if (w32_unicode_filenames)
3416 wchar_t fnw[MAX_PATH];
3418 filename_to_utf16 (filename, fnw);
3419 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3421 else
3423 char fna[MAX_PATH];
3425 filename_to_ansi (filename, fna);
3426 /* If FILENAME is not representable by the current ANSI
3427 codepage, we don't want FindFirstFileA to interpret the
3428 '?' characters as a wildcard. */
3429 if (_mbspbrk (fna, "?"))
3430 dir_find_handle = INVALID_HANDLE_VALUE;
3431 else
3432 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3435 if (dir_find_handle == INVALID_HANDLE_VALUE)
3437 /* Any changes in the value of errno here should be in sync
3438 with what directory_files_internal does when it calls
3439 readdir. */
3440 switch (GetLastError ())
3442 /* Windows uses this value when FindFirstFile finds no
3443 files that match the wildcard. This is not supposed
3444 to happen, since our wildcard is "*", but just in
3445 case, if there's some weird empty directory with not
3446 even "." and ".." entries... */
3447 case ERROR_FILE_NOT_FOUND:
3448 errno = 0;
3449 /* FALLTHRU */
3450 default:
3451 break;
3452 case ERROR_ACCESS_DENIED:
3453 case ERROR_NETWORK_ACCESS_DENIED:
3454 errno = EACCES;
3455 break;
3456 case ERROR_PATH_NOT_FOUND:
3457 case ERROR_INVALID_DRIVE:
3458 case ERROR_NOT_READY:
3459 case ERROR_BAD_NETPATH:
3460 case ERROR_BAD_NET_NAME:
3461 errno = ENOENT;
3462 break;
3464 return NULL;
3467 else if (w32_unicode_filenames)
3469 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3471 errno = 0;
3472 return NULL;
3475 else
3477 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3479 errno = 0;
3480 return NULL;
3484 /* Emacs never uses this value, so don't bother making it match
3485 value returned by stat(). */
3486 dir_static.d_ino = 1;
3488 if (w32_unicode_filenames)
3490 if (downcase || dir_is_fat)
3492 wchar_t tem[MAX_PATH];
3494 wcscpy (tem, dir_find_data_w.cFileName);
3495 CharLowerW (tem);
3496 filename_from_utf16 (tem, dir_static.d_name);
3498 else
3499 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3500 last_dir_find_data = DIR_FIND_DATA_W;
3502 else
3504 char tem[MAX_PATH];
3506 /* If the file name in cFileName[] includes `?' characters, it
3507 means the original file name used characters that cannot be
3508 represented by the current ANSI codepage. To avoid total
3509 lossage, retrieve the short 8+3 alias of the long file
3510 name. */
3511 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3513 strcpy (tem, dir_find_data_a.cAlternateFileName);
3514 /* 8+3 aliases are returned in all caps, which could break
3515 various alists that look at filenames' extensions. */
3516 downcase = 1;
3518 else if (downcase || dir_is_fat)
3519 strcpy (tem, dir_find_data_a.cFileName);
3520 else
3521 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3522 if (downcase || dir_is_fat)
3524 _mbslwr (tem);
3525 filename_from_ansi (tem, dir_static.d_name);
3527 last_dir_find_data = DIR_FIND_DATA_A;
3530 dir_static.d_namlen = strlen (dir_static.d_name);
3531 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3532 dir_static.d_namlen - dir_static.d_namlen % 4;
3534 return &dir_static;
3537 static HANDLE
3538 open_unc_volume (const char *path)
3540 const char *fn = map_w32_filename (path, NULL);
3541 DWORD result;
3542 HANDLE henum;
3544 if (w32_unicode_filenames)
3546 NETRESOURCEW nrw;
3547 wchar_t fnw[MAX_PATH];
3549 nrw.dwScope = RESOURCE_GLOBALNET;
3550 nrw.dwType = RESOURCETYPE_DISK;
3551 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3552 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3553 nrw.lpLocalName = NULL;
3554 filename_to_utf16 (fn, fnw);
3555 nrw.lpRemoteName = fnw;
3556 nrw.lpComment = NULL;
3557 nrw.lpProvider = NULL;
3559 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3560 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3562 else
3564 NETRESOURCEA nra;
3565 char fna[MAX_PATH];
3567 nra.dwScope = RESOURCE_GLOBALNET;
3568 nra.dwType = RESOURCETYPE_DISK;
3569 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3570 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3571 nra.lpLocalName = NULL;
3572 filename_to_ansi (fn, fna);
3573 nra.lpRemoteName = fna;
3574 nra.lpComment = NULL;
3575 nra.lpProvider = NULL;
3577 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3578 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3580 if (result == NO_ERROR)
3581 return henum;
3582 else
3584 /* Make sure directory_files_internal reports a sensible error. */
3585 errno = ENOENT;
3586 return INVALID_HANDLE_VALUE;
3590 static void *
3591 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3593 DWORD count;
3594 int result;
3595 char *buffer;
3596 DWORD bufsize = 512;
3597 void *retval;
3599 count = 1;
3600 if (w32_unicode_filenames)
3602 wchar_t *ptrw;
3604 bufsize *= 2;
3605 buffer = alloca (bufsize);
3606 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3607 if (result != NO_ERROR)
3608 return NULL;
3609 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3610 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3611 ptrw += 2;
3612 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3613 ptrw++;
3614 wcsncpy (fname_w, ptrw, size);
3615 retval = fname_w;
3617 else
3619 int dbcs_p = max_filename_mbslen () > 1;
3620 char *ptra;
3622 buffer = alloca (bufsize);
3623 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3624 if (result != NO_ERROR)
3625 return NULL;
3626 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3627 ptra += 2;
3628 if (!dbcs_p)
3629 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3630 else
3632 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3633 ptra = CharNextExA (file_name_codepage, ptra, 0);
3635 ptra++;
3636 strncpy (fname_a, ptra, size);
3637 retval = fname_a;
3640 return retval;
3643 static void
3644 close_unc_volume (HANDLE henum)
3646 if (henum != INVALID_HANDLE_VALUE)
3647 WNetCloseEnum (henum);
3650 static DWORD
3651 unc_volume_file_attributes (const char *path)
3653 HANDLE henum;
3654 DWORD attrs;
3656 henum = open_unc_volume (path);
3657 if (henum == INVALID_HANDLE_VALUE)
3658 return -1;
3660 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3662 close_unc_volume (henum);
3664 return attrs;
3667 /* Ensure a network connection is authenticated. */
3668 static void
3669 logon_network_drive (const char *path)
3671 char share[MAX_UTF8_PATH];
3672 int n_slashes;
3673 char drive[4];
3674 UINT drvtype;
3675 char *p;
3676 DWORD val;
3678 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3679 drvtype = DRIVE_REMOTE;
3680 else if (path[0] == '\0' || path[1] != ':')
3681 drvtype = GetDriveType (NULL);
3682 else
3684 drive[0] = path[0];
3685 drive[1] = ':';
3686 drive[2] = '\\';
3687 drive[3] = '\0';
3688 drvtype = GetDriveType (drive);
3691 /* Only logon to networked drives. */
3692 if (drvtype != DRIVE_REMOTE)
3693 return;
3695 n_slashes = 2;
3696 strncpy (share, path, MAX_UTF8_PATH);
3697 /* Truncate to just server and share name. */
3698 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3700 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3702 *p = '\0';
3703 break;
3707 if (w32_unicode_filenames)
3709 NETRESOURCEW resourcew;
3710 wchar_t share_w[MAX_PATH];
3712 resourcew.dwScope = RESOURCE_GLOBALNET;
3713 resourcew.dwType = RESOURCETYPE_DISK;
3714 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3715 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3716 resourcew.lpLocalName = NULL;
3717 filename_to_utf16 (share, share_w);
3718 resourcew.lpRemoteName = share_w;
3719 resourcew.lpProvider = NULL;
3721 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3723 else
3725 NETRESOURCEA resourcea;
3726 char share_a[MAX_PATH];
3728 resourcea.dwScope = RESOURCE_GLOBALNET;
3729 resourcea.dwType = RESOURCETYPE_DISK;
3730 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3731 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3732 resourcea.lpLocalName = NULL;
3733 filename_to_ansi (share, share_a);
3734 resourcea.lpRemoteName = share_a;
3735 resourcea.lpProvider = NULL;
3737 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3740 switch (val)
3742 case NO_ERROR:
3743 case ERROR_ALREADY_ASSIGNED:
3744 break;
3745 case ERROR_ACCESS_DENIED:
3746 case ERROR_LOGON_FAILURE:
3747 errno = EACCES;
3748 break;
3749 case ERROR_BUSY:
3750 errno = EAGAIN;
3751 break;
3752 case ERROR_BAD_NET_NAME:
3753 case ERROR_NO_NET_OR_BAD_PATH:
3754 case ERROR_NO_NETWORK:
3755 case ERROR_CANCELLED:
3756 default:
3757 errno = ENOENT;
3758 break;
3762 /* Emulate faccessat(2). */
3764 faccessat (int dirfd, const char * path, int mode, int flags)
3766 DWORD attributes;
3768 if (dirfd != AT_FDCWD
3769 && !(IS_DIRECTORY_SEP (path[0])
3770 || IS_DEVICE_SEP (path[1])))
3772 errno = EBADF;
3773 return -1;
3776 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3777 newer versions blow up when passed D_OK. */
3778 path = map_w32_filename (path, NULL);
3779 /* If the last element of PATH is a symlink, we need to resolve it
3780 to get the attributes of its target file. Note: any symlinks in
3781 PATH elements other than the last one are transparently resolved
3782 by GetFileAttributes below. */
3783 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3784 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3785 path = chase_symlinks (path);
3787 if (w32_unicode_filenames)
3789 wchar_t path_w[MAX_PATH];
3791 filename_to_utf16 (path, path_w);
3792 attributes = GetFileAttributesW (path_w);
3794 else
3796 char path_a[MAX_PATH];
3798 filename_to_ansi (path, path_a);
3799 attributes = GetFileAttributesA (path_a);
3802 if (attributes == -1)
3804 DWORD w32err = GetLastError ();
3806 switch (w32err)
3808 case ERROR_INVALID_NAME:
3809 case ERROR_BAD_PATHNAME:
3810 if (is_unc_volume (path))
3812 attributes = unc_volume_file_attributes (path);
3813 if (attributes == -1)
3815 errno = EACCES;
3816 return -1;
3818 break;
3820 /* FALLTHROUGH */
3821 case ERROR_FILE_NOT_FOUND:
3822 case ERROR_BAD_NETPATH:
3823 errno = ENOENT;
3824 break;
3825 default:
3826 errno = EACCES;
3827 break;
3829 return -1;
3831 if ((mode & X_OK) != 0
3832 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3834 errno = EACCES;
3835 return -1;
3837 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3839 errno = EACCES;
3840 return -1;
3842 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3844 errno = EACCES;
3845 return -1;
3847 return 0;
3850 /* A version of 'access' to be used locally with file names in
3851 locale-specific encoding. Does not resolve symlinks and does not
3852 support file names on FAT12 and FAT16 volumes, but that's OK, since
3853 we only invoke this function for files inside the Emacs source or
3854 installation tree, on directories (so any symlinks should have the
3855 directory bit set), and on short file names such as "C:/.emacs". */
3856 static int
3857 sys_access (const char *fname, int mode)
3859 char fname_copy[MAX_PATH], *p;
3860 DWORD attributes;
3862 strcpy (fname_copy, fname);
3863 /* Do the equivalent of unixtodos_filename. */
3864 for (p = fname_copy; *p; p = CharNext (p))
3865 if (*p == '/')
3866 *p = '\\';
3868 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
3870 DWORD w32err = GetLastError ();
3872 switch (w32err)
3874 case ERROR_INVALID_NAME:
3875 case ERROR_BAD_PATHNAME:
3876 case ERROR_FILE_NOT_FOUND:
3877 case ERROR_BAD_NETPATH:
3878 errno = ENOENT;
3879 break;
3880 default:
3881 errno = EACCES;
3882 break;
3884 return -1;
3886 if ((mode & X_OK) != 0
3887 && !(is_exec (fname_copy)
3888 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3890 errno = EACCES;
3891 return -1;
3893 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3895 errno = EACCES;
3896 return -1;
3898 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3900 errno = EACCES;
3901 return -1;
3903 return 0;
3906 /* Shadow some MSVC runtime functions to map requests for long filenames
3907 to reasonable short names if necessary. This was originally added to
3908 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3909 long file names. */
3912 sys_chdir (const char * path)
3914 path = map_w32_filename (path, NULL);
3915 if (w32_unicode_filenames)
3917 wchar_t newdir_w[MAX_PATH];
3919 if (filename_to_utf16 (path, newdir_w) == 0)
3920 return _wchdir (newdir_w);
3921 return -1;
3923 else
3925 char newdir_a[MAX_PATH];
3927 if (filename_to_ansi (path, newdir_a) == 0)
3928 return _chdir (newdir_a);
3929 return -1;
3934 sys_chmod (const char * path, int mode)
3936 path = chase_symlinks (map_w32_filename (path, NULL));
3937 if (w32_unicode_filenames)
3939 wchar_t path_w[MAX_PATH];
3941 filename_to_utf16 (path, path_w);
3942 return _wchmod (path_w, mode);
3944 else
3946 char path_a[MAX_PATH];
3948 filename_to_ansi (path, path_a);
3949 return _chmod (path_a, mode);
3954 sys_creat (const char * path, int mode)
3956 path = map_w32_filename (path, NULL);
3957 if (w32_unicode_filenames)
3959 wchar_t path_w[MAX_PATH];
3961 filename_to_utf16 (path, path_w);
3962 return _wcreat (path_w, mode);
3964 else
3966 char path_a[MAX_PATH];
3968 filename_to_ansi (path, path_a);
3969 return _creat (path_a, mode);
3973 FILE *
3974 sys_fopen (const char * path, const char * mode)
3976 int fd;
3977 int oflag;
3978 const char * mode_save = mode;
3980 /* Force all file handles to be non-inheritable. This is necessary to
3981 ensure child processes don't unwittingly inherit handles that might
3982 prevent future file access. */
3984 if (mode[0] == 'r')
3985 oflag = O_RDONLY;
3986 else if (mode[0] == 'w' || mode[0] == 'a')
3987 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3988 else
3989 return NULL;
3991 /* Only do simplistic option parsing. */
3992 while (*++mode)
3993 if (mode[0] == '+')
3995 oflag &= ~(O_RDONLY | O_WRONLY);
3996 oflag |= O_RDWR;
3998 else if (mode[0] == 'b')
4000 oflag &= ~O_TEXT;
4001 oflag |= O_BINARY;
4003 else if (mode[0] == 't')
4005 oflag &= ~O_BINARY;
4006 oflag |= O_TEXT;
4008 else break;
4010 path = map_w32_filename (path, NULL);
4011 if (w32_unicode_filenames)
4013 wchar_t path_w[MAX_PATH];
4015 filename_to_utf16 (path, path_w);
4016 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4018 else
4020 char path_a[MAX_PATH];
4022 filename_to_ansi (path, path_a);
4023 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4025 if (fd < 0)
4026 return NULL;
4028 return _fdopen (fd, mode_save);
4031 /* This only works on NTFS volumes, but is useful to have. */
4033 sys_link (const char * old, const char * new)
4035 HANDLE fileh;
4036 int result = -1;
4037 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4038 wchar_t oldname_w[MAX_PATH];
4039 char oldname_a[MAX_PATH];
4041 if (old == NULL || new == NULL)
4043 errno = ENOENT;
4044 return -1;
4047 strcpy (oldname, map_w32_filename (old, NULL));
4048 strcpy (newname, map_w32_filename (new, NULL));
4050 if (w32_unicode_filenames)
4052 filename_to_utf16 (oldname, oldname_w);
4053 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4054 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4056 else
4058 filename_to_ansi (oldname, oldname_a);
4059 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4060 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4062 if (fileh != INVALID_HANDLE_VALUE)
4064 int wlen;
4066 /* Confusingly, the "alternate" stream name field does not apply
4067 when restoring a hard link, and instead contains the actual
4068 stream data for the link (ie. the name of the link to create).
4069 The WIN32_STREAM_ID structure before the cStreamName field is
4070 the stream header, which is then immediately followed by the
4071 stream data. */
4073 struct {
4074 WIN32_STREAM_ID wid;
4075 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4076 } data;
4078 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4079 indicates that flag is unsupported for CP_UTF8, and OTOH says
4080 it is the default anyway. */
4081 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4082 data.wid.cStreamName, MAX_PATH);
4083 if (wlen > 0)
4085 LPVOID context = NULL;
4086 DWORD wbytes = 0;
4088 data.wid.dwStreamId = BACKUP_LINK;
4089 data.wid.dwStreamAttributes = 0;
4090 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4091 data.wid.Size.HighPart = 0;
4092 data.wid.dwStreamNameSize = 0;
4094 if (BackupWrite (fileh, (LPBYTE)&data,
4095 offsetof (WIN32_STREAM_ID, cStreamName)
4096 + data.wid.Size.LowPart,
4097 &wbytes, FALSE, FALSE, &context)
4098 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4100 /* succeeded */
4101 result = 0;
4103 else
4105 DWORD err = GetLastError ();
4106 DWORD attributes;
4108 switch (err)
4110 case ERROR_ACCESS_DENIED:
4111 /* This is what happens when OLDNAME is a directory,
4112 since Windows doesn't support hard links to
4113 directories. Posix says to set errno to EPERM in
4114 that case. */
4115 if (w32_unicode_filenames)
4116 attributes = GetFileAttributesW (oldname_w);
4117 else
4118 attributes = GetFileAttributesA (oldname_a);
4119 if (attributes != -1
4120 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4121 errno = EPERM;
4122 else if (attributes == -1
4123 && is_unc_volume (oldname)
4124 && unc_volume_file_attributes (oldname) != -1)
4125 errno = EPERM;
4126 else
4127 errno = EACCES;
4128 break;
4129 case ERROR_TOO_MANY_LINKS:
4130 errno = EMLINK;
4131 break;
4132 case ERROR_NOT_SAME_DEVICE:
4133 errno = EXDEV;
4134 break;
4135 default:
4136 errno = EINVAL;
4137 break;
4142 CloseHandle (fileh);
4144 else
4145 errno = ENOENT;
4147 return result;
4151 sys_mkdir (const char * path)
4153 path = map_w32_filename (path, NULL);
4155 if (w32_unicode_filenames)
4157 wchar_t path_w[MAX_PATH];
4159 filename_to_utf16 (path, path_w);
4160 return _wmkdir (path_w);
4162 else
4164 char path_a[MAX_PATH];
4166 filename_to_ansi (path, path_a);
4167 return _mkdir (path_a);
4172 sys_open (const char * path, int oflag, int mode)
4174 const char* mpath = map_w32_filename (path, NULL);
4175 int res = -1;
4177 if (w32_unicode_filenames)
4179 wchar_t mpath_w[MAX_PATH];
4181 filename_to_utf16 (mpath, mpath_w);
4182 /* If possible, try to open file without _O_CREAT, to be able to
4183 write to existing hidden and system files. Force all file
4184 handles to be non-inheritable. */
4185 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4186 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4187 if (res < 0)
4188 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4190 else
4192 char mpath_a[MAX_PATH];
4194 filename_to_ansi (mpath, mpath_a);
4195 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4196 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4197 if (res < 0)
4198 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4201 return res;
4204 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4205 when using mktemp.
4207 Standard algorithm for generating a temporary file name seems to be
4208 use pid or tid with a letter on the front (in place of the 6 X's)
4209 and cycle through the letters to find a unique name. We extend
4210 that to allow any reasonable character as the first of the 6 X's,
4211 so that the number of simultaneously used temporary files will be
4212 greater. */
4215 mkostemp (char * template, int flags)
4217 char * p;
4218 int i, fd = -1;
4219 unsigned uid = GetCurrentThreadId ();
4220 int save_errno = errno;
4221 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4223 errno = EINVAL;
4224 if (template == NULL)
4225 return -1;
4227 p = template + strlen (template);
4228 i = 5;
4229 /* replace up to the last 5 X's with uid in decimal */
4230 while (--p >= template && p[0] == 'X' && --i >= 0)
4232 p[0] = '0' + uid % 10;
4233 uid /= 10;
4236 if (i < 0 && p[0] == 'X')
4238 i = 0;
4241 p[0] = first_char[i];
4242 if ((fd = sys_open (template,
4243 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4244 S_IRUSR | S_IWUSR)) >= 0
4245 || errno != EEXIST)
4247 if (fd >= 0)
4248 errno = save_errno;
4249 return fd;
4252 while (++i < sizeof (first_char));
4255 /* Template is badly formed or else we can't generate a unique name. */
4256 return -1;
4260 fchmod (int fd, mode_t mode)
4262 return 0;
4266 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4268 BOOL result;
4269 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4270 int newname_dev;
4271 int oldname_dev;
4272 bool have_temp_a = false;
4274 /* MoveFile on Windows 95 doesn't correctly change the short file name
4275 alias in a number of circumstances (it is not easy to predict when
4276 just by looking at oldname and newname, unfortunately). In these
4277 cases, renaming through a temporary name avoids the problem.
4279 A second problem on Windows 95 is that renaming through a temp name when
4280 newname is uppercase fails (the final long name ends up in
4281 lowercase, although the short alias might be uppercase) UNLESS the
4282 long temp name is not 8.3.
4284 So, on Windows 95 we always rename through a temp name, and we make sure
4285 the temp name has a long extension to ensure correct renaming. */
4287 strcpy (temp, map_w32_filename (oldname, NULL));
4289 /* volume_info is set indirectly by map_w32_filename. */
4290 oldname_dev = volume_info.serialnum;
4292 if (os_subtype == OS_9X)
4294 char * o;
4295 char * p;
4296 int i = 0;
4297 char oldname_a[MAX_PATH];
4299 oldname = map_w32_filename (oldname, NULL);
4300 filename_to_ansi (oldname, oldname_a);
4301 filename_to_ansi (temp, temp_a);
4302 if ((o = strrchr (oldname_a, '\\')))
4303 o++;
4304 else
4305 o = (char *) oldname_a;
4307 if ((p = strrchr (temp_a, '\\')))
4308 p++;
4309 else
4310 p = temp_a;
4314 /* Force temp name to require a manufactured 8.3 alias - this
4315 seems to make the second rename work properly. */
4316 sprintf (p, "_.%s.%u", o, i);
4317 i++;
4318 result = rename (oldname_a, temp_a);
4320 /* This loop must surely terminate! */
4321 while (result < 0 && errno == EEXIST);
4322 if (result < 0)
4323 return -1;
4324 have_temp_a = true;
4327 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4328 (at least if it is a file; don't do this for directories).
4330 Since we mustn't do this if we are just changing the case of the
4331 file name (we would end up deleting the file we are trying to
4332 rename!), we let rename detect if the destination file already
4333 exists - that way we avoid the possible pitfalls of trying to
4334 determine ourselves whether two names really refer to the same
4335 file, which is not always possible in the general case. (Consider
4336 all the permutations of shared or subst'd drives, etc.) */
4338 newname = map_w32_filename (newname, NULL);
4340 /* volume_info is set indirectly by map_w32_filename. */
4341 newname_dev = volume_info.serialnum;
4343 if (w32_unicode_filenames)
4345 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4347 filename_to_utf16 (temp, temp_w);
4348 filename_to_utf16 (newname, newname_w);
4349 result = _wrename (temp_w, newname_w);
4350 if (result < 0 && force)
4352 DWORD w32err = GetLastError ();
4354 if (errno == EACCES
4355 && newname_dev != oldname_dev)
4357 /* The implementation of `rename' on Windows does not return
4358 errno = EXDEV when you are moving a directory to a
4359 different storage device (ex. logical disk). It returns
4360 EACCES instead. So here we handle such situations and
4361 return EXDEV. */
4362 DWORD attributes;
4364 if ((attributes = GetFileAttributesW (temp_w)) != -1
4365 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4366 errno = EXDEV;
4368 else if (errno == EEXIST)
4370 if (_wchmod (newname_w, 0666) != 0)
4371 return result;
4372 if (_wunlink (newname_w) != 0)
4373 return result;
4374 result = _wrename (temp_w, newname_w);
4376 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4377 && is_symlink (temp))
4379 /* This is Windows prohibiting the user from creating a
4380 symlink in another place, since that requires
4381 privileges. */
4382 errno = EPERM;
4386 else
4388 char newname_a[MAX_PATH];
4390 if (!have_temp_a)
4391 filename_to_ansi (temp, temp_a);
4392 filename_to_ansi (newname, newname_a);
4393 result = rename (temp_a, newname_a);
4394 if (result < 0 && force)
4396 DWORD w32err = GetLastError ();
4398 if (errno == EACCES
4399 && newname_dev != oldname_dev)
4401 DWORD attributes;
4403 if ((attributes = GetFileAttributesA (temp_a)) != -1
4404 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4405 errno = EXDEV;
4407 else if (errno == EEXIST)
4409 if (_chmod (newname_a, 0666) != 0)
4410 return result;
4411 if (_unlink (newname_a) != 0)
4412 return result;
4413 result = rename (temp_a, newname_a);
4415 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4416 && is_symlink (temp))
4417 errno = EPERM;
4421 return result;
4425 sys_rename (char const *old, char const *new)
4427 return sys_rename_replace (old, new, TRUE);
4431 sys_rmdir (const char * path)
4433 path = map_w32_filename (path, NULL);
4435 if (w32_unicode_filenames)
4437 wchar_t path_w[MAX_PATH];
4439 filename_to_utf16 (path, path_w);
4440 return _wrmdir (path_w);
4442 else
4444 char path_a[MAX_PATH];
4446 filename_to_ansi (path, path_a);
4447 return _rmdir (path_a);
4452 sys_unlink (const char * path)
4454 path = map_w32_filename (path, NULL);
4456 if (w32_unicode_filenames)
4458 wchar_t path_w[MAX_PATH];
4460 filename_to_utf16 (path, path_w);
4461 /* On Unix, unlink works without write permission. */
4462 _wchmod (path_w, 0666);
4463 return _wunlink (path_w);
4465 else
4467 char path_a[MAX_PATH];
4469 filename_to_ansi (path, path_a);
4470 _chmod (path_a, 0666);
4471 return _unlink (path_a);
4475 static FILETIME utc_base_ft;
4476 static ULONGLONG utc_base; /* In 100ns units */
4477 static int init = 0;
4479 #define FILETIME_TO_U64(result, ft) \
4480 do { \
4481 ULARGE_INTEGER uiTemp; \
4482 uiTemp.LowPart = (ft).dwLowDateTime; \
4483 uiTemp.HighPart = (ft).dwHighDateTime; \
4484 result = uiTemp.QuadPart; \
4485 } while (0)
4487 static void
4488 initialize_utc_base (void)
4490 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4491 SYSTEMTIME st;
4493 st.wYear = 1970;
4494 st.wMonth = 1;
4495 st.wDay = 1;
4496 st.wHour = 0;
4497 st.wMinute = 0;
4498 st.wSecond = 0;
4499 st.wMilliseconds = 0;
4501 SystemTimeToFileTime (&st, &utc_base_ft);
4502 FILETIME_TO_U64 (utc_base, utc_base_ft);
4505 static time_t
4506 convert_time (FILETIME ft)
4508 ULONGLONG tmp;
4510 if (!init)
4512 initialize_utc_base ();
4513 init = 1;
4516 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4517 return 0;
4519 FILETIME_TO_U64 (tmp, ft);
4520 return (time_t) ((tmp - utc_base) / 10000000L);
4523 static void
4524 convert_from_time_t (time_t time, FILETIME * pft)
4526 ULARGE_INTEGER tmp;
4528 if (!init)
4530 initialize_utc_base ();
4531 init = 1;
4534 /* time in 100ns units since 1-Jan-1601 */
4535 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4536 pft->dwHighDateTime = tmp.HighPart;
4537 pft->dwLowDateTime = tmp.LowPart;
4540 static PSECURITY_DESCRIPTOR
4541 get_file_security_desc_by_handle (HANDLE h)
4543 PSECURITY_DESCRIPTOR psd = NULL;
4544 DWORD err;
4545 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4546 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4548 err = get_security_info (h, SE_FILE_OBJECT, si,
4549 NULL, NULL, NULL, NULL, &psd);
4550 if (err != ERROR_SUCCESS)
4551 return NULL;
4553 return psd;
4556 static PSECURITY_DESCRIPTOR
4557 get_file_security_desc_by_name (const char *fname)
4559 PSECURITY_DESCRIPTOR psd = NULL;
4560 DWORD sd_len, err;
4561 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4562 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4564 if (!get_file_security (fname, si, psd, 0, &sd_len))
4566 err = GetLastError ();
4567 if (err != ERROR_INSUFFICIENT_BUFFER)
4568 return NULL;
4571 psd = xmalloc (sd_len);
4572 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4574 xfree (psd);
4575 return NULL;
4578 return psd;
4581 static DWORD
4582 get_rid (PSID sid)
4584 unsigned n_subauthorities;
4586 /* Use the last sub-authority value of the RID, the relative
4587 portion of the SID, as user/group ID. */
4588 n_subauthorities = *get_sid_sub_authority_count (sid);
4589 if (n_subauthorities < 1)
4590 return 0; /* the "World" RID */
4591 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4594 /* Caching SID and account values for faster lokup. */
4596 struct w32_id {
4597 unsigned rid;
4598 struct w32_id *next;
4599 char name[GNLEN+1];
4600 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4603 static struct w32_id *w32_idlist;
4605 static int
4606 w32_cached_id (PSID sid, unsigned *id, char *name)
4608 struct w32_id *tail, *found;
4610 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4612 if (equal_sid ((PSID)tail->sid, sid))
4614 found = tail;
4615 break;
4618 if (found)
4620 *id = found->rid;
4621 strcpy (name, found->name);
4622 return 1;
4624 else
4625 return 0;
4628 static void
4629 w32_add_to_cache (PSID sid, unsigned id, char *name)
4631 DWORD sid_len;
4632 struct w32_id *new_entry;
4634 /* We don't want to leave behind stale cache from when Emacs was
4635 dumped. */
4636 if (initialized)
4638 sid_len = get_length_sid (sid);
4639 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4640 if (new_entry)
4642 new_entry->rid = id;
4643 strcpy (new_entry->name, name);
4644 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4645 new_entry->next = w32_idlist;
4646 w32_idlist = new_entry;
4651 #define UID 1
4652 #define GID 2
4654 static int
4655 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4657 PSID sid = NULL;
4658 BOOL dflt;
4659 SID_NAME_USE ignore;
4660 char name[UNLEN+1];
4661 DWORD name_len = sizeof (name);
4662 char domain[1024];
4663 DWORD domain_len = sizeof (domain);
4664 int use_dflt = 0;
4665 int result;
4667 if (what == UID)
4668 result = get_security_descriptor_owner (psd, &sid, &dflt);
4669 else if (what == GID)
4670 result = get_security_descriptor_group (psd, &sid, &dflt);
4671 else
4672 result = 0;
4674 if (!result || !is_valid_sid (sid))
4675 use_dflt = 1;
4676 else if (!w32_cached_id (sid, id, nm))
4678 if (!lookup_account_sid (NULL, sid, name, &name_len,
4679 domain, &domain_len, &ignore)
4680 || name_len > UNLEN+1)
4681 use_dflt = 1;
4682 else
4684 *id = get_rid (sid);
4685 strcpy (nm, name);
4686 w32_add_to_cache (sid, *id, name);
4689 return use_dflt;
4692 static void
4693 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4695 int dflt_usr = 0, dflt_grp = 0;
4697 if (!psd)
4699 dflt_usr = 1;
4700 dflt_grp = 1;
4702 else
4704 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4705 dflt_usr = 1;
4706 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4707 dflt_grp = 1;
4709 /* Consider files to belong to current user/group, if we cannot get
4710 more accurate information. */
4711 if (dflt_usr)
4713 st->st_uid = dflt_passwd.pw_uid;
4714 strcpy (st->st_uname, dflt_passwd.pw_name);
4716 if (dflt_grp)
4718 st->st_gid = dflt_passwd.pw_gid;
4719 strcpy (st->st_gname, dflt_group.gr_name);
4723 /* Return non-zero if NAME is a potentially slow filesystem. */
4725 is_slow_fs (const char *name)
4727 char drive_root[4];
4728 UINT devtype;
4730 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4731 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4732 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4733 devtype = GetDriveType (NULL); /* use root of current drive */
4734 else
4736 /* GetDriveType needs the root directory of the drive. */
4737 strncpy (drive_root, name, 2);
4738 drive_root[2] = '\\';
4739 drive_root[3] = '\0';
4740 devtype = GetDriveType (drive_root);
4742 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4745 /* If this is non-zero, the caller wants accurate information about
4746 file's owner and group, which could be expensive to get. dired.c
4747 uses this flag when needed for the job at hand. */
4748 int w32_stat_get_owner_group;
4750 /* MSVC stat function can't cope with UNC names and has other bugs, so
4751 replace it with our own. This also allows us to calculate consistent
4752 inode values and owner/group without hacks in the main Emacs code,
4753 and support file names encoded in UTF-8. */
4755 static int
4756 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4758 char *name, *save_name, *r;
4759 WIN32_FIND_DATAW wfd_w;
4760 WIN32_FIND_DATAA wfd_a;
4761 HANDLE fh;
4762 unsigned __int64 fake_inode = 0;
4763 int permission;
4764 int len;
4765 int rootdir = FALSE;
4766 PSECURITY_DESCRIPTOR psd = NULL;
4767 int is_a_symlink = 0;
4768 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4769 DWORD access_rights = 0;
4770 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4771 FILETIME ctime, atime, wtime;
4772 wchar_t name_w[MAX_PATH];
4773 char name_a[MAX_PATH];
4775 if (path == NULL || buf == NULL)
4777 errno = EFAULT;
4778 return -1;
4781 save_name = name = (char *) map_w32_filename (path, &path);
4782 /* Must be valid filename, no wild cards or other invalid
4783 characters. */
4784 if (strpbrk (name, "*?|<>\""))
4786 errno = ENOENT;
4787 return -1;
4790 len = strlen (name);
4791 /* Allocate 1 extra byte so that we could append a slash to a root
4792 directory, down below. */
4793 name = strcpy (alloca (len + 2), name);
4795 /* Avoid a somewhat costly call to is_symlink if the filesystem
4796 doesn't support symlinks. */
4797 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4798 is_a_symlink = is_symlink (name);
4800 /* Plan A: Open the file and get all the necessary information via
4801 the resulting handle. This solves several issues in one blow:
4803 . retrieves attributes for the target of a symlink, if needed
4804 . gets attributes of root directories and symlinks pointing to
4805 root directories, thus avoiding the need for special-casing
4806 these and detecting them by examining the file-name format
4807 . retrieves more accurate attributes (e.g., non-zero size for
4808 some directories, esp. directories that are junction points)
4809 . correctly resolves "c:/..", "/.." and similar file names
4810 . avoids run-time penalties for 99% of use cases
4812 Plan A is always tried first, unless the user asked not to (but
4813 if the file is a symlink and we need to follow links, we try Plan
4814 A even if the user asked not to).
4816 If Plan A fails, we go to Plan B (below), where various
4817 potentially expensive techniques must be used to handle "special"
4818 files such as UNC volumes etc. */
4819 if (!(NILP (Vw32_get_true_file_attributes)
4820 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4821 /* Following symlinks requires getting the info by handle. */
4822 || (is_a_symlink && follow_symlinks))
4824 BY_HANDLE_FILE_INFORMATION info;
4826 if (is_a_symlink && !follow_symlinks)
4827 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4828 /* READ_CONTROL access rights are required to get security info
4829 by handle. But if the OS doesn't support security in the
4830 first place, we don't need to try. */
4831 if (is_windows_9x () != TRUE)
4832 access_rights |= READ_CONTROL;
4834 if (w32_unicode_filenames)
4836 filename_to_utf16 (name, name_w);
4837 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4838 file_flags, NULL);
4839 /* If CreateFile fails with READ_CONTROL, try again with
4840 zero as access rights. */
4841 if (fh == INVALID_HANDLE_VALUE && access_rights)
4842 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
4843 file_flags, NULL);
4845 else
4847 filename_to_ansi (name, name_a);
4848 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
4849 file_flags, NULL);
4850 if (fh == INVALID_HANDLE_VALUE && access_rights)
4851 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
4852 file_flags, NULL);
4854 if (fh == INVALID_HANDLE_VALUE)
4855 goto no_true_file_attributes;
4857 /* This is more accurate in terms of getting the correct number
4858 of links, but is quite slow (it is noticeable when Emacs is
4859 making a list of file name completions). */
4860 if (GetFileInformationByHandle (fh, &info))
4862 nlinks = info.nNumberOfLinks;
4863 /* Might as well use file index to fake inode values, but this
4864 is not guaranteed to be unique unless we keep a handle open
4865 all the time (even then there are situations where it is
4866 not unique). Reputedly, there are at most 48 bits of info
4867 (on NTFS, presumably less on FAT). */
4868 fake_inode = info.nFileIndexHigh;
4869 fake_inode <<= 32;
4870 fake_inode += info.nFileIndexLow;
4871 serialnum = info.dwVolumeSerialNumber;
4872 fs_high = info.nFileSizeHigh;
4873 fs_low = info.nFileSizeLow;
4874 ctime = info.ftCreationTime;
4875 atime = info.ftLastAccessTime;
4876 wtime = info.ftLastWriteTime;
4877 fattrs = info.dwFileAttributes;
4879 else
4881 /* We don't go to Plan B here, because it's not clear that
4882 it's a good idea. The only known use case where
4883 CreateFile succeeds, but GetFileInformationByHandle fails
4884 (with ERROR_INVALID_FUNCTION) is for character devices
4885 such as NUL, PRN, etc. For these, switching to Plan B is
4886 a net loss, because we lose the character device
4887 attribute returned by GetFileType below (FindFirstFile
4888 doesn't set that bit in the attributes), and the other
4889 fields don't make sense for character devices anyway.
4890 Emacs doesn't really care for non-file entities in the
4891 context of l?stat, so neither do we. */
4893 /* w32err is assigned so one could put a breakpoint here and
4894 examine its value, when GetFileInformationByHandle
4895 fails. */
4896 DWORD w32err = GetLastError ();
4898 switch (w32err)
4900 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4901 errno = ENOENT;
4902 return -1;
4906 /* Test for a symlink before testing for a directory, since
4907 symlinks to directories have the directory bit set, but we
4908 don't want them to appear as directories. */
4909 if (is_a_symlink && !follow_symlinks)
4910 buf->st_mode = S_IFLNK;
4911 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4912 buf->st_mode = S_IFDIR;
4913 else
4915 DWORD ftype = GetFileType (fh);
4917 switch (ftype)
4919 case FILE_TYPE_DISK:
4920 buf->st_mode = S_IFREG;
4921 break;
4922 case FILE_TYPE_PIPE:
4923 buf->st_mode = S_IFIFO;
4924 break;
4925 case FILE_TYPE_CHAR:
4926 case FILE_TYPE_UNKNOWN:
4927 default:
4928 buf->st_mode = S_IFCHR;
4931 /* We produce the fallback owner and group data, based on the
4932 current user that runs Emacs, in the following cases:
4934 . caller didn't request owner and group info
4935 . this is Windows 9X
4936 . getting security by handle failed, and we need to produce
4937 information for the target of a symlink (this is better
4938 than producing a potentially misleading info about the
4939 symlink itself)
4941 If getting security by handle fails, and we don't need to
4942 resolve symlinks, we try getting security by name. */
4943 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4944 get_file_owner_and_group (NULL, buf);
4945 else
4947 psd = get_file_security_desc_by_handle (fh);
4948 if (psd)
4950 get_file_owner_and_group (psd, buf);
4951 LocalFree (psd);
4953 else if (!(is_a_symlink && follow_symlinks))
4955 psd = get_file_security_desc_by_name (name);
4956 get_file_owner_and_group (psd, buf);
4957 xfree (psd);
4959 else
4960 get_file_owner_and_group (NULL, buf);
4962 CloseHandle (fh);
4964 else
4966 no_true_file_attributes:
4967 /* Plan B: Either getting a handle on the file failed, or the
4968 caller explicitly asked us to not bother making this
4969 information more accurate.
4971 Implementation note: In Plan B, we never bother to resolve
4972 symlinks, even if we got here because we tried Plan A and
4973 failed. That's because, even if the caller asked for extra
4974 precision by setting Vw32_get_true_file_attributes to t,
4975 resolving symlinks requires acquiring a file handle to the
4976 symlink, which we already know will fail. And if the user
4977 did not ask for extra precision, resolving symlinks will fly
4978 in the face of that request, since the user then wants the
4979 lightweight version of the code. */
4980 rootdir = (path >= save_name + len - 1
4981 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4983 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4984 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4985 if (IS_DIRECTORY_SEP (r[0])
4986 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4987 r[1] = r[2] = '\0';
4989 /* Note: If NAME is a symlink to the root of a UNC volume
4990 (i.e. "\\SERVER"), we will not detect that here, and we will
4991 return data about the symlink as result of FindFirst below.
4992 This is unfortunate, but that marginal use case does not
4993 justify a call to chase_symlinks which would impose a penalty
4994 on all the other use cases. (We get here for symlinks to
4995 roots of UNC volumes because CreateFile above fails for them,
4996 unlike with symlinks to root directories X:\ of drives.) */
4997 if (is_unc_volume (name))
4999 fattrs = unc_volume_file_attributes (name);
5000 if (fattrs == -1)
5001 return -1;
5003 ctime = atime = wtime = utc_base_ft;
5005 else if (rootdir)
5007 /* Make sure root directories end in a slash. */
5008 if (!IS_DIRECTORY_SEP (name[len-1]))
5009 strcpy (name + len, "\\");
5010 if (GetDriveType (name) < 2)
5012 errno = ENOENT;
5013 return -1;
5016 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5017 ctime = atime = wtime = utc_base_ft;
5019 else
5021 int have_wfd = -1;
5023 /* Make sure non-root directories do NOT end in a slash,
5024 otherwise FindFirstFile might fail. */
5025 if (IS_DIRECTORY_SEP (name[len-1]))
5026 name[len - 1] = 0;
5028 /* (This is hacky, but helps when doing file completions on
5029 network drives.) Optimize by using information available from
5030 active readdir if possible. */
5031 len = strlen (dir_pathname);
5032 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5033 len--;
5034 if (dir_find_handle != INVALID_HANDLE_VALUE
5035 && last_dir_find_data != -1
5036 && !(is_a_symlink && follow_symlinks)
5037 /* The 2 file-name comparisons below support only ASCII
5038 characters, and will lose (compare not equal) when
5039 the file names include non-ASCII characters that are
5040 the same but for the case. However, doing this
5041 properly involves: (a) converting both file names to
5042 UTF-16, (b) lower-casing both names using CharLowerW,
5043 and (c) comparing the results; this would be quite a
5044 bit slower, whereas Plan B is for users who want
5045 lightweight albeit inaccurate version of 'stat'. */
5046 && c_strncasecmp (save_name, dir_pathname, len) == 0
5047 && IS_DIRECTORY_SEP (name[len])
5048 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5050 have_wfd = last_dir_find_data;
5051 /* This was the last entry returned by readdir. */
5052 if (last_dir_find_data == DIR_FIND_DATA_W)
5053 wfd_w = dir_find_data_w;
5054 else
5055 wfd_a = dir_find_data_a;
5057 else
5059 logon_network_drive (name);
5061 if (w32_unicode_filenames)
5063 filename_to_utf16 (name, name_w);
5064 fh = FindFirstFileW (name_w, &wfd_w);
5065 have_wfd = DIR_FIND_DATA_W;
5067 else
5069 filename_to_ansi (name, name_a);
5070 /* If NAME includes characters not representable by
5071 the current ANSI codepage, filename_to_ansi
5072 usually replaces them with a '?'. We don't want
5073 to let FindFirstFileA interpret those as wildcards,
5074 and "succeed", returning us data from some random
5075 file in the same directory. */
5076 if (_mbspbrk (name_a, "?"))
5077 fh = INVALID_HANDLE_VALUE;
5078 else
5079 fh = FindFirstFileA (name_a, &wfd_a);
5080 have_wfd = DIR_FIND_DATA_A;
5082 if (fh == INVALID_HANDLE_VALUE)
5084 errno = ENOENT;
5085 return -1;
5087 FindClose (fh);
5089 /* Note: if NAME is a symlink, the information we get from
5090 FindFirstFile is for the symlink, not its target. */
5091 if (have_wfd == DIR_FIND_DATA_W)
5093 fattrs = wfd_w.dwFileAttributes;
5094 ctime = wfd_w.ftCreationTime;
5095 atime = wfd_w.ftLastAccessTime;
5096 wtime = wfd_w.ftLastWriteTime;
5097 fs_high = wfd_w.nFileSizeHigh;
5098 fs_low = wfd_w.nFileSizeLow;
5100 else
5102 fattrs = wfd_a.dwFileAttributes;
5103 ctime = wfd_a.ftCreationTime;
5104 atime = wfd_a.ftLastAccessTime;
5105 wtime = wfd_a.ftLastWriteTime;
5106 fs_high = wfd_a.nFileSizeHigh;
5107 fs_low = wfd_a.nFileSizeLow;
5109 fake_inode = 0;
5110 nlinks = 1;
5111 serialnum = volume_info.serialnum;
5113 if (is_a_symlink && !follow_symlinks)
5114 buf->st_mode = S_IFLNK;
5115 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5116 buf->st_mode = S_IFDIR;
5117 else
5118 buf->st_mode = S_IFREG;
5120 get_file_owner_and_group (NULL, buf);
5123 buf->st_ino = fake_inode;
5125 buf->st_dev = serialnum;
5126 buf->st_rdev = serialnum;
5128 buf->st_size = fs_high;
5129 buf->st_size <<= 32;
5130 buf->st_size += fs_low;
5131 buf->st_nlink = nlinks;
5133 /* Convert timestamps to Unix format. */
5134 buf->st_mtime = convert_time (wtime);
5135 buf->st_atime = convert_time (atime);
5136 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5137 buf->st_ctime = convert_time (ctime);
5138 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5140 /* determine rwx permissions */
5141 if (is_a_symlink && !follow_symlinks)
5142 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5143 else
5145 if (fattrs & FILE_ATTRIBUTE_READONLY)
5146 permission = S_IREAD;
5147 else
5148 permission = S_IREAD | S_IWRITE;
5150 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5151 permission |= S_IEXEC;
5152 else if (is_exec (name))
5153 permission |= S_IEXEC;
5156 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5158 return 0;
5162 stat (const char * path, struct stat * buf)
5164 return stat_worker (path, buf, 1);
5168 lstat (const char * path, struct stat * buf)
5170 return stat_worker (path, buf, 0);
5174 fstatat (int fd, char const *name, struct stat *st, int flags)
5176 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5177 This is good enough for the current usage in Emacs, but is fragile.
5179 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5180 Gnulib does this and can serve as a model. */
5181 char fullname[MAX_UTF8_PATH];
5183 if (fd != AT_FDCWD)
5185 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5187 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5188 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5189 < 0)
5191 errno = ENAMETOOLONG;
5192 return -1;
5194 name = fullname;
5197 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5200 /* Provide fstat and utime as well as stat for consistent handling of
5201 file timestamps. */
5203 fstat (int desc, struct stat * buf)
5205 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5206 BY_HANDLE_FILE_INFORMATION info;
5207 unsigned __int64 fake_inode;
5208 int permission;
5210 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5212 case FILE_TYPE_DISK:
5213 buf->st_mode = S_IFREG;
5214 if (!GetFileInformationByHandle (fh, &info))
5216 errno = EACCES;
5217 return -1;
5219 break;
5220 case FILE_TYPE_PIPE:
5221 buf->st_mode = S_IFIFO;
5222 goto non_disk;
5223 case FILE_TYPE_CHAR:
5224 case FILE_TYPE_UNKNOWN:
5225 default:
5226 buf->st_mode = S_IFCHR;
5227 non_disk:
5228 memset (&info, 0, sizeof (info));
5229 info.dwFileAttributes = 0;
5230 info.ftCreationTime = utc_base_ft;
5231 info.ftLastAccessTime = utc_base_ft;
5232 info.ftLastWriteTime = utc_base_ft;
5235 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5236 buf->st_mode = S_IFDIR;
5238 buf->st_nlink = info.nNumberOfLinks;
5239 /* Might as well use file index to fake inode values, but this
5240 is not guaranteed to be unique unless we keep a handle open
5241 all the time (even then there are situations where it is
5242 not unique). Reputedly, there are at most 48 bits of info
5243 (on NTFS, presumably less on FAT). */
5244 fake_inode = info.nFileIndexHigh;
5245 fake_inode <<= 32;
5246 fake_inode += info.nFileIndexLow;
5248 /* MSVC defines _ino_t to be short; other libc's might not. */
5249 if (sizeof (buf->st_ino) == 2)
5250 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5251 else
5252 buf->st_ino = fake_inode;
5254 /* If the caller so requested, get the true file owner and group.
5255 Otherwise, consider the file to belong to the current user. */
5256 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5257 get_file_owner_and_group (NULL, buf);
5258 else
5260 PSECURITY_DESCRIPTOR psd = NULL;
5262 psd = get_file_security_desc_by_handle (fh);
5263 if (psd)
5265 get_file_owner_and_group (psd, buf);
5266 LocalFree (psd);
5268 else
5269 get_file_owner_and_group (NULL, buf);
5272 buf->st_dev = info.dwVolumeSerialNumber;
5273 buf->st_rdev = info.dwVolumeSerialNumber;
5275 buf->st_size = info.nFileSizeHigh;
5276 buf->st_size <<= 32;
5277 buf->st_size += info.nFileSizeLow;
5279 /* Convert timestamps to Unix format. */
5280 buf->st_mtime = convert_time (info.ftLastWriteTime);
5281 buf->st_atime = convert_time (info.ftLastAccessTime);
5282 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5283 buf->st_ctime = convert_time (info.ftCreationTime);
5284 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5286 /* determine rwx permissions */
5287 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5288 permission = S_IREAD;
5289 else
5290 permission = S_IREAD | S_IWRITE;
5292 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5293 permission |= S_IEXEC;
5294 else
5296 #if 0 /* no way of knowing the filename */
5297 char * p = strrchr (name, '.');
5298 if (p != NULL &&
5299 (xstrcasecmp (p, ".exe") == 0 ||
5300 xstrcasecmp (p, ".com") == 0 ||
5301 xstrcasecmp (p, ".bat") == 0 ||
5302 xstrcasecmp (p, ".cmd") == 0))
5303 permission |= S_IEXEC;
5304 #endif
5307 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5309 return 0;
5312 /* A version of 'utime' which handles directories as well as
5313 files. */
5316 utime (const char *name, struct utimbuf *times)
5318 struct utimbuf deftime;
5319 HANDLE fh;
5320 FILETIME mtime;
5321 FILETIME atime;
5323 if (times == NULL)
5325 deftime.modtime = deftime.actime = time (NULL);
5326 times = &deftime;
5329 if (w32_unicode_filenames)
5331 wchar_t name_utf16[MAX_PATH];
5333 if (filename_to_utf16 (name, name_utf16) != 0)
5334 return -1; /* errno set by filename_to_utf16 */
5336 /* Need write access to set times. */
5337 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5338 /* If NAME specifies a directory, FILE_SHARE_DELETE
5339 allows other processes to delete files inside it,
5340 while we have the directory open. */
5341 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5342 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5344 else
5346 char name_ansi[MAX_PATH];
5348 if (filename_to_ansi (name, name_ansi) != 0)
5349 return -1; /* errno set by filename_to_ansi */
5351 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5352 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5353 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5355 if (fh != INVALID_HANDLE_VALUE)
5357 convert_from_time_t (times->actime, &atime);
5358 convert_from_time_t (times->modtime, &mtime);
5359 if (!SetFileTime (fh, NULL, &atime, &mtime))
5361 CloseHandle (fh);
5362 errno = EACCES;
5363 return -1;
5365 CloseHandle (fh);
5367 else
5369 DWORD err = GetLastError ();
5371 switch (err)
5373 case ERROR_FILE_NOT_FOUND:
5374 case ERROR_PATH_NOT_FOUND:
5375 case ERROR_INVALID_DRIVE:
5376 case ERROR_BAD_NETPATH:
5377 case ERROR_DEV_NOT_EXIST:
5378 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5379 file name includes ?s, i.e. translation to ANSI failed. */
5380 case ERROR_INVALID_NAME:
5381 errno = ENOENT;
5382 break;
5383 case ERROR_TOO_MANY_OPEN_FILES:
5384 errno = ENFILE;
5385 break;
5386 case ERROR_ACCESS_DENIED:
5387 case ERROR_SHARING_VIOLATION:
5388 errno = EACCES;
5389 break;
5390 default:
5391 errno = EINVAL;
5392 break;
5394 return -1;
5396 return 0;
5400 sys_umask (int mode)
5402 static int current_mask;
5403 int retval, arg = 0;
5405 /* The only bit we really support is the write bit. Files are
5406 always readable on MS-Windows, and the execute bit does not exist
5407 at all. */
5408 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5409 to prevent access by other users on NTFS. */
5410 if ((mode & S_IWRITE) != 0)
5411 arg |= S_IWRITE;
5413 retval = _umask (arg);
5414 /* Merge into the return value the bits they've set the last time,
5415 which msvcrt.dll ignores and never returns. Emacs insists on its
5416 notion of mask being identical to what we return. */
5417 retval |= (current_mask & ~S_IWRITE);
5418 current_mask = mode;
5420 return retval;
5424 /* Symlink-related functions. */
5425 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5426 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5427 #endif
5430 symlink (char const *filename, char const *linkname)
5432 char linkfn[MAX_UTF8_PATH], *tgtfn;
5433 DWORD flags = 0;
5434 int dir_access, filename_ends_in_slash;
5436 /* Diagnostics follows Posix as much as possible. */
5437 if (filename == NULL || linkname == NULL)
5439 errno = EFAULT;
5440 return -1;
5442 if (!*filename)
5444 errno = ENOENT;
5445 return -1;
5447 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5449 errno = ENAMETOOLONG;
5450 return -1;
5453 strcpy (linkfn, map_w32_filename (linkname, NULL));
5454 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5456 errno = EPERM;
5457 return -1;
5460 /* Note: since empty FILENAME was already rejected, we can safely
5461 refer to FILENAME[1]. */
5462 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5464 /* Non-absolute FILENAME is understood as being relative to
5465 LINKNAME's directory. We need to prepend that directory to
5466 FILENAME to get correct results from faccessat below, since
5467 otherwise it will interpret FILENAME relative to the
5468 directory where the Emacs process runs. Note that
5469 make-symbolic-link always makes sure LINKNAME is a fully
5470 expanded file name. */
5471 char tem[MAX_UTF8_PATH];
5472 char *p = linkfn + strlen (linkfn);
5474 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5475 p--;
5476 if (p > linkfn)
5477 strncpy (tem, linkfn, p - linkfn);
5478 strcpy (tem + (p - linkfn), filename);
5479 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5481 else
5482 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5484 /* Since Windows distinguishes between symlinks to directories and
5485 to files, we provide a kludgy feature: if FILENAME doesn't
5486 exist, but ends in a slash, we create a symlink to directory. If
5487 FILENAME exists and is a directory, we always create a symlink to
5488 directory. */
5489 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5490 if (dir_access == 0 || filename_ends_in_slash)
5491 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5493 tgtfn = (char *)map_w32_filename (filename, NULL);
5494 if (filename_ends_in_slash)
5495 tgtfn[strlen (tgtfn) - 1] = '\0';
5497 errno = 0;
5498 if (!create_symbolic_link (linkfn, tgtfn, flags))
5500 /* ENOSYS is set by create_symbolic_link, when it detects that
5501 the OS doesn't support the CreateSymbolicLink API. */
5502 if (errno != ENOSYS)
5504 DWORD w32err = GetLastError ();
5506 switch (w32err)
5508 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5509 TGTFN point to the same file name, go figure. */
5510 case ERROR_SUCCESS:
5511 case ERROR_FILE_EXISTS:
5512 errno = EEXIST;
5513 break;
5514 case ERROR_ACCESS_DENIED:
5515 errno = EACCES;
5516 break;
5517 case ERROR_FILE_NOT_FOUND:
5518 case ERROR_PATH_NOT_FOUND:
5519 case ERROR_BAD_NETPATH:
5520 case ERROR_INVALID_REPARSE_DATA:
5521 errno = ENOENT;
5522 break;
5523 case ERROR_DIRECTORY:
5524 errno = EISDIR;
5525 break;
5526 case ERROR_PRIVILEGE_NOT_HELD:
5527 case ERROR_NOT_ALL_ASSIGNED:
5528 errno = EPERM;
5529 break;
5530 case ERROR_DISK_FULL:
5531 errno = ENOSPC;
5532 break;
5533 default:
5534 errno = EINVAL;
5535 break;
5538 return -1;
5540 return 0;
5543 /* A quick inexpensive test of whether FILENAME identifies a file that
5544 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5545 must already be in the normalized form returned by
5546 map_w32_filename.
5548 Note: for repeated operations on many files, it is best to test
5549 whether the underlying volume actually supports symlinks, by
5550 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5551 avoid the call to this function if it doesn't. That's because the
5552 call to GetFileAttributes takes a non-negligible time, especially
5553 on non-local or removable filesystems. See stat_worker for an
5554 example of how to do that. */
5555 static int
5556 is_symlink (const char *filename)
5558 DWORD attrs;
5559 wchar_t filename_w[MAX_PATH];
5560 char filename_a[MAX_PATH];
5561 WIN32_FIND_DATAW wfdw;
5562 WIN32_FIND_DATAA wfda;
5563 HANDLE fh;
5564 int attrs_mean_symlink;
5566 if (w32_unicode_filenames)
5568 filename_to_utf16 (filename, filename_w);
5569 attrs = GetFileAttributesW (filename_w);
5571 else
5573 filename_to_ansi (filename, filename_a);
5574 attrs = GetFileAttributesA (filename_a);
5576 if (attrs == -1)
5578 DWORD w32err = GetLastError ();
5580 switch (w32err)
5582 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5583 break;
5584 case ERROR_ACCESS_DENIED:
5585 errno = EACCES;
5586 break;
5587 case ERROR_FILE_NOT_FOUND:
5588 case ERROR_PATH_NOT_FOUND:
5589 default:
5590 errno = ENOENT;
5591 break;
5593 return 0;
5595 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5596 return 0;
5597 logon_network_drive (filename);
5598 if (w32_unicode_filenames)
5600 fh = FindFirstFileW (filename_w, &wfdw);
5601 attrs_mean_symlink =
5602 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5603 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5605 else if (_mbspbrk (filename_a, "?"))
5607 /* filename_to_ansi failed to convert the file name. */
5608 errno = ENOENT;
5609 return 0;
5611 else
5613 fh = FindFirstFileA (filename_a, &wfda);
5614 attrs_mean_symlink =
5615 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5616 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5618 if (fh == INVALID_HANDLE_VALUE)
5619 return 0;
5620 FindClose (fh);
5621 return attrs_mean_symlink;
5624 /* If NAME identifies a symbolic link, copy into BUF the file name of
5625 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5626 null-terminate the target name, even if it fits. Return the number
5627 of bytes copied, or -1 if NAME is not a symlink or any error was
5628 encountered while resolving it. The file name copied into BUF is
5629 encoded in the current ANSI codepage. */
5630 ssize_t
5631 readlink (const char *name, char *buf, size_t buf_size)
5633 const char *path;
5634 TOKEN_PRIVILEGES privs;
5635 int restore_privs = 0;
5636 HANDLE sh;
5637 ssize_t retval;
5638 char resolved[MAX_UTF8_PATH];
5640 if (name == NULL)
5642 errno = EFAULT;
5643 return -1;
5645 if (!*name)
5647 errno = ENOENT;
5648 return -1;
5651 path = map_w32_filename (name, NULL);
5653 if (strlen (path) > MAX_UTF8_PATH)
5655 errno = ENAMETOOLONG;
5656 return -1;
5659 errno = 0;
5660 if (is_windows_9x () == TRUE
5661 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5662 || !is_symlink (path))
5664 if (!errno)
5665 errno = EINVAL; /* not a symlink */
5666 return -1;
5669 /* Done with simple tests, now we're in for some _real_ work. */
5670 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5671 restore_privs = 1;
5672 /* Implementation note: From here and onward, don't return early,
5673 since that will fail to restore the original set of privileges of
5674 the calling thread. */
5676 retval = -1; /* not too optimistic, are we? */
5678 /* Note: In the next call to CreateFile, we use zero as the 2nd
5679 argument because, when the symlink is a hidden/system file,
5680 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5681 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5682 and directory symlinks. */
5683 if (w32_unicode_filenames)
5685 wchar_t path_w[MAX_PATH];
5687 filename_to_utf16 (path, path_w);
5688 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5689 FILE_FLAG_OPEN_REPARSE_POINT
5690 | FILE_FLAG_BACKUP_SEMANTICS,
5691 NULL);
5693 else
5695 char path_a[MAX_PATH];
5697 filename_to_ansi (path, path_a);
5698 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5699 FILE_FLAG_OPEN_REPARSE_POINT
5700 | FILE_FLAG_BACKUP_SEMANTICS,
5701 NULL);
5703 if (sh != INVALID_HANDLE_VALUE)
5705 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5706 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5707 DWORD retbytes;
5709 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5710 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5711 &retbytes, NULL))
5712 errno = EIO;
5713 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5714 errno = EINVAL;
5715 else
5717 /* Copy the link target name, in wide characters, from
5718 reparse_data, then convert it to multibyte encoding in
5719 the current locale's codepage. */
5720 WCHAR *lwname;
5721 size_t lname_size;
5722 USHORT lwname_len =
5723 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5724 WCHAR *lwname_src =
5725 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5726 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5727 size_t size_to_copy = buf_size;
5729 /* According to MSDN, PrintNameLength does not include the
5730 terminating null character. */
5731 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5732 memcpy (lwname, lwname_src, lwname_len);
5733 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5734 filename_from_utf16 (lwname, resolved);
5735 dostounix_filename (resolved);
5736 lname_size = strlen (resolved) + 1;
5737 if (lname_size <= buf_size)
5738 size_to_copy = lname_size;
5739 strncpy (buf, resolved, size_to_copy);
5740 /* Success! */
5741 retval = size_to_copy;
5743 CloseHandle (sh);
5745 else
5747 /* CreateFile failed. */
5748 DWORD w32err2 = GetLastError ();
5750 switch (w32err2)
5752 case ERROR_FILE_NOT_FOUND:
5753 case ERROR_PATH_NOT_FOUND:
5754 errno = ENOENT;
5755 break;
5756 case ERROR_ACCESS_DENIED:
5757 case ERROR_TOO_MANY_OPEN_FILES:
5758 errno = EACCES;
5759 break;
5760 default:
5761 errno = EPERM;
5762 break;
5765 if (restore_privs)
5767 restore_privilege (&privs);
5768 revert_to_self ();
5771 return retval;
5774 ssize_t
5775 readlinkat (int fd, char const *name, char *buffer,
5776 size_t buffer_size)
5778 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5779 as in fstatat. FIXME: Add proper support for readlinkat. */
5780 char fullname[MAX_UTF8_PATH];
5782 if (fd != AT_FDCWD)
5784 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5785 < 0)
5787 errno = ENAMETOOLONG;
5788 return -1;
5790 name = fullname;
5793 return readlink (name, buffer, buffer_size);
5796 /* If FILE is a symlink, return its target (stored in a static
5797 buffer); otherwise return FILE.
5799 This function repeatedly resolves symlinks in the last component of
5800 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5801 until it arrives at a file whose last component is not a symlink,
5802 or some error occurs. It returns the target of the last
5803 successfully resolved symlink in the chain. If it succeeds to
5804 resolve even a single symlink, the value returned is an absolute
5805 file name with backslashes (result of GetFullPathName). By
5806 contrast, if the original FILE is returned, it is unaltered.
5808 Note: This function can set errno even if it succeeds.
5810 Implementation note: we only resolve the last portion ("basename")
5811 of the argument FILE and of each following file in the chain,
5812 disregarding any possible symlinks in its leading directories.
5813 This is because Windows system calls and library functions
5814 transparently resolve symlinks in leading directories and return
5815 correct information, as long as the basename is not a symlink. */
5816 static char *
5817 chase_symlinks (const char *file)
5819 static char target[MAX_UTF8_PATH];
5820 char link[MAX_UTF8_PATH];
5821 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5822 char target_a[MAX_PATH], link_a[MAX_PATH];
5823 ssize_t res, link_len;
5824 int loop_count = 0;
5826 if (is_windows_9x () == TRUE || !is_symlink (file))
5827 return (char *)file;
5829 if (w32_unicode_filenames)
5831 wchar_t file_w[MAX_PATH];
5833 filename_to_utf16 (file, file_w);
5834 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5835 return (char *)file;
5836 filename_from_utf16 (link_w, link);
5838 else
5840 char file_a[MAX_PATH];
5842 filename_to_ansi (file, file_a);
5843 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
5844 return (char *)file;
5845 filename_from_ansi (link_a, link);
5847 link_len = strlen (link);
5849 target[0] = '\0';
5850 do {
5852 /* Remove trailing slashes, as we want to resolve the last
5853 non-trivial part of the link name. */
5854 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5855 link[link_len--] = '\0';
5857 res = readlink (link, target, MAX_UTF8_PATH);
5858 if (res > 0)
5860 target[res] = '\0';
5861 if (!(IS_DEVICE_SEP (target[1])
5862 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5864 /* Target is relative. Append it to the directory part of
5865 the symlink, then copy the result back to target. */
5866 char *p = link + link_len;
5868 while (p > link && !IS_ANY_SEP (p[-1]))
5869 p--;
5870 strcpy (p, target);
5871 strcpy (target, link);
5873 /* Resolve any "." and ".." to get a fully-qualified file name
5874 in link[] again. */
5875 if (w32_unicode_filenames)
5877 filename_to_utf16 (target, target_w);
5878 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
5879 if (link_len > 0)
5880 filename_from_utf16 (link_w, link);
5882 else
5884 filename_to_ansi (target, target_a);
5885 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
5886 if (link_len > 0)
5887 filename_from_ansi (link_a, link);
5889 link_len = strlen (link);
5891 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5893 if (loop_count > 100)
5894 errno = ELOOP;
5896 if (target[0] == '\0') /* not a single call to readlink succeeded */
5897 return (char *)file;
5898 return target;
5902 /* Posix ACL emulation. */
5905 acl_valid (acl_t acl)
5907 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5910 char *
5911 acl_to_text (acl_t acl, ssize_t *size)
5913 LPTSTR str_acl;
5914 SECURITY_INFORMATION flags =
5915 OWNER_SECURITY_INFORMATION |
5916 GROUP_SECURITY_INFORMATION |
5917 DACL_SECURITY_INFORMATION;
5918 char *retval = NULL;
5919 ULONG local_size;
5920 int e = errno;
5922 errno = 0;
5924 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5926 errno = e;
5927 /* We don't want to mix heaps, so we duplicate the string in our
5928 heap and free the one allocated by the API. */
5929 retval = xstrdup (str_acl);
5930 if (size)
5931 *size = local_size;
5932 LocalFree (str_acl);
5934 else if (errno != ENOTSUP)
5935 errno = EINVAL;
5937 return retval;
5940 acl_t
5941 acl_from_text (const char *acl_str)
5943 PSECURITY_DESCRIPTOR psd, retval = NULL;
5944 ULONG sd_size;
5945 int e = errno;
5947 errno = 0;
5949 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5951 errno = e;
5952 retval = xmalloc (sd_size);
5953 memcpy (retval, psd, sd_size);
5954 LocalFree (psd);
5956 else if (errno != ENOTSUP)
5957 errno = EINVAL;
5959 return retval;
5963 acl_free (void *ptr)
5965 xfree (ptr);
5966 return 0;
5969 acl_t
5970 acl_get_file (const char *fname, acl_type_t type)
5972 PSECURITY_DESCRIPTOR psd = NULL;
5973 const char *filename;
5975 if (type == ACL_TYPE_ACCESS)
5977 DWORD sd_len, err;
5978 SECURITY_INFORMATION si =
5979 OWNER_SECURITY_INFORMATION |
5980 GROUP_SECURITY_INFORMATION |
5981 DACL_SECURITY_INFORMATION ;
5982 int e = errno;
5984 filename = map_w32_filename (fname, NULL);
5985 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5986 fname = chase_symlinks (filename);
5987 else
5988 fname = filename;
5990 errno = 0;
5991 if (!get_file_security (fname, si, psd, 0, &sd_len)
5992 && errno != ENOTSUP)
5994 err = GetLastError ();
5995 if (err == ERROR_INSUFFICIENT_BUFFER)
5997 psd = xmalloc (sd_len);
5998 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6000 xfree (psd);
6001 errno = EIO;
6002 psd = NULL;
6005 else if (err == ERROR_FILE_NOT_FOUND
6006 || err == ERROR_PATH_NOT_FOUND
6007 /* ERROR_INVALID_NAME is what we get if
6008 w32-unicode-filenames is nil and the file cannot
6009 be encoded in the current ANSI codepage. */
6010 || err == ERROR_INVALID_NAME)
6011 errno = ENOENT;
6012 else
6013 errno = EIO;
6015 else if (!errno)
6016 errno = e;
6018 else if (type != ACL_TYPE_DEFAULT)
6019 errno = EINVAL;
6021 return psd;
6025 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6027 TOKEN_PRIVILEGES old1, old2;
6028 DWORD err;
6029 int st = 0, retval = -1;
6030 SECURITY_INFORMATION flags = 0;
6031 PSID psidOwner, psidGroup;
6032 PACL pacl;
6033 BOOL dflt;
6034 BOOL dacl_present;
6035 int e;
6036 const char *filename;
6038 if (acl_valid (acl) != 0
6039 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6041 errno = EINVAL;
6042 return -1;
6045 if (type == ACL_TYPE_DEFAULT)
6047 errno = ENOSYS;
6048 return -1;
6051 filename = map_w32_filename (fname, NULL);
6052 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6053 fname = chase_symlinks (filename);
6054 else
6055 fname = filename;
6057 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6058 &dflt)
6059 && psidOwner)
6060 flags |= OWNER_SECURITY_INFORMATION;
6061 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6062 &dflt)
6063 && psidGroup)
6064 flags |= GROUP_SECURITY_INFORMATION;
6065 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6066 &pacl, &dflt)
6067 && dacl_present)
6068 flags |= DACL_SECURITY_INFORMATION;
6069 if (!flags)
6070 return 0;
6072 /* According to KB-245153, setting the owner will succeed if either:
6073 (1) the caller is the user who will be the new owner, and has the
6074 SE_TAKE_OWNERSHIP privilege, or
6075 (2) the caller has the SE_RESTORE privilege, in which case she can
6076 set any valid user or group as the owner
6078 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6079 privileges, and disregard any failures in obtaining them. If
6080 these privileges cannot be obtained, and do not already exist in
6081 the calling thread's security token, this function could fail
6082 with EPERM. */
6083 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6084 st++;
6085 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6086 st++;
6088 e = errno;
6089 errno = 0;
6090 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6091 DACL inheritance is involved, but it seems to preserve ownership
6092 better than SetNamedSecurityInfo, which is important e.g., in
6093 copy-file. */
6094 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6096 err = GetLastError ();
6098 if (errno != ENOTSUP)
6099 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6100 psidOwner, psidGroup, pacl, NULL);
6102 else
6103 err = ERROR_SUCCESS;
6104 if (err != ERROR_SUCCESS)
6106 if (errno == ENOTSUP)
6108 else if (err == ERROR_INVALID_OWNER
6109 || err == ERROR_NOT_ALL_ASSIGNED
6110 || err == ERROR_ACCESS_DENIED)
6112 /* Maybe the requested ACL and the one the file already has
6113 are identical, in which case we can silently ignore the
6114 failure. (And no, Windows doesn't.) */
6115 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6117 errno = EPERM;
6118 if (current_acl)
6120 char *acl_from = acl_to_text (current_acl, NULL);
6121 char *acl_to = acl_to_text (acl, NULL);
6123 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6125 retval = 0;
6126 errno = e;
6128 if (acl_from)
6129 acl_free (acl_from);
6130 if (acl_to)
6131 acl_free (acl_to);
6132 acl_free (current_acl);
6135 else if (err == ERROR_FILE_NOT_FOUND
6136 || err == ERROR_PATH_NOT_FOUND
6137 /* ERROR_INVALID_NAME is what we get if
6138 w32-unicode-filenames is nil and the file cannot be
6139 encoded in the current ANSI codepage. */
6140 || err == ERROR_INVALID_NAME)
6141 errno = ENOENT;
6142 else
6143 errno = EACCES;
6145 else
6147 retval = 0;
6148 errno = e;
6151 if (st)
6153 if (st >= 2)
6154 restore_privilege (&old2);
6155 restore_privilege (&old1);
6156 revert_to_self ();
6159 return retval;
6163 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6164 have a fixed max size for file names, so we don't need the kind of
6165 alloc/malloc/realloc dance the gnulib version does. We also don't
6166 support FD-relative symlinks. */
6167 char *
6168 careadlinkat (int fd, char const *filename,
6169 char *buffer, size_t buffer_size,
6170 struct allocator const *alloc,
6171 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6173 char linkname[MAX_UTF8_PATH];
6174 ssize_t link_size;
6176 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6178 if (link_size > 0)
6180 char *retval = buffer;
6182 linkname[link_size++] = '\0';
6183 if (link_size > buffer_size)
6184 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6185 if (retval)
6186 memcpy (retval, linkname, link_size);
6188 return retval;
6190 return NULL;
6194 w32_copy_file (const char *from, const char *to,
6195 int keep_time, int preserve_ownership, int copy_acls)
6197 acl_t acl = NULL;
6198 BOOL copy_result;
6199 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6200 char from_a[MAX_PATH], to_a[MAX_PATH];
6202 /* We ignore preserve_ownership for now. */
6203 preserve_ownership = preserve_ownership;
6205 if (copy_acls)
6207 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6208 if (acl == NULL && acl_errno_valid (errno))
6209 return -2;
6211 if (w32_unicode_filenames)
6213 filename_to_utf16 (from, from_w);
6214 filename_to_utf16 (to, to_w);
6215 copy_result = CopyFileW (from_w, to_w, FALSE);
6217 else
6219 filename_to_ansi (from, from_a);
6220 filename_to_ansi (to, to_a);
6221 copy_result = CopyFileA (from_a, to_a, FALSE);
6223 if (!copy_result)
6225 /* CopyFile doesn't set errno when it fails. By far the most
6226 "popular" reason is that the target is read-only. */
6227 DWORD err = GetLastError ();
6229 switch (err)
6231 case ERROR_FILE_NOT_FOUND:
6232 errno = ENOENT;
6233 break;
6234 case ERROR_ACCESS_DENIED:
6235 errno = EACCES;
6236 break;
6237 case ERROR_ENCRYPTION_FAILED:
6238 errno = EIO;
6239 break;
6240 default:
6241 errno = EPERM;
6242 break;
6245 if (acl)
6246 acl_free (acl);
6247 return -1;
6249 /* CopyFile retains the timestamp by default. However, see
6250 "Community Additions" for CopyFile: it sounds like that is not
6251 entirely true. Testing on Windows XP confirms that modified time
6252 is copied, but creation and last-access times are not.
6253 FIXME? */
6254 else if (!keep_time)
6256 struct timespec now;
6257 DWORD attributes;
6259 if (w32_unicode_filenames)
6261 /* Ensure file is writable while its times are set. */
6262 attributes = GetFileAttributesW (to_w);
6263 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6264 now = current_timespec ();
6265 if (set_file_times (-1, to, now, now))
6267 /* Restore original attributes. */
6268 SetFileAttributesW (to_w, attributes);
6269 if (acl)
6270 acl_free (acl);
6271 return -3;
6273 /* Restore original attributes. */
6274 SetFileAttributesW (to_w, attributes);
6276 else
6278 attributes = GetFileAttributesA (to_a);
6279 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6280 now = current_timespec ();
6281 if (set_file_times (-1, to, now, now))
6283 SetFileAttributesA (to_a, attributes);
6284 if (acl)
6285 acl_free (acl);
6286 return -3;
6288 SetFileAttributesA (to_a, attributes);
6291 if (acl != NULL)
6293 bool fail =
6294 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6295 acl_free (acl);
6296 if (fail && acl_errno_valid (errno))
6297 return -4;
6300 return 0;
6304 /* Support for browsing other processes and their attributes. See
6305 process.c for the Lisp bindings. */
6307 /* Helper wrapper functions. */
6309 static HANDLE WINAPI
6310 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6312 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6314 if (g_b_init_create_toolhelp32_snapshot == 0)
6316 g_b_init_create_toolhelp32_snapshot = 1;
6317 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6318 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6319 "CreateToolhelp32Snapshot");
6321 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6323 return INVALID_HANDLE_VALUE;
6325 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6328 static BOOL WINAPI
6329 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6331 static Process32First_Proc s_pfn_Process32_First = NULL;
6333 if (g_b_init_process32_first == 0)
6335 g_b_init_process32_first = 1;
6336 s_pfn_Process32_First = (Process32First_Proc)
6337 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6338 "Process32First");
6340 if (s_pfn_Process32_First == NULL)
6342 return FALSE;
6344 return (s_pfn_Process32_First (hSnapshot, lppe));
6347 static BOOL WINAPI
6348 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6350 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6352 if (g_b_init_process32_next == 0)
6354 g_b_init_process32_next = 1;
6355 s_pfn_Process32_Next = (Process32Next_Proc)
6356 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6357 "Process32Next");
6359 if (s_pfn_Process32_Next == NULL)
6361 return FALSE;
6363 return (s_pfn_Process32_Next (hSnapshot, lppe));
6366 static BOOL WINAPI
6367 open_thread_token (HANDLE ThreadHandle,
6368 DWORD DesiredAccess,
6369 BOOL OpenAsSelf,
6370 PHANDLE TokenHandle)
6372 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6373 HMODULE hm_advapi32 = NULL;
6374 if (is_windows_9x () == TRUE)
6376 SetLastError (ERROR_NOT_SUPPORTED);
6377 return FALSE;
6379 if (g_b_init_open_thread_token == 0)
6381 g_b_init_open_thread_token = 1;
6382 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6383 s_pfn_Open_Thread_Token =
6384 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6386 if (s_pfn_Open_Thread_Token == NULL)
6388 SetLastError (ERROR_NOT_SUPPORTED);
6389 return FALSE;
6391 return (
6392 s_pfn_Open_Thread_Token (
6393 ThreadHandle,
6394 DesiredAccess,
6395 OpenAsSelf,
6396 TokenHandle)
6400 static BOOL WINAPI
6401 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6403 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6404 HMODULE hm_advapi32 = NULL;
6405 if (is_windows_9x () == TRUE)
6407 return FALSE;
6409 if (g_b_init_impersonate_self == 0)
6411 g_b_init_impersonate_self = 1;
6412 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6413 s_pfn_Impersonate_Self =
6414 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6416 if (s_pfn_Impersonate_Self == NULL)
6418 return FALSE;
6420 return s_pfn_Impersonate_Self (ImpersonationLevel);
6423 static BOOL WINAPI
6424 revert_to_self (void)
6426 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6427 HMODULE hm_advapi32 = NULL;
6428 if (is_windows_9x () == TRUE)
6430 return FALSE;
6432 if (g_b_init_revert_to_self == 0)
6434 g_b_init_revert_to_self = 1;
6435 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6436 s_pfn_Revert_To_Self =
6437 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6439 if (s_pfn_Revert_To_Self == NULL)
6441 return FALSE;
6443 return s_pfn_Revert_To_Self ();
6446 static BOOL WINAPI
6447 get_process_memory_info (HANDLE h_proc,
6448 PPROCESS_MEMORY_COUNTERS mem_counters,
6449 DWORD bufsize)
6451 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6452 HMODULE hm_psapi = NULL;
6453 if (is_windows_9x () == TRUE)
6455 return FALSE;
6457 if (g_b_init_get_process_memory_info == 0)
6459 g_b_init_get_process_memory_info = 1;
6460 hm_psapi = LoadLibrary ("Psapi.dll");
6461 if (hm_psapi)
6462 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6463 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6465 if (s_pfn_Get_Process_Memory_Info == NULL)
6467 return FALSE;
6469 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6472 static BOOL WINAPI
6473 get_process_working_set_size (HANDLE h_proc,
6474 PSIZE_T minrss,
6475 PSIZE_T maxrss)
6477 static GetProcessWorkingSetSize_Proc
6478 s_pfn_Get_Process_Working_Set_Size = NULL;
6480 if (is_windows_9x () == TRUE)
6482 return FALSE;
6484 if (g_b_init_get_process_working_set_size == 0)
6486 g_b_init_get_process_working_set_size = 1;
6487 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6488 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6489 "GetProcessWorkingSetSize");
6491 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6493 return FALSE;
6495 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6498 static BOOL WINAPI
6499 global_memory_status (MEMORYSTATUS *buf)
6501 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6503 if (is_windows_9x () == TRUE)
6505 return FALSE;
6507 if (g_b_init_global_memory_status == 0)
6509 g_b_init_global_memory_status = 1;
6510 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6511 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6512 "GlobalMemoryStatus");
6514 if (s_pfn_Global_Memory_Status == NULL)
6516 return FALSE;
6518 return s_pfn_Global_Memory_Status (buf);
6521 static BOOL WINAPI
6522 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6524 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6526 if (is_windows_9x () == TRUE)
6528 return FALSE;
6530 if (g_b_init_global_memory_status_ex == 0)
6532 g_b_init_global_memory_status_ex = 1;
6533 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6534 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6535 "GlobalMemoryStatusEx");
6537 if (s_pfn_Global_Memory_Status_Ex == NULL)
6539 return FALSE;
6541 return s_pfn_Global_Memory_Status_Ex (buf);
6544 Lisp_Object
6545 list_system_processes (void)
6547 struct gcpro gcpro1;
6548 Lisp_Object proclist = Qnil;
6549 HANDLE h_snapshot;
6551 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6553 if (h_snapshot != INVALID_HANDLE_VALUE)
6555 PROCESSENTRY32 proc_entry;
6556 DWORD proc_id;
6557 BOOL res;
6559 GCPRO1 (proclist);
6561 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6562 for (res = process32_first (h_snapshot, &proc_entry); res;
6563 res = process32_next (h_snapshot, &proc_entry))
6565 proc_id = proc_entry.th32ProcessID;
6566 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6569 CloseHandle (h_snapshot);
6570 UNGCPRO;
6571 proclist = Fnreverse (proclist);
6574 return proclist;
6577 static int
6578 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6580 TOKEN_PRIVILEGES priv;
6581 DWORD priv_size = sizeof (priv);
6582 DWORD opriv_size = sizeof (*old_priv);
6583 HANDLE h_token = NULL;
6584 HANDLE h_thread = GetCurrentThread ();
6585 int ret_val = 0;
6586 BOOL res;
6588 res = open_thread_token (h_thread,
6589 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6590 FALSE, &h_token);
6591 if (!res && GetLastError () == ERROR_NO_TOKEN)
6593 if (impersonate_self (SecurityImpersonation))
6594 res = open_thread_token (h_thread,
6595 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6596 FALSE, &h_token);
6598 if (res)
6600 priv.PrivilegeCount = 1;
6601 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6602 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6603 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6604 old_priv, &opriv_size)
6605 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6606 ret_val = 1;
6608 if (h_token)
6609 CloseHandle (h_token);
6611 return ret_val;
6614 static int
6615 restore_privilege (TOKEN_PRIVILEGES *priv)
6617 DWORD priv_size = sizeof (*priv);
6618 HANDLE h_token = NULL;
6619 int ret_val = 0;
6621 if (open_thread_token (GetCurrentThread (),
6622 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6623 FALSE, &h_token))
6625 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6626 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6627 ret_val = 1;
6629 if (h_token)
6630 CloseHandle (h_token);
6632 return ret_val;
6635 static Lisp_Object
6636 ltime (ULONGLONG time_100ns)
6638 ULONGLONG time_sec = time_100ns / 10000000;
6639 int subsec = time_100ns % 10000000;
6640 return list4i (time_sec >> 16, time_sec & 0xffff,
6641 subsec / 10, subsec % 10 * 100000);
6644 #define U64_TO_LISP_TIME(time) ltime (time)
6646 static int
6647 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6648 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6649 double *pcpu)
6651 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6652 ULONGLONG tem1, tem2, tem3, tem;
6654 if (!h_proc
6655 || !get_process_times_fn
6656 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6657 &ft_kernel, &ft_user))
6658 return 0;
6660 GetSystemTimeAsFileTime (&ft_current);
6662 FILETIME_TO_U64 (tem1, ft_kernel);
6663 *stime = U64_TO_LISP_TIME (tem1);
6665 FILETIME_TO_U64 (tem2, ft_user);
6666 *utime = U64_TO_LISP_TIME (tem2);
6668 tem3 = tem1 + tem2;
6669 *ttime = U64_TO_LISP_TIME (tem3);
6671 FILETIME_TO_U64 (tem, ft_creation);
6672 /* Process no 4 (System) returns zero creation time. */
6673 if (tem)
6674 tem -= utc_base;
6675 *ctime = U64_TO_LISP_TIME (tem);
6677 if (tem)
6679 FILETIME_TO_U64 (tem3, ft_current);
6680 tem = (tem3 - utc_base) - tem;
6682 *etime = U64_TO_LISP_TIME (tem);
6684 if (tem)
6686 *pcpu = 100.0 * (tem1 + tem2) / tem;
6687 if (*pcpu > 100)
6688 *pcpu = 100.0;
6690 else
6691 *pcpu = 0;
6693 return 1;
6696 Lisp_Object
6697 system_process_attributes (Lisp_Object pid)
6699 struct gcpro gcpro1, gcpro2, gcpro3;
6700 Lisp_Object attrs = Qnil;
6701 Lisp_Object cmd_str, decoded_cmd, tem;
6702 HANDLE h_snapshot, h_proc;
6703 DWORD proc_id;
6704 int found_proc = 0;
6705 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6706 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6707 DWORD glength = sizeof (gname);
6708 HANDLE token = NULL;
6709 SID_NAME_USE user_type;
6710 unsigned char *buf = NULL;
6711 DWORD blen = 0;
6712 TOKEN_USER user_token;
6713 TOKEN_PRIMARY_GROUP group_token;
6714 unsigned euid;
6715 unsigned egid;
6716 PROCESS_MEMORY_COUNTERS mem;
6717 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6718 SIZE_T minrss, maxrss;
6719 MEMORYSTATUS memst;
6720 MEMORY_STATUS_EX memstex;
6721 double totphys = 0.0;
6722 Lisp_Object ctime, stime, utime, etime, ttime;
6723 double pcpu;
6724 BOOL result = FALSE;
6726 CHECK_NUMBER_OR_FLOAT (pid);
6727 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6729 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6731 GCPRO3 (attrs, decoded_cmd, tem);
6733 if (h_snapshot != INVALID_HANDLE_VALUE)
6735 PROCESSENTRY32 pe;
6736 BOOL res;
6738 pe.dwSize = sizeof (PROCESSENTRY32);
6739 for (res = process32_first (h_snapshot, &pe); res;
6740 res = process32_next (h_snapshot, &pe))
6742 if (proc_id == pe.th32ProcessID)
6744 if (proc_id == 0)
6745 decoded_cmd = build_string ("Idle");
6746 else
6748 /* Decode the command name from locale-specific
6749 encoding. */
6750 cmd_str = build_unibyte_string (pe.szExeFile);
6752 decoded_cmd =
6753 code_convert_string_norecord (cmd_str,
6754 Vlocale_coding_system, 0);
6756 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6757 attrs = Fcons (Fcons (Qppid,
6758 make_fixnum_or_float (pe.th32ParentProcessID)),
6759 attrs);
6760 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6761 attrs);
6762 attrs = Fcons (Fcons (Qthcount,
6763 make_fixnum_or_float (pe.cntThreads)),
6764 attrs);
6765 found_proc = 1;
6766 break;
6770 CloseHandle (h_snapshot);
6773 if (!found_proc)
6775 UNGCPRO;
6776 return Qnil;
6779 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6780 FALSE, proc_id);
6781 /* If we were denied a handle to the process, try again after
6782 enabling the SeDebugPrivilege in our process. */
6783 if (!h_proc)
6785 TOKEN_PRIVILEGES priv_current;
6787 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6789 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6790 FALSE, proc_id);
6791 restore_privilege (&priv_current);
6792 revert_to_self ();
6795 if (h_proc)
6797 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6798 if (result)
6800 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6801 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6803 buf = xmalloc (blen);
6804 result = get_token_information (token, TokenUser,
6805 (LPVOID)buf, blen, &needed);
6806 if (result)
6808 memcpy (&user_token, buf, sizeof (user_token));
6809 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6811 euid = get_rid (user_token.User.Sid);
6812 result = lookup_account_sid (NULL, user_token.User.Sid,
6813 uname, &ulength,
6814 domain, &dlength,
6815 &user_type);
6816 if (result)
6817 w32_add_to_cache (user_token.User.Sid, euid, uname);
6818 else
6820 strcpy (uname, "unknown");
6821 result = TRUE;
6824 ulength = strlen (uname);
6828 if (result)
6830 /* Determine a reasonable euid and gid values. */
6831 if (xstrcasecmp ("administrator", uname) == 0)
6833 euid = 500; /* well-known Administrator uid */
6834 egid = 513; /* well-known None gid */
6836 else
6838 /* Get group id and name. */
6839 result = get_token_information (token, TokenPrimaryGroup,
6840 (LPVOID)buf, blen, &needed);
6841 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6843 buf = xrealloc (buf, blen = needed);
6844 result = get_token_information (token, TokenPrimaryGroup,
6845 (LPVOID)buf, blen, &needed);
6847 if (result)
6849 memcpy (&group_token, buf, sizeof (group_token));
6850 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6852 egid = get_rid (group_token.PrimaryGroup);
6853 dlength = sizeof (domain);
6854 result =
6855 lookup_account_sid (NULL, group_token.PrimaryGroup,
6856 gname, &glength, NULL, &dlength,
6857 &user_type);
6858 if (result)
6859 w32_add_to_cache (group_token.PrimaryGroup,
6860 egid, gname);
6861 else
6863 strcpy (gname, "None");
6864 result = TRUE;
6867 glength = strlen (gname);
6871 xfree (buf);
6873 if (!result)
6875 if (!is_windows_9x ())
6877 /* We couldn't open the process token, presumably because of
6878 insufficient access rights. Assume this process is run
6879 by the system. */
6880 strcpy (uname, "SYSTEM");
6881 strcpy (gname, "None");
6882 euid = 18; /* SYSTEM */
6883 egid = 513; /* None */
6884 glength = strlen (gname);
6885 ulength = strlen (uname);
6887 /* If we are running under Windows 9X, where security calls are
6888 not supported, we assume all processes are run by the current
6889 user. */
6890 else if (GetUserName (uname, &ulength))
6892 if (xstrcasecmp ("administrator", uname) == 0)
6893 euid = 0;
6894 else
6895 euid = 123;
6896 egid = euid;
6897 strcpy (gname, "None");
6898 glength = strlen (gname);
6899 ulength = strlen (uname);
6901 else
6903 euid = 123;
6904 egid = 123;
6905 strcpy (uname, "administrator");
6906 ulength = strlen (uname);
6907 strcpy (gname, "None");
6908 glength = strlen (gname);
6910 if (token)
6911 CloseHandle (token);
6914 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
6915 tem = make_unibyte_string (uname, ulength);
6916 attrs = Fcons (Fcons (Quser,
6917 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6918 attrs);
6919 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
6920 tem = make_unibyte_string (gname, glength);
6921 attrs = Fcons (Fcons (Qgroup,
6922 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6923 attrs);
6925 if (global_memory_status_ex (&memstex))
6926 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6927 totphys = memstex.ullTotalPhys / 1024.0;
6928 #else
6929 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6930 double, so we need to do this for it... */
6932 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6933 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6934 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6936 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6938 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6939 else if (global_memory_status (&memst))
6940 totphys = memst.dwTotalPhys / 1024.0;
6942 if (h_proc
6943 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6944 sizeof (mem_ex)))
6946 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6948 attrs = Fcons (Fcons (Qmajflt,
6949 make_fixnum_or_float (mem_ex.PageFaultCount)),
6950 attrs);
6951 attrs = Fcons (Fcons (Qvsize,
6952 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6953 attrs);
6954 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6955 if (totphys)
6956 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6958 else if (h_proc
6959 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6961 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6963 attrs = Fcons (Fcons (Qmajflt,
6964 make_fixnum_or_float (mem.PageFaultCount)),
6965 attrs);
6966 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6967 if (totphys)
6968 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6970 else if (h_proc
6971 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6973 DWORD rss = maxrss / 1024;
6975 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6976 if (totphys)
6977 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6980 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6982 attrs = Fcons (Fcons (Qutime, utime), attrs);
6983 attrs = Fcons (Fcons (Qstime, stime), attrs);
6984 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6985 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6986 attrs = Fcons (Fcons (Qetime, etime), attrs);
6987 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6990 /* FIXME: Retrieve command line by walking the PEB of the process. */
6992 if (h_proc)
6993 CloseHandle (h_proc);
6994 UNGCPRO;
6995 return attrs;
6999 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7000 unsigned long long *totalswap, unsigned long long *freeswap)
7002 MEMORYSTATUS memst;
7003 MEMORY_STATUS_EX memstex;
7005 /* Use GlobalMemoryStatusEx if available, as it can report more than
7006 2GB of memory. */
7007 if (global_memory_status_ex (&memstex))
7009 *totalram = memstex.ullTotalPhys;
7010 *freeram = memstex.ullAvailPhys;
7011 *totalswap = memstex.ullTotalPageFile;
7012 *freeswap = memstex.ullAvailPageFile;
7013 return 0;
7015 else if (global_memory_status (&memst))
7017 *totalram = memst.dwTotalPhys;
7018 *freeram = memst.dwAvailPhys;
7019 *totalswap = memst.dwTotalPageFile;
7020 *freeswap = memst.dwAvailPageFile;
7021 return 0;
7023 else
7024 return -1;
7028 /* Wrappers for winsock functions to map between our file descriptors
7029 and winsock's handles; also set h_errno for convenience.
7031 To allow Emacs to run on systems which don't have winsock support
7032 installed, we dynamically link to winsock on startup if present, and
7033 otherwise provide the minimum necessary functionality
7034 (eg. gethostname). */
7036 /* function pointers for relevant socket functions */
7037 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7038 void (PASCAL *pfn_WSASetLastError) (int iError);
7039 int (PASCAL *pfn_WSAGetLastError) (void);
7040 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7041 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7042 WSANETWORKEVENTS *NetworkEvents);
7044 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7045 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7046 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7047 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7048 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7049 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7050 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7051 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7052 int (PASCAL *pfn_closesocket) (SOCKET s);
7053 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7054 int (PASCAL *pfn_WSACleanup) (void);
7056 u_short (PASCAL *pfn_htons) (u_short hostshort);
7057 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7058 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7059 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7060 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7061 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7062 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7063 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7064 const char * optval, int optlen);
7065 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7066 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7067 int * namelen);
7068 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7069 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7070 struct sockaddr * from, int * fromlen);
7071 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7072 const struct sockaddr * to, int tolen);
7074 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7075 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7076 #ifndef HANDLE_FLAG_INHERIT
7077 #define HANDLE_FLAG_INHERIT 1
7078 #endif
7080 HANDLE winsock_lib;
7081 static int winsock_inuse;
7083 BOOL
7084 term_winsock (void)
7086 if (winsock_lib != NULL && winsock_inuse == 0)
7088 release_listen_threads ();
7089 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7090 after WSAStartup returns successfully, but it seems reasonable
7091 to allow unloading winsock anyway in that case. */
7092 if (pfn_WSACleanup () == 0 ||
7093 pfn_WSAGetLastError () == WSAENETDOWN)
7095 if (FreeLibrary (winsock_lib))
7096 winsock_lib = NULL;
7097 return TRUE;
7100 return FALSE;
7103 BOOL
7104 init_winsock (int load_now)
7106 WSADATA winsockData;
7108 if (winsock_lib != NULL)
7109 return TRUE;
7111 pfn_SetHandleInformation
7112 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7113 "SetHandleInformation");
7115 winsock_lib = LoadLibrary ("Ws2_32.dll");
7117 if (winsock_lib != NULL)
7119 /* dynamically link to socket functions */
7121 #define LOAD_PROC(fn) \
7122 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7123 goto fail;
7125 LOAD_PROC (WSAStartup);
7126 LOAD_PROC (WSASetLastError);
7127 LOAD_PROC (WSAGetLastError);
7128 LOAD_PROC (WSAEventSelect);
7129 LOAD_PROC (WSAEnumNetworkEvents);
7130 LOAD_PROC (WSACreateEvent);
7131 LOAD_PROC (WSACloseEvent);
7132 LOAD_PROC (socket);
7133 LOAD_PROC (bind);
7134 LOAD_PROC (connect);
7135 LOAD_PROC (ioctlsocket);
7136 LOAD_PROC (recv);
7137 LOAD_PROC (send);
7138 LOAD_PROC (closesocket);
7139 LOAD_PROC (shutdown);
7140 LOAD_PROC (htons);
7141 LOAD_PROC (ntohs);
7142 LOAD_PROC (inet_addr);
7143 LOAD_PROC (gethostname);
7144 LOAD_PROC (gethostbyname);
7145 LOAD_PROC (getservbyname);
7146 LOAD_PROC (getpeername);
7147 LOAD_PROC (WSACleanup);
7148 LOAD_PROC (setsockopt);
7149 LOAD_PROC (listen);
7150 LOAD_PROC (getsockname);
7151 LOAD_PROC (accept);
7152 LOAD_PROC (recvfrom);
7153 LOAD_PROC (sendto);
7154 #undef LOAD_PROC
7156 /* specify version 1.1 of winsock */
7157 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7159 if (winsockData.wVersion != 0x101)
7160 goto fail;
7162 if (!load_now)
7164 /* Report that winsock exists and is usable, but leave
7165 socket functions disabled. I am assuming that calling
7166 WSAStartup does not require any network interaction,
7167 and in particular does not cause or require a dial-up
7168 connection to be established. */
7170 pfn_WSACleanup ();
7171 FreeLibrary (winsock_lib);
7172 winsock_lib = NULL;
7174 winsock_inuse = 0;
7175 return TRUE;
7178 fail:
7179 FreeLibrary (winsock_lib);
7180 winsock_lib = NULL;
7183 return FALSE;
7187 int h_errno = 0;
7189 /* Function to map winsock error codes to errno codes for those errno
7190 code defined in errno.h (errno values not defined by errno.h are
7191 already in nt/inc/sys/socket.h). */
7192 static void
7193 set_errno (void)
7195 int wsa_err;
7197 h_errno = 0;
7198 if (winsock_lib == NULL)
7199 wsa_err = EINVAL;
7200 else
7201 wsa_err = pfn_WSAGetLastError ();
7203 switch (wsa_err)
7205 case WSAEACCES: errno = EACCES; break;
7206 case WSAEBADF: errno = EBADF; break;
7207 case WSAEFAULT: errno = EFAULT; break;
7208 case WSAEINTR: errno = EINTR; break;
7209 case WSAEINVAL: errno = EINVAL; break;
7210 case WSAEMFILE: errno = EMFILE; break;
7211 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7212 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7213 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7214 case WSAENOTCONN: errno = ENOTCONN; break;
7215 default: errno = wsa_err; break;
7219 static void
7220 check_errno (void)
7222 h_errno = 0;
7223 if (winsock_lib != NULL)
7224 pfn_WSASetLastError (0);
7227 /* Extend strerror to handle the winsock-specific error codes. */
7228 struct {
7229 int errnum;
7230 char * msg;
7231 } _wsa_errlist[] = {
7232 {WSAEINTR , "Interrupted function call"},
7233 {WSAEBADF , "Bad file descriptor"},
7234 {WSAEACCES , "Permission denied"},
7235 {WSAEFAULT , "Bad address"},
7236 {WSAEINVAL , "Invalid argument"},
7237 {WSAEMFILE , "Too many open files"},
7239 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7240 {WSAEINPROGRESS , "Operation now in progress"},
7241 {WSAEALREADY , "Operation already in progress"},
7242 {WSAENOTSOCK , "Socket operation on non-socket"},
7243 {WSAEDESTADDRREQ , "Destination address required"},
7244 {WSAEMSGSIZE , "Message too long"},
7245 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7246 {WSAENOPROTOOPT , "Bad protocol option"},
7247 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7248 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7249 {WSAEOPNOTSUPP , "Operation not supported"},
7250 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7251 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7252 {WSAEADDRINUSE , "Address already in use"},
7253 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7254 {WSAENETDOWN , "Network is down"},
7255 {WSAENETUNREACH , "Network is unreachable"},
7256 {WSAENETRESET , "Network dropped connection on reset"},
7257 {WSAECONNABORTED , "Software caused connection abort"},
7258 {WSAECONNRESET , "Connection reset by peer"},
7259 {WSAENOBUFS , "No buffer space available"},
7260 {WSAEISCONN , "Socket is already connected"},
7261 {WSAENOTCONN , "Socket is not connected"},
7262 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7263 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7264 {WSAETIMEDOUT , "Connection timed out"},
7265 {WSAECONNREFUSED , "Connection refused"},
7266 {WSAELOOP , "Network loop"}, /* not sure */
7267 {WSAENAMETOOLONG , "Name is too long"},
7268 {WSAEHOSTDOWN , "Host is down"},
7269 {WSAEHOSTUNREACH , "No route to host"},
7270 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7271 {WSAEPROCLIM , "Too many processes"},
7272 {WSAEUSERS , "Too many users"}, /* not sure */
7273 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7274 {WSAESTALE , "Data is stale"}, /* not sure */
7275 {WSAEREMOTE , "Remote error"}, /* not sure */
7277 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7278 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7279 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7280 {WSAEDISCON , "Graceful shutdown in progress"},
7281 #ifdef WSAENOMORE
7282 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7283 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7284 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7285 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7286 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7287 {WSASYSCALLFAILURE , "System call failure"},
7288 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7289 {WSATYPE_NOT_FOUND , "Class type not found"},
7290 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7291 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7292 {WSAEREFUSED , "Operation refused"}, /* not sure */
7293 #endif
7295 {WSAHOST_NOT_FOUND , "Host not found"},
7296 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7297 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7298 {WSANO_DATA , "Valid name, no data record of requested type"},
7300 {-1, NULL}
7303 char *
7304 sys_strerror (int error_no)
7306 int i;
7307 static char unknown_msg[40];
7309 if (error_no >= 0 && error_no < sys_nerr)
7310 return sys_errlist[error_no];
7312 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7313 if (_wsa_errlist[i].errnum == error_no)
7314 return _wsa_errlist[i].msg;
7316 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7317 return unknown_msg;
7320 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7321 but I believe the method of keeping the socket handle separate (and
7322 insuring it is not inheritable) is the correct one. */
7324 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7326 static int socket_to_fd (SOCKET s);
7329 sys_socket (int af, int type, int protocol)
7331 SOCKET s;
7333 if (winsock_lib == NULL)
7335 errno = ENETDOWN;
7336 return INVALID_SOCKET;
7339 check_errno ();
7341 /* call the real socket function */
7342 s = pfn_socket (af, type, protocol);
7344 if (s != INVALID_SOCKET)
7345 return socket_to_fd (s);
7347 set_errno ();
7348 return -1;
7351 /* Convert a SOCKET to a file descriptor. */
7352 static int
7353 socket_to_fd (SOCKET s)
7355 int fd;
7356 child_process * cp;
7358 /* Although under NT 3.5 _open_osfhandle will accept a socket
7359 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7360 that does not work under NT 3.1. However, we can get the same
7361 effect by using a backdoor function to replace an existing
7362 descriptor handle with the one we want. */
7364 /* allocate a file descriptor (with appropriate flags) */
7365 fd = _open ("NUL:", _O_RDWR);
7366 if (fd >= 0)
7368 /* Make a non-inheritable copy of the socket handle. Note
7369 that it is possible that sockets aren't actually kernel
7370 handles, which appears to be the case on Windows 9x when
7371 the MS Proxy winsock client is installed. */
7373 /* Apparently there is a bug in NT 3.51 with some service
7374 packs, which prevents using DuplicateHandle to make a
7375 socket handle non-inheritable (causes WSACleanup to
7376 hang). The work-around is to use SetHandleInformation
7377 instead if it is available and implemented. */
7378 if (pfn_SetHandleInformation)
7380 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7382 else
7384 HANDLE parent = GetCurrentProcess ();
7385 HANDLE new_s = INVALID_HANDLE_VALUE;
7387 if (DuplicateHandle (parent,
7388 (HANDLE) s,
7389 parent,
7390 &new_s,
7392 FALSE,
7393 DUPLICATE_SAME_ACCESS))
7395 /* It is possible that DuplicateHandle succeeds even
7396 though the socket wasn't really a kernel handle,
7397 because a real handle has the same value. So
7398 test whether the new handle really is a socket. */
7399 long nonblocking = 0;
7400 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7402 pfn_closesocket (s);
7403 s = (SOCKET) new_s;
7405 else
7407 CloseHandle (new_s);
7412 eassert (fd < MAXDESC);
7413 fd_info[fd].hnd = (HANDLE) s;
7415 /* set our own internal flags */
7416 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7418 cp = new_child ();
7419 if (cp)
7421 cp->fd = fd;
7422 cp->status = STATUS_READ_ACKNOWLEDGED;
7424 /* attach child_process to fd_info */
7425 if (fd_info[ fd ].cp != NULL)
7427 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7428 emacs_abort ();
7431 fd_info[ fd ].cp = cp;
7433 /* success! */
7434 winsock_inuse++; /* count open sockets */
7435 return fd;
7438 /* clean up */
7439 _close (fd);
7441 else
7442 pfn_closesocket (s);
7443 errno = EMFILE;
7444 return -1;
7448 sys_bind (int s, const struct sockaddr * addr, int namelen)
7450 if (winsock_lib == NULL)
7452 errno = ENOTSOCK;
7453 return SOCKET_ERROR;
7456 check_errno ();
7457 if (fd_info[s].flags & FILE_SOCKET)
7459 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7460 if (rc == SOCKET_ERROR)
7461 set_errno ();
7462 return rc;
7464 errno = ENOTSOCK;
7465 return SOCKET_ERROR;
7469 sys_connect (int s, const struct sockaddr * name, int namelen)
7471 if (winsock_lib == NULL)
7473 errno = ENOTSOCK;
7474 return SOCKET_ERROR;
7477 check_errno ();
7478 if (fd_info[s].flags & FILE_SOCKET)
7480 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7481 if (rc == SOCKET_ERROR)
7483 set_errno ();
7484 /* If this is a non-blocking 'connect', set the bit in flags
7485 that will tell reader_thread to wait for connection
7486 before trying to read. */
7487 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7489 errno = EINPROGRESS; /* that's what process.c expects */
7490 fd_info[s].flags |= FILE_CONNECT;
7492 return rc;
7495 errno = ENOTSOCK;
7496 return SOCKET_ERROR;
7499 u_short
7500 sys_htons (u_short hostshort)
7502 return (winsock_lib != NULL) ?
7503 pfn_htons (hostshort) : hostshort;
7506 u_short
7507 sys_ntohs (u_short netshort)
7509 return (winsock_lib != NULL) ?
7510 pfn_ntohs (netshort) : netshort;
7513 unsigned long
7514 sys_inet_addr (const char * cp)
7516 return (winsock_lib != NULL) ?
7517 pfn_inet_addr (cp) : INADDR_NONE;
7521 sys_gethostname (char * name, int namelen)
7523 if (winsock_lib != NULL)
7525 int retval;
7527 check_errno ();
7528 retval = pfn_gethostname (name, namelen);
7529 if (retval == SOCKET_ERROR)
7530 set_errno ();
7531 return retval;
7534 if (namelen > MAX_COMPUTERNAME_LENGTH)
7535 return !GetComputerName (name, (DWORD *)&namelen);
7537 errno = EFAULT;
7538 return SOCKET_ERROR;
7541 struct hostent *
7542 sys_gethostbyname (const char * name)
7544 struct hostent * host;
7545 int h_err = h_errno;
7547 if (winsock_lib == NULL)
7549 h_errno = NO_RECOVERY;
7550 errno = ENETDOWN;
7551 return NULL;
7554 check_errno ();
7555 host = pfn_gethostbyname (name);
7556 if (!host)
7558 set_errno ();
7559 h_errno = errno;
7561 else
7562 h_errno = h_err;
7563 return host;
7566 struct servent *
7567 sys_getservbyname (const char * name, const char * proto)
7569 struct servent * serv;
7571 if (winsock_lib == NULL)
7573 errno = ENETDOWN;
7574 return NULL;
7577 check_errno ();
7578 serv = pfn_getservbyname (name, proto);
7579 if (!serv)
7580 set_errno ();
7581 return serv;
7585 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7587 if (winsock_lib == NULL)
7589 errno = ENETDOWN;
7590 return SOCKET_ERROR;
7593 check_errno ();
7594 if (fd_info[s].flags & FILE_SOCKET)
7596 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7597 if (rc == SOCKET_ERROR)
7598 set_errno ();
7599 return rc;
7601 errno = ENOTSOCK;
7602 return SOCKET_ERROR;
7606 sys_shutdown (int s, int how)
7608 if (winsock_lib == NULL)
7610 errno = ENETDOWN;
7611 return SOCKET_ERROR;
7614 check_errno ();
7615 if (fd_info[s].flags & FILE_SOCKET)
7617 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7618 if (rc == SOCKET_ERROR)
7619 set_errno ();
7620 return rc;
7622 errno = ENOTSOCK;
7623 return SOCKET_ERROR;
7627 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7629 if (winsock_lib == NULL)
7631 errno = ENETDOWN;
7632 return SOCKET_ERROR;
7635 check_errno ();
7636 if (fd_info[s].flags & FILE_SOCKET)
7638 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7639 (const char *)optval, optlen);
7640 if (rc == SOCKET_ERROR)
7641 set_errno ();
7642 return rc;
7644 errno = ENOTSOCK;
7645 return SOCKET_ERROR;
7649 sys_listen (int s, int backlog)
7651 if (winsock_lib == NULL)
7653 errno = ENETDOWN;
7654 return SOCKET_ERROR;
7657 check_errno ();
7658 if (fd_info[s].flags & FILE_SOCKET)
7660 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7661 if (rc == SOCKET_ERROR)
7662 set_errno ();
7663 else
7664 fd_info[s].flags |= FILE_LISTEN;
7665 return rc;
7667 errno = ENOTSOCK;
7668 return SOCKET_ERROR;
7672 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7674 if (winsock_lib == NULL)
7676 errno = ENETDOWN;
7677 return SOCKET_ERROR;
7680 check_errno ();
7681 if (fd_info[s].flags & FILE_SOCKET)
7683 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7684 if (rc == SOCKET_ERROR)
7685 set_errno ();
7686 return rc;
7688 errno = ENOTSOCK;
7689 return SOCKET_ERROR;
7693 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7695 if (winsock_lib == NULL)
7697 errno = ENETDOWN;
7698 return -1;
7701 check_errno ();
7702 if (fd_info[s].flags & FILE_LISTEN)
7704 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7705 int fd = -1;
7706 if (t == INVALID_SOCKET)
7707 set_errno ();
7708 else
7709 fd = socket_to_fd (t);
7711 if (fd >= 0)
7713 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7714 ResetEvent (fd_info[s].cp->char_avail);
7716 return fd;
7718 errno = ENOTSOCK;
7719 return -1;
7723 sys_recvfrom (int s, char * buf, int len, int flags,
7724 struct sockaddr * from, int * fromlen)
7726 if (winsock_lib == NULL)
7728 errno = ENETDOWN;
7729 return SOCKET_ERROR;
7732 check_errno ();
7733 if (fd_info[s].flags & FILE_SOCKET)
7735 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7736 if (rc == SOCKET_ERROR)
7737 set_errno ();
7738 return rc;
7740 errno = ENOTSOCK;
7741 return SOCKET_ERROR;
7745 sys_sendto (int s, const char * buf, int len, int flags,
7746 const struct sockaddr * to, int tolen)
7748 if (winsock_lib == NULL)
7750 errno = ENETDOWN;
7751 return SOCKET_ERROR;
7754 check_errno ();
7755 if (fd_info[s].flags & FILE_SOCKET)
7757 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7758 if (rc == SOCKET_ERROR)
7759 set_errno ();
7760 return rc;
7762 errno = ENOTSOCK;
7763 return SOCKET_ERROR;
7766 /* Windows does not have an fcntl function. Provide an implementation
7767 good enough for Emacs. */
7769 fcntl (int s, int cmd, int options)
7771 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7772 invoked in a context where fd1 is closed and all descriptors less
7773 than fd1 are open, so sys_dup is an adequate implementation. */
7774 if (cmd == F_DUPFD_CLOEXEC)
7775 return sys_dup (s);
7777 check_errno ();
7778 if (fd_info[s].flags & FILE_SOCKET)
7780 if (winsock_lib == NULL)
7782 errno = ENETDOWN;
7783 return -1;
7786 if (cmd == F_SETFL && options == O_NONBLOCK)
7788 unsigned long nblock = 1;
7789 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7790 if (rc == SOCKET_ERROR)
7791 set_errno ();
7792 /* Keep track of the fact that we set this to non-blocking. */
7793 fd_info[s].flags |= FILE_NDELAY;
7794 return rc;
7796 else
7798 errno = EINVAL;
7799 return SOCKET_ERROR;
7802 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7803 == (FILE_PIPE | FILE_WRITE))
7805 /* Force our writes to pipes be non-blocking. */
7806 if (cmd == F_SETFL && options == O_NONBLOCK)
7808 HANDLE h = (HANDLE)_get_osfhandle (s);
7809 DWORD pipe_mode = PIPE_NOWAIT;
7811 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7813 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7814 return SOCKET_ERROR;
7816 fd_info[s].flags |= FILE_NDELAY;
7817 return 0;
7819 else
7821 errno = EINVAL;
7822 return SOCKET_ERROR;
7825 errno = ENOTSOCK;
7826 return SOCKET_ERROR;
7830 /* Shadow main io functions: we need to handle pipes and sockets more
7831 intelligently. */
7834 sys_close (int fd)
7836 int rc;
7838 if (fd < 0)
7840 errno = EBADF;
7841 return -1;
7844 if (fd < MAXDESC && fd_info[fd].cp)
7846 child_process * cp = fd_info[fd].cp;
7848 fd_info[fd].cp = NULL;
7850 if (CHILD_ACTIVE (cp))
7852 /* if last descriptor to active child_process then cleanup */
7853 int i;
7854 for (i = 0; i < MAXDESC; i++)
7856 if (i == fd)
7857 continue;
7858 if (fd_info[i].cp == cp)
7859 break;
7861 if (i == MAXDESC)
7863 if (fd_info[fd].flags & FILE_SOCKET)
7865 if (winsock_lib == NULL) emacs_abort ();
7867 pfn_shutdown (SOCK_HANDLE (fd), 2);
7868 rc = pfn_closesocket (SOCK_HANDLE (fd));
7870 winsock_inuse--; /* count open sockets */
7872 /* If the process handle is NULL, it's either a socket
7873 or serial connection, or a subprocess that was
7874 already reaped by reap_subprocess, but whose
7875 resources were not yet freed, because its output was
7876 not fully read yet by the time it was reaped. (This
7877 usually happens with async subprocesses whose output
7878 is being read by Emacs.) Otherwise, this process was
7879 not reaped yet, so we set its FD to a negative value
7880 to make sure sys_select will eventually get to
7881 calling the SIGCHLD handler for it, which will then
7882 invoke waitpid and reap_subprocess. */
7883 if (cp->procinfo.hProcess == NULL)
7884 delete_child (cp);
7885 else
7886 cp->fd = -1;
7891 if (fd >= 0 && fd < MAXDESC)
7892 fd_info[fd].flags = 0;
7894 /* Note that sockets do not need special treatment here (at least on
7895 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7896 closesocket is equivalent to CloseHandle, which is to be expected
7897 because socket handles are fully fledged kernel handles. */
7898 rc = _close (fd);
7900 return rc;
7904 sys_dup (int fd)
7906 int new_fd;
7908 new_fd = _dup (fd);
7909 if (new_fd >= 0 && new_fd < MAXDESC)
7911 /* duplicate our internal info as well */
7912 fd_info[new_fd] = fd_info[fd];
7914 return new_fd;
7918 sys_dup2 (int src, int dst)
7920 int rc;
7922 if (dst < 0 || dst >= MAXDESC)
7924 errno = EBADF;
7925 return -1;
7928 /* make sure we close the destination first if it's a pipe or socket */
7929 if (src != dst && fd_info[dst].flags != 0)
7930 sys_close (dst);
7932 rc = _dup2 (src, dst);
7933 if (rc == 0)
7935 /* duplicate our internal info as well */
7936 fd_info[dst] = fd_info[src];
7938 return rc;
7942 pipe2 (int * phandles, int pipe2_flags)
7944 int rc;
7945 unsigned flags;
7947 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
7949 /* make pipe handles non-inheritable; when we spawn a child, we
7950 replace the relevant handle with an inheritable one. Also put
7951 pipes into binary mode; we will do text mode translation ourselves
7952 if required. */
7953 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
7955 if (rc == 0)
7957 /* Protect against overflow, since Windows can open more handles than
7958 our fd_info array has room for. */
7959 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
7961 _close (phandles[0]);
7962 _close (phandles[1]);
7963 errno = EMFILE;
7964 rc = -1;
7966 else
7968 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
7969 fd_info[phandles[0]].flags = flags;
7971 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
7972 fd_info[phandles[1]].flags = flags;
7976 return rc;
7979 /* Function to do blocking read of one byte, needed to implement
7980 select. It is only allowed on communication ports, sockets, or
7981 pipes. */
7983 _sys_read_ahead (int fd)
7985 child_process * cp;
7986 int rc;
7988 if (fd < 0 || fd >= MAXDESC)
7989 return STATUS_READ_ERROR;
7991 cp = fd_info[fd].cp;
7993 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7994 return STATUS_READ_ERROR;
7996 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
7997 || (fd_info[fd].flags & FILE_READ) == 0)
7999 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8000 emacs_abort ();
8003 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8004 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8005 cp->status = STATUS_READ_IN_PROGRESS;
8007 if (fd_info[fd].flags & FILE_PIPE)
8009 rc = _read (fd, &cp->chr, sizeof (char));
8011 /* Give subprocess time to buffer some more output for us before
8012 reporting that input is available; we need this because Windows 95
8013 connects DOS programs to pipes by making the pipe appear to be
8014 the normal console stdout - as a result most DOS programs will
8015 write to stdout without buffering, ie. one character at a
8016 time. Even some W32 programs do this - "dir" in a command
8017 shell on NT is very slow if we don't do this. */
8018 if (rc > 0)
8020 int wait = w32_pipe_read_delay;
8022 if (wait > 0)
8023 Sleep (wait);
8024 else if (wait < 0)
8025 while (++wait <= 0)
8026 /* Yield remainder of our time slice, effectively giving a
8027 temporary priority boost to the child process. */
8028 Sleep (0);
8031 else if (fd_info[fd].flags & FILE_SERIAL)
8033 HANDLE hnd = fd_info[fd].hnd;
8034 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8035 COMMTIMEOUTS ct;
8037 /* Configure timeouts for blocking read. */
8038 if (!GetCommTimeouts (hnd, &ct))
8040 cp->status = STATUS_READ_ERROR;
8041 return STATUS_READ_ERROR;
8043 ct.ReadIntervalTimeout = 0;
8044 ct.ReadTotalTimeoutMultiplier = 0;
8045 ct.ReadTotalTimeoutConstant = 0;
8046 if (!SetCommTimeouts (hnd, &ct))
8048 cp->status = STATUS_READ_ERROR;
8049 return STATUS_READ_ERROR;
8052 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8054 if (GetLastError () != ERROR_IO_PENDING)
8056 cp->status = STATUS_READ_ERROR;
8057 return STATUS_READ_ERROR;
8059 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8061 cp->status = STATUS_READ_ERROR;
8062 return STATUS_READ_ERROR;
8066 else if (fd_info[fd].flags & FILE_SOCKET)
8068 unsigned long nblock = 0;
8069 /* We always want this to block, so temporarily disable NDELAY. */
8070 if (fd_info[fd].flags & FILE_NDELAY)
8071 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8073 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8075 if (fd_info[fd].flags & FILE_NDELAY)
8077 nblock = 1;
8078 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8082 if (rc == sizeof (char))
8083 cp->status = STATUS_READ_SUCCEEDED;
8084 else
8085 cp->status = STATUS_READ_FAILED;
8087 return cp->status;
8091 _sys_wait_accept (int fd)
8093 HANDLE hEv;
8094 child_process * cp;
8095 int rc;
8097 if (fd < 0 || fd >= MAXDESC)
8098 return STATUS_READ_ERROR;
8100 cp = fd_info[fd].cp;
8102 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8103 return STATUS_READ_ERROR;
8105 cp->status = STATUS_READ_FAILED;
8107 hEv = pfn_WSACreateEvent ();
8108 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8109 if (rc != SOCKET_ERROR)
8111 do {
8112 rc = WaitForSingleObject (hEv, 500);
8113 Sleep (5);
8114 } while (rc == WAIT_TIMEOUT
8115 && cp->status != STATUS_READ_ERROR
8116 && cp->char_avail);
8117 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8118 if (rc == WAIT_OBJECT_0)
8119 cp->status = STATUS_READ_SUCCEEDED;
8121 pfn_WSACloseEvent (hEv);
8123 return cp->status;
8127 _sys_wait_connect (int fd)
8129 HANDLE hEv;
8130 child_process * cp;
8131 int rc;
8133 if (fd < 0 || fd >= MAXDESC)
8134 return STATUS_READ_ERROR;
8136 cp = fd_info[fd].cp;
8137 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8138 return STATUS_READ_ERROR;
8140 cp->status = STATUS_READ_FAILED;
8142 hEv = pfn_WSACreateEvent ();
8143 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8144 if (rc != SOCKET_ERROR)
8146 do {
8147 rc = WaitForSingleObject (hEv, 500);
8148 Sleep (5);
8149 } while (rc == WAIT_TIMEOUT
8150 && cp->status != STATUS_READ_ERROR
8151 && cp->char_avail);
8152 if (rc == WAIT_OBJECT_0)
8154 /* We've got an event, but it could be a successful
8155 connection, or it could be a failure. Find out
8156 which one is it. */
8157 WSANETWORKEVENTS events;
8159 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8160 if ((events.lNetworkEvents & FD_CONNECT) != 0
8161 && events.iErrorCode[FD_CONNECT_BIT])
8163 cp->status = STATUS_CONNECT_FAILED;
8164 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8166 else
8168 cp->status = STATUS_READ_SUCCEEDED;
8169 cp->errcode = 0;
8172 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8174 else
8175 pfn_WSACloseEvent (hEv);
8177 return cp->status;
8181 sys_read (int fd, char * buffer, unsigned int count)
8183 int nchars;
8184 int to_read;
8185 DWORD waiting;
8186 char * orig_buffer = buffer;
8188 if (fd < 0)
8190 errno = EBADF;
8191 return -1;
8194 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8196 child_process *cp = fd_info[fd].cp;
8198 if ((fd_info[fd].flags & FILE_READ) == 0)
8200 errno = EBADF;
8201 return -1;
8204 nchars = 0;
8206 /* re-read CR carried over from last read */
8207 if (fd_info[fd].flags & FILE_LAST_CR)
8209 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8210 *buffer++ = 0x0d;
8211 count--;
8212 nchars++;
8213 fd_info[fd].flags &= ~FILE_LAST_CR;
8216 /* presence of a child_process structure means we are operating in
8217 non-blocking mode - otherwise we just call _read directly.
8218 Note that the child_process structure might be missing because
8219 reap_subprocess has been called; in this case the pipe is
8220 already broken, so calling _read on it is okay. */
8221 if (cp)
8223 int current_status = cp->status;
8225 switch (current_status)
8227 case STATUS_READ_FAILED:
8228 case STATUS_READ_ERROR:
8229 /* report normal EOF if nothing in buffer */
8230 if (nchars <= 0)
8231 fd_info[fd].flags |= FILE_AT_EOF;
8232 return nchars;
8234 case STATUS_READ_READY:
8235 case STATUS_READ_IN_PROGRESS:
8236 DebPrint (("sys_read called when read is in progress\n"));
8237 errno = EWOULDBLOCK;
8238 return -1;
8240 case STATUS_READ_SUCCEEDED:
8241 /* consume read-ahead char */
8242 *buffer++ = cp->chr;
8243 count--;
8244 nchars++;
8245 cp->status = STATUS_READ_ACKNOWLEDGED;
8246 ResetEvent (cp->char_avail);
8248 case STATUS_READ_ACKNOWLEDGED:
8249 case STATUS_CONNECT_FAILED:
8250 break;
8252 default:
8253 DebPrint (("sys_read: bad status %d\n", current_status));
8254 errno = EBADF;
8255 return -1;
8258 if (fd_info[fd].flags & FILE_PIPE)
8260 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8261 to_read = min (waiting, (DWORD) count);
8263 if (to_read > 0)
8264 nchars += _read (fd, buffer, to_read);
8266 else if (fd_info[fd].flags & FILE_SERIAL)
8268 HANDLE hnd = fd_info[fd].hnd;
8269 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8270 int rc = 0;
8271 COMMTIMEOUTS ct;
8273 if (count > 0)
8275 /* Configure timeouts for non-blocking read. */
8276 if (!GetCommTimeouts (hnd, &ct))
8278 errno = EIO;
8279 return -1;
8281 ct.ReadIntervalTimeout = MAXDWORD;
8282 ct.ReadTotalTimeoutMultiplier = 0;
8283 ct.ReadTotalTimeoutConstant = 0;
8284 if (!SetCommTimeouts (hnd, &ct))
8286 errno = EIO;
8287 return -1;
8290 if (!ResetEvent (ovl->hEvent))
8292 errno = EIO;
8293 return -1;
8295 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8297 if (GetLastError () != ERROR_IO_PENDING)
8299 errno = EIO;
8300 return -1;
8302 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8304 errno = EIO;
8305 return -1;
8308 nchars += rc;
8311 else /* FILE_SOCKET */
8313 if (winsock_lib == NULL) emacs_abort ();
8315 /* When a non-blocking 'connect' call fails,
8316 wait_reading_process_output detects this by calling
8317 'getpeername', and then attempts to obtain the connection
8318 error code by trying to read 1 byte from the socket. If
8319 we try to serve that read by calling 'recv' below, the
8320 error we get is a generic WSAENOTCONN, not the actual
8321 connection error. So instead, we use the actual error
8322 code stashed by '_sys_wait_connect' in cp->errcode.
8323 Alternatively, we could have used 'getsockopt', like on
8324 GNU/Linux, but: (a) I have no idea whether the winsock
8325 version could hang, as it does "on some systems" (see the
8326 comment in process.c); and (b) 'getsockopt' on Windows is
8327 documented to clear the socket error for the entire
8328 process, which I'm not sure is TRT; FIXME. */
8329 if (current_status == STATUS_CONNECT_FAILED
8330 && (fd_info[fd].flags & FILE_CONNECT) != 0
8331 && cp->errcode != 0)
8333 pfn_WSASetLastError (cp->errcode);
8334 set_errno ();
8335 return -1;
8337 /* Do the equivalent of a non-blocking read. */
8338 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8339 if (waiting == 0 && nchars == 0)
8341 errno = EWOULDBLOCK;
8342 return -1;
8345 if (waiting)
8347 /* always use binary mode for sockets */
8348 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8349 if (res == SOCKET_ERROR)
8351 set_errno ();
8352 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8353 errno, SOCK_HANDLE (fd)));
8354 return -1;
8356 nchars += res;
8360 else
8362 int nread = _read (fd, buffer, count);
8363 if (nread >= 0)
8364 nchars += nread;
8365 else if (nchars == 0)
8366 nchars = nread;
8369 if (nchars <= 0)
8370 fd_info[fd].flags |= FILE_AT_EOF;
8371 /* Perform text mode translation if required. */
8372 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8374 nchars = crlf_to_lf (nchars, orig_buffer);
8375 /* If buffer contains only CR, return that. To be absolutely
8376 sure we should attempt to read the next char, but in
8377 practice a CR to be followed by LF would not appear by
8378 itself in the buffer. */
8379 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8381 fd_info[fd].flags |= FILE_LAST_CR;
8382 nchars--;
8386 else
8387 nchars = _read (fd, buffer, count);
8389 return nchars;
8392 /* From w32xfns.c */
8393 extern HANDLE interrupt_handle;
8396 sys_write (int fd, const void * buffer, unsigned int count)
8398 int nchars;
8399 USE_SAFE_ALLOCA;
8401 if (fd < 0)
8403 errno = EBADF;
8404 return -1;
8407 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8409 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8411 errno = EBADF;
8412 return -1;
8415 /* Perform text mode translation if required. */
8416 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8418 char * tmpbuf;
8419 const unsigned char * src = buffer;
8420 unsigned char * dst;
8421 int nbytes = count;
8423 SAFE_NALLOCA (tmpbuf, 2, count);
8424 dst = tmpbuf;
8426 while (1)
8428 unsigned char *next;
8429 /* Copy next line or remaining bytes. */
8430 next = _memccpy (dst, src, '\n', nbytes);
8431 if (next)
8433 /* Copied one line ending with '\n'. */
8434 int copied = next - dst;
8435 nbytes -= copied;
8436 src += copied;
8437 /* Insert '\r' before '\n'. */
8438 next[-1] = '\r';
8439 next[0] = '\n';
8440 dst = next + 1;
8441 count++;
8443 else
8444 /* Copied remaining partial line -> now finished. */
8445 break;
8447 buffer = tmpbuf;
8451 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8453 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8454 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8455 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8456 DWORD active = 0;
8458 /* This is async (a.k.a. "overlapped") I/O, so the return value
8459 of FALSE from WriteFile means either an error or the output
8460 will be completed asynchronously (ERROR_IO_PENDING). */
8461 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8463 if (GetLastError () != ERROR_IO_PENDING)
8465 errno = EIO;
8466 nchars = -1;
8468 else
8470 /* Wait for the write to complete, and watch C-g while
8471 at that. */
8472 if (detect_input_pending ())
8473 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8474 INFINITE, QS_ALLINPUT);
8475 else
8476 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8477 switch (active)
8479 case WAIT_OBJECT_0:
8480 /* User pressed C-g, cancel write, then leave.
8481 Don't bother cleaning up as we may only get stuck
8482 in buggy drivers. */
8483 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8484 CancelIo (hnd);
8485 errno = EIO; /* Why not EINTR? */
8486 nchars = -1;
8487 break;
8488 case WAIT_OBJECT_0 + 1:
8489 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8491 errno = EIO;
8492 nchars = -1;
8494 break;
8499 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8501 unsigned long nblock = 0;
8502 if (winsock_lib == NULL) emacs_abort ();
8504 /* TODO: implement select() properly so non-blocking I/O works. */
8505 /* For now, make sure the write blocks. */
8506 if (fd_info[fd].flags & FILE_NDELAY)
8507 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8509 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8511 /* Set the socket back to non-blocking if it was before,
8512 for other operations that support it. */
8513 if (fd_info[fd].flags & FILE_NDELAY)
8515 nblock = 1;
8516 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8519 if (nchars == SOCKET_ERROR)
8521 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8522 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8523 set_errno ();
8526 else
8528 /* Some networked filesystems don't like too large writes, so
8529 break them into smaller chunks. See the Comments section of
8530 the MSDN documentation of WriteFile for details behind the
8531 choice of the value of CHUNK below. See also the thread
8532 http://thread.gmane.org/gmane.comp.version-control.git/145294
8533 in the git mailing list. */
8534 const unsigned char *p = buffer;
8535 const unsigned chunk = 30 * 1024 * 1024;
8537 nchars = 0;
8538 while (count > 0)
8540 unsigned this_chunk = count < chunk ? count : chunk;
8541 int n = _write (fd, p, this_chunk);
8543 nchars += n;
8544 if (n < 0)
8546 /* When there's no buffer space in a pipe that is in the
8547 non-blocking mode, _write returns ENOSPC. We return
8548 EAGAIN instead, which should trigger the logic in
8549 send_process that enters waiting loop and calls
8550 wait_reading_process_output to allow process input to
8551 be accepted during the wait. Those calls to
8552 wait_reading_process_output allow sys_select to
8553 notice when process input becomes available, thus
8554 avoiding deadlock whereby each side of the pipe is
8555 blocked on write, waiting for the other party to read
8556 its end of the pipe. */
8557 if (errno == ENOSPC
8558 && fd < MAXDESC
8559 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8560 == (FILE_PIPE | FILE_NDELAY)))
8561 errno = EAGAIN;
8562 nchars = n;
8563 break;
8565 else if (n < this_chunk)
8566 break;
8567 count -= n;
8568 p += n;
8572 SAFE_FREE ();
8573 return nchars;
8577 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8579 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8581 /* Return information about network interface IFNAME, or about all
8582 interfaces (if IFNAME is nil). */
8583 static Lisp_Object
8584 network_interface_get_info (Lisp_Object ifname)
8586 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8587 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8588 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8589 Lisp_Object res = Qnil;
8591 if (retval == ERROR_BUFFER_OVERFLOW)
8593 ainfo = xrealloc (ainfo, ainfo_len);
8594 retval = get_adapters_info (ainfo, &ainfo_len);
8597 if (retval == ERROR_SUCCESS)
8599 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8600 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8601 int if_num;
8602 struct sockaddr_in sa;
8604 /* For the below, we need some winsock functions, so make sure
8605 the winsock DLL is loaded. If we cannot successfully load
8606 it, they will have no use of the information we provide,
8607 anyway, so punt. */
8608 if (!winsock_lib && !init_winsock (1))
8609 goto done;
8611 for (adapter = ainfo; adapter; adapter = adapter->Next)
8613 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8614 u_long ip_addr;
8615 /* Present Unix-compatible interface names, instead of the
8616 Windows names, which are really GUIDs not readable by
8617 humans. */
8618 static const char *ifmt[] = {
8619 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8620 "lo", "ifx%d"
8622 enum {
8623 NONE = -1,
8624 ETHERNET = 0,
8625 TOKENRING = 1,
8626 FDDI = 2,
8627 PPP = 3,
8628 SLIP = 4,
8629 WLAN = 5,
8630 LOOPBACK = 6,
8631 OTHER_IF = 7
8632 } ifmt_idx;
8634 switch (adapter->Type)
8636 case MIB_IF_TYPE_ETHERNET:
8637 /* Windows before Vista reports wireless adapters as
8638 Ethernet. Work around by looking at the Description
8639 string. */
8640 if (strstr (adapter->Description, "Wireless "))
8642 ifmt_idx = WLAN;
8643 if_num = wlan_count++;
8645 else
8647 ifmt_idx = ETHERNET;
8648 if_num = eth_count++;
8650 break;
8651 case MIB_IF_TYPE_TOKENRING:
8652 ifmt_idx = TOKENRING;
8653 if_num = tr_count++;
8654 break;
8655 case MIB_IF_TYPE_FDDI:
8656 ifmt_idx = FDDI;
8657 if_num = fddi_count++;
8658 break;
8659 case MIB_IF_TYPE_PPP:
8660 ifmt_idx = PPP;
8661 if_num = ppp_count++;
8662 break;
8663 case MIB_IF_TYPE_SLIP:
8664 ifmt_idx = SLIP;
8665 if_num = sl_count++;
8666 break;
8667 case IF_TYPE_IEEE80211:
8668 ifmt_idx = WLAN;
8669 if_num = wlan_count++;
8670 break;
8671 case MIB_IF_TYPE_LOOPBACK:
8672 if (lo_count < 0)
8674 ifmt_idx = LOOPBACK;
8675 if_num = lo_count++;
8677 else
8678 ifmt_idx = NONE;
8679 break;
8680 default:
8681 ifmt_idx = OTHER_IF;
8682 if_num = ifx_count++;
8683 break;
8685 if (ifmt_idx == NONE)
8686 continue;
8687 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8689 sa.sin_family = AF_INET;
8690 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8691 if (ip_addr == INADDR_NONE)
8693 /* Bogus address, skip this interface. */
8694 continue;
8696 sa.sin_addr.s_addr = ip_addr;
8697 sa.sin_port = 0;
8698 if (NILP (ifname))
8699 res = Fcons (Fcons (build_string (namebuf),
8700 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8701 sizeof (struct sockaddr))),
8702 res);
8703 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8705 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8706 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8707 Lisp_Object flags = Qnil;
8708 int n;
8709 u_long net_mask;
8711 /* Flags. We guess most of them by type, since the
8712 Windows flags are different and hard to get by. */
8713 flags = Fcons (intern ("up"), flags);
8714 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8716 flags = Fcons (intern ("broadcast"), flags);
8717 flags = Fcons (intern ("multicast"), flags);
8719 flags = Fcons (intern ("running"), flags);
8720 if (ifmt_idx == PPP)
8722 flags = Fcons (intern ("pointopoint"), flags);
8723 flags = Fcons (intern ("noarp"), flags);
8725 if (adapter->HaveWins)
8726 flags = Fcons (intern ("WINS"), flags);
8727 if (adapter->DhcpEnabled)
8728 flags = Fcons (intern ("dynamic"), flags);
8730 res = Fcons (flags, res);
8732 /* Hardware address and its family. */
8733 for (n = 0; n < adapter->AddressLength; n++)
8734 p->contents[n] = make_number ((int) adapter->Address[n]);
8735 /* Windows does not support AF_LINK or AF_PACKET family
8736 of addresses. Use an arbitrary family number that is
8737 identical to what GNU/Linux returns. */
8738 res = Fcons (Fcons (make_number (1), hwaddr), res);
8740 /* Network mask. */
8741 sa.sin_family = AF_INET;
8742 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8743 if (net_mask != INADDR_NONE)
8745 sa.sin_addr.s_addr = net_mask;
8746 sa.sin_port = 0;
8747 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8748 sizeof (struct sockaddr)),
8749 res);
8751 else
8752 res = Fcons (Qnil, res);
8754 sa.sin_family = AF_INET;
8755 if (ip_addr != INADDR_NONE)
8757 /* Broadcast address is only reported by
8758 GetAdaptersAddresses, which is of limited
8759 availability. Generate it on our own. */
8760 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8762 sa.sin_addr.s_addr = bcast_addr;
8763 sa.sin_port = 0;
8764 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8765 sizeof (struct sockaddr)),
8766 res);
8768 /* IP address. */
8769 sa.sin_addr.s_addr = ip_addr;
8770 sa.sin_port = 0;
8771 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8772 sizeof (struct sockaddr)),
8773 res);
8775 else
8776 res = Fcons (Qnil, Fcons (Qnil, res));
8779 /* GetAdaptersInfo is documented to not report loopback
8780 interfaces, so we generate one out of thin air. */
8781 if (!lo_count)
8783 sa.sin_family = AF_INET;
8784 sa.sin_port = 0;
8785 if (NILP (ifname))
8787 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8788 res = Fcons (Fcons (build_string ("lo"),
8789 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8790 sizeof (struct sockaddr))),
8791 res);
8793 else if (strcmp (SSDATA (ifname), "lo") == 0)
8795 res = Fcons (Fcons (intern ("running"),
8796 Fcons (intern ("loopback"),
8797 Fcons (intern ("up"), Qnil))), Qnil);
8798 /* 772 is what 3 different GNU/Linux systems report for
8799 the loopback interface. */
8800 res = Fcons (Fcons (make_number (772),
8801 Fmake_vector (make_number (6),
8802 make_number (0))),
8803 res);
8804 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8805 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8806 sizeof (struct sockaddr)),
8807 res);
8808 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8809 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8810 sizeof (struct sockaddr)),
8811 res);
8812 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8813 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8814 sizeof (struct sockaddr)),
8815 res);
8821 done:
8822 xfree (ainfo);
8823 return res;
8826 Lisp_Object
8827 network_interface_list (void)
8829 return network_interface_get_info (Qnil);
8832 Lisp_Object
8833 network_interface_info (Lisp_Object ifname)
8835 CHECK_STRING (ifname);
8836 return network_interface_get_info (ifname);
8840 /* The Windows CRT functions are "optimized for speed", so they don't
8841 check for timezone and DST changes if they were last called less
8842 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8843 all Emacs features that repeatedly call time functions (e.g.,
8844 display-time) are in real danger of missing timezone and DST
8845 changes. Calling tzset before each localtime call fixes that. */
8846 struct tm *
8847 sys_localtime (const time_t *t)
8849 tzset ();
8850 return localtime (t);
8855 /* Try loading LIBRARY_ID from the file(s) specified in
8856 Vdynamic_library_alist. If the library is loaded successfully,
8857 return the handle of the DLL, and record the filename in the
8858 property :loaded-from of LIBRARY_ID. If the library could not be
8859 found, or when it was already loaded (because the handle is not
8860 recorded anywhere, and so is lost after use), return NULL.
8862 We could also save the handle in :loaded-from, but currently
8863 there's no use case for it. */
8864 HMODULE
8865 w32_delayed_load (Lisp_Object library_id)
8867 HMODULE dll_handle = NULL;
8869 CHECK_SYMBOL (library_id);
8871 if (CONSP (Vdynamic_library_alist)
8872 && NILP (Fassq (library_id, Vlibrary_cache)))
8874 Lisp_Object found = Qnil;
8875 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
8877 if (CONSP (dlls))
8878 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
8880 Lisp_Object dll = XCAR (dlls);
8881 char name[MAX_UTF8_PATH];
8882 DWORD res = -1;
8884 CHECK_STRING (dll);
8885 dll = ENCODE_FILE (dll);
8886 if (w32_unicode_filenames)
8888 wchar_t name_w[MAX_PATH];
8890 filename_to_utf16 (SSDATA (dll), name_w);
8891 dll_handle = LoadLibraryW (name_w);
8892 if (dll_handle)
8894 res = GetModuleFileNameW (dll_handle, name_w,
8895 sizeof (name_w));
8896 if (res > 0)
8897 filename_from_utf16 (name_w, name);
8900 else
8902 char name_a[MAX_PATH];
8904 filename_to_ansi (SSDATA (dll), name_a);
8905 dll_handle = LoadLibraryA (name_a);
8906 if (dll_handle)
8908 res = GetModuleFileNameA (dll_handle, name_a,
8909 sizeof (name_a));
8910 if (res > 0)
8911 filename_from_ansi (name_a, name);
8914 if (dll_handle)
8916 ptrdiff_t len = strlen (name);
8917 found = Fcons (dll,
8918 (res > 0)
8919 /* Possibly truncated */
8920 ? make_specified_string (name, -1, len, 1)
8921 : Qnil);
8922 /* This prevents thread start and end notifications
8923 from being sent to the DLL, for every thread we
8924 start. We don't need those notifications because
8925 threads we create never use any of these DLLs, only
8926 the main thread uses them. This is supposed to
8927 speed up thread creation. */
8928 DisableThreadLibraryCalls (dll_handle);
8929 break;
8933 Fput (library_id, QCloaded_from, found);
8936 return dll_handle;
8940 void
8941 check_windows_init_file (void)
8943 /* A common indication that Emacs is not installed properly is when
8944 it cannot find the Windows installation file. If this file does
8945 not exist in the expected place, tell the user. */
8947 if (!noninteractive && !inhibit_window_system
8948 /* Vload_path is not yet initialized when we are loading
8949 loadup.el. */
8950 && NILP (Vpurify_flag))
8952 Lisp_Object init_file;
8953 int fd;
8955 /* Implementation note: this function runs early during Emacs
8956 startup, before startup.el is run. So Vload_path is still in
8957 its initial unibyte form, but it holds UTF-8 encoded file
8958 names, since init_callproc was already called. So we do not
8959 need to ENCODE_FILE here, but we do need to convert the file
8960 names from UTF-8 to ANSI. */
8961 init_file = build_string ("term/w32-win");
8962 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
8963 if (fd < 0)
8965 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
8966 char *init_file_name = SDATA (init_file);
8967 char *load_path = SDATA (load_path_print);
8968 char *buffer = alloca (1024
8969 + strlen (init_file_name)
8970 + strlen (load_path));
8971 char *msg = buffer;
8972 int needed;
8974 sprintf (buffer,
8975 "The Emacs Windows initialization file \"%s.el\" "
8976 "could not be found in your Emacs installation. "
8977 "Emacs checked the following directories for this file:\n"
8978 "\n%s\n\n"
8979 "When Emacs cannot find this file, it usually means that it "
8980 "was not installed properly, or its distribution file was "
8981 "not unpacked properly.\nSee the README.W32 file in the "
8982 "top-level Emacs directory for more information.",
8983 init_file_name, load_path);
8984 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer,
8985 -1, NULL, 0);
8986 if (needed > 0)
8988 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
8990 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer, -1,
8991 msg_w, needed);
8992 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
8993 NULL, 0, NULL, NULL);
8994 if (needed > 0)
8996 char *msg_a = alloca (needed + 1);
8998 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
8999 NULL, NULL);
9000 msg = msg_a;
9003 MessageBox (NULL,
9004 msg,
9005 "Emacs Abort Dialog",
9006 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9007 /* Use the low-level system abort. */
9008 abort ();
9010 else
9012 _close (fd);
9017 void
9018 term_ntproc (int ignored)
9020 (void)ignored;
9022 term_timers ();
9024 /* shutdown the socket interface if necessary */
9025 term_winsock ();
9027 term_w32select ();
9030 void
9031 init_ntproc (int dumping)
9033 sigset_t initial_mask = 0;
9035 /* Initialize the socket interface now if available and requested by
9036 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9037 delayed until open-network-stream is called (w32-has-winsock can
9038 also be used to dynamically load or reload winsock).
9040 Conveniently, init_environment is called before us, so
9041 PRELOAD_WINSOCK can be set in the registry. */
9043 /* Always initialize this correctly. */
9044 winsock_lib = NULL;
9046 if (getenv ("PRELOAD_WINSOCK") != NULL)
9047 init_winsock (TRUE);
9049 /* Initial preparation for subprocess support: replace our standard
9050 handles with non-inheritable versions. */
9052 HANDLE parent;
9053 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9054 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9055 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9057 parent = GetCurrentProcess ();
9059 /* ignore errors when duplicating and closing; typically the
9060 handles will be invalid when running as a gui program. */
9061 DuplicateHandle (parent,
9062 GetStdHandle (STD_INPUT_HANDLE),
9063 parent,
9064 &stdin_save,
9066 FALSE,
9067 DUPLICATE_SAME_ACCESS);
9069 DuplicateHandle (parent,
9070 GetStdHandle (STD_OUTPUT_HANDLE),
9071 parent,
9072 &stdout_save,
9074 FALSE,
9075 DUPLICATE_SAME_ACCESS);
9077 DuplicateHandle (parent,
9078 GetStdHandle (STD_ERROR_HANDLE),
9079 parent,
9080 &stderr_save,
9082 FALSE,
9083 DUPLICATE_SAME_ACCESS);
9085 fclose (stdin);
9086 fclose (stdout);
9087 fclose (stderr);
9089 if (stdin_save != INVALID_HANDLE_VALUE)
9090 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9091 else
9092 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9093 _fdopen (0, "r");
9095 if (stdout_save != INVALID_HANDLE_VALUE)
9096 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9097 else
9098 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9099 _fdopen (1, "w");
9101 if (stderr_save != INVALID_HANDLE_VALUE)
9102 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9103 else
9104 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9105 _fdopen (2, "w");
9108 /* unfortunately, atexit depends on implementation of malloc */
9109 /* atexit (term_ntproc); */
9110 if (!dumping)
9112 /* Make sure we start with all signals unblocked. */
9113 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9114 signal (SIGABRT, term_ntproc);
9116 init_timers ();
9118 /* determine which drives are fixed, for GetCachedVolumeInformation */
9120 /* GetDriveType must have trailing backslash. */
9121 char drive[] = "A:\\";
9123 /* Loop over all possible drive letters */
9124 while (*drive <= 'Z')
9126 /* Record if this drive letter refers to a fixed drive. */
9127 fixed_drives[DRIVE_INDEX (*drive)] =
9128 (GetDriveType (drive) == DRIVE_FIXED);
9130 (*drive)++;
9133 /* Reset the volume info cache. */
9134 volume_cache = NULL;
9139 shutdown_handler ensures that buffers' autosave files are
9140 up to date when the user logs off, or the system shuts down.
9142 static BOOL WINAPI
9143 shutdown_handler (DWORD type)
9145 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9146 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9147 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9148 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9150 /* Shut down cleanly, making sure autosave files are up to date. */
9151 shut_down_emacs (0, Qnil);
9154 /* Allow other handlers to handle this signal. */
9155 return FALSE;
9158 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9159 NT, return a handle to GDI32.DLL. */
9160 HANDLE
9161 maybe_load_unicows_dll (void)
9163 if (os_subtype == OS_9X)
9165 HANDLE ret = LoadLibrary ("Unicows.dll");
9166 if (ret)
9168 /* These two functions are present on Windows 9X as stubs
9169 that always fail. We need the real implementations from
9170 UNICOWS.DLL, so we must call these functions through
9171 pointers, and assign the correct addresses to these
9172 pointers at program startup (see emacs.c, which calls
9173 this function early on). */
9174 pMultiByteToWideChar = GetProcAddress (ret, "MultiByteToWideChar");
9175 pWideCharToMultiByte = GetProcAddress (ret, "WideCharToMultiByte");
9176 return ret;
9178 else
9180 int button;
9182 button = MessageBox (NULL,
9183 "Emacs cannot load the UNICOWS.DLL library.\n"
9184 "This library is essential for using Emacs\n"
9185 "on this system. You need to install it.\n\n"
9186 "Emacs will exit when you click OK.",
9187 "Emacs cannot load UNICOWS.DLL",
9188 MB_ICONERROR | MB_TASKMODAL
9189 | MB_SETFOREGROUND | MB_OK);
9190 switch (button)
9192 case IDOK:
9193 default:
9194 exit (1);
9198 else
9200 /* On NT family of Windows, these two functions are always
9201 linked in, so we just assign their addresses to the 2
9202 pointers; no need for the LoadLibrary dance. */
9203 pMultiByteToWideChar = MultiByteToWideChar;
9204 pWideCharToMultiByte = WideCharToMultiByte;
9205 return LoadLibrary ("Gdi32.dll");
9210 globals_of_w32 is used to initialize those global variables that
9211 must always be initialized on startup even when the global variable
9212 initialized is non zero (see the function main in emacs.c).
9214 void
9215 globals_of_w32 (void)
9217 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9219 get_process_times_fn = (GetProcessTimes_Proc)
9220 GetProcAddress (kernel32, "GetProcessTimes");
9222 DEFSYM (QCloaded_from, ":loaded-from");
9224 g_b_init_is_windows_9x = 0;
9225 g_b_init_open_process_token = 0;
9226 g_b_init_get_token_information = 0;
9227 g_b_init_lookup_account_sid = 0;
9228 g_b_init_get_sid_sub_authority = 0;
9229 g_b_init_get_sid_sub_authority_count = 0;
9230 g_b_init_get_security_info = 0;
9231 g_b_init_get_file_security_w = 0;
9232 g_b_init_get_file_security_a = 0;
9233 g_b_init_get_security_descriptor_owner = 0;
9234 g_b_init_get_security_descriptor_group = 0;
9235 g_b_init_is_valid_sid = 0;
9236 g_b_init_create_toolhelp32_snapshot = 0;
9237 g_b_init_process32_first = 0;
9238 g_b_init_process32_next = 0;
9239 g_b_init_open_thread_token = 0;
9240 g_b_init_impersonate_self = 0;
9241 g_b_init_revert_to_self = 0;
9242 g_b_init_get_process_memory_info = 0;
9243 g_b_init_get_process_working_set_size = 0;
9244 g_b_init_global_memory_status = 0;
9245 g_b_init_global_memory_status_ex = 0;
9246 g_b_init_equal_sid = 0;
9247 g_b_init_copy_sid = 0;
9248 g_b_init_get_length_sid = 0;
9249 g_b_init_get_native_system_info = 0;
9250 g_b_init_get_system_times = 0;
9251 g_b_init_create_symbolic_link_w = 0;
9252 g_b_init_create_symbolic_link_a = 0;
9253 g_b_init_get_security_descriptor_dacl = 0;
9254 g_b_init_convert_sd_to_sddl = 0;
9255 g_b_init_convert_sddl_to_sd = 0;
9256 g_b_init_is_valid_security_descriptor = 0;
9257 g_b_init_set_file_security_w = 0;
9258 g_b_init_set_file_security_a = 0;
9259 g_b_init_set_named_security_info_w = 0;
9260 g_b_init_set_named_security_info_a = 0;
9261 g_b_init_get_adapters_info = 0;
9262 g_b_init_compare_string_w = 0;
9263 num_of_processors = 0;
9264 /* The following sets a handler for shutdown notifications for
9265 console apps. This actually applies to Emacs in both console and
9266 GUI modes, since we had to fool windows into thinking emacs is a
9267 console application to get console mode to work. */
9268 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9270 /* "None" is the default group name on standalone workstations. */
9271 strcpy (dflt_group_name, "None");
9273 /* Reset, in case it has some value inherited from dump time. */
9274 w32_stat_get_owner_group = 0;
9276 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9277 (a.k.a. "wide") APIs to invoke functions that accept file
9278 names. */
9279 if (is_windows_9x ())
9280 w32_unicode_filenames = 0;
9281 else
9282 w32_unicode_filenames = 1;
9285 /* For make-serial-process */
9287 serial_open (Lisp_Object port_obj)
9289 char *port = SSDATA (port_obj);
9290 HANDLE hnd;
9291 child_process *cp;
9292 int fd = -1;
9294 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9295 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9296 if (hnd == INVALID_HANDLE_VALUE)
9297 error ("Could not open %s", port);
9298 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9299 if (fd == -1)
9300 error ("Could not open %s", port);
9302 cp = new_child ();
9303 if (!cp)
9304 error ("Could not create child process");
9305 cp->fd = fd;
9306 cp->status = STATUS_READ_ACKNOWLEDGED;
9307 fd_info[ fd ].hnd = hnd;
9308 fd_info[ fd ].flags |=
9309 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9310 if (fd_info[ fd ].cp != NULL)
9312 error ("fd_info[fd = %d] is already in use", fd);
9314 fd_info[ fd ].cp = cp;
9315 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9316 if (cp->ovl_read.hEvent == NULL)
9317 error ("Could not create read event");
9318 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9319 if (cp->ovl_write.hEvent == NULL)
9320 error ("Could not create write event");
9322 return fd;
9325 /* For serial-process-configure */
9326 void
9327 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9329 Lisp_Object childp2 = Qnil;
9330 Lisp_Object tem = Qnil;
9331 HANDLE hnd;
9332 DCB dcb;
9333 COMMTIMEOUTS ct;
9334 char summary[4] = "???"; /* This usually becomes "8N1". */
9336 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9337 error ("Not a serial process");
9338 hnd = fd_info[ p->outfd ].hnd;
9340 childp2 = Fcopy_sequence (p->childp);
9342 /* Initialize timeouts for blocking read and blocking write. */
9343 if (!GetCommTimeouts (hnd, &ct))
9344 error ("GetCommTimeouts() failed");
9345 ct.ReadIntervalTimeout = 0;
9346 ct.ReadTotalTimeoutMultiplier = 0;
9347 ct.ReadTotalTimeoutConstant = 0;
9348 ct.WriteTotalTimeoutMultiplier = 0;
9349 ct.WriteTotalTimeoutConstant = 0;
9350 if (!SetCommTimeouts (hnd, &ct))
9351 error ("SetCommTimeouts() failed");
9352 /* Read port attributes and prepare default configuration. */
9353 memset (&dcb, 0, sizeof (dcb));
9354 dcb.DCBlength = sizeof (DCB);
9355 if (!GetCommState (hnd, &dcb))
9356 error ("GetCommState() failed");
9357 dcb.fBinary = TRUE;
9358 dcb.fNull = FALSE;
9359 dcb.fAbortOnError = FALSE;
9360 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9361 dcb.ErrorChar = 0;
9362 dcb.EofChar = 0;
9363 dcb.EvtChar = 0;
9365 /* Configure speed. */
9366 if (!NILP (Fplist_member (contact, QCspeed)))
9367 tem = Fplist_get (contact, QCspeed);
9368 else
9369 tem = Fplist_get (p->childp, QCspeed);
9370 CHECK_NUMBER (tem);
9371 dcb.BaudRate = XINT (tem);
9372 childp2 = Fplist_put (childp2, QCspeed, tem);
9374 /* Configure bytesize. */
9375 if (!NILP (Fplist_member (contact, QCbytesize)))
9376 tem = Fplist_get (contact, QCbytesize);
9377 else
9378 tem = Fplist_get (p->childp, QCbytesize);
9379 if (NILP (tem))
9380 tem = make_number (8);
9381 CHECK_NUMBER (tem);
9382 if (XINT (tem) != 7 && XINT (tem) != 8)
9383 error (":bytesize must be nil (8), 7, or 8");
9384 dcb.ByteSize = XINT (tem);
9385 summary[0] = XINT (tem) + '0';
9386 childp2 = Fplist_put (childp2, QCbytesize, tem);
9388 /* Configure parity. */
9389 if (!NILP (Fplist_member (contact, QCparity)))
9390 tem = Fplist_get (contact, QCparity);
9391 else
9392 tem = Fplist_get (p->childp, QCparity);
9393 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9394 error (":parity must be nil (no parity), `even', or `odd'");
9395 dcb.fParity = FALSE;
9396 dcb.Parity = NOPARITY;
9397 dcb.fErrorChar = FALSE;
9398 if (NILP (tem))
9400 summary[1] = 'N';
9402 else if (EQ (tem, Qeven))
9404 summary[1] = 'E';
9405 dcb.fParity = TRUE;
9406 dcb.Parity = EVENPARITY;
9407 dcb.fErrorChar = TRUE;
9409 else if (EQ (tem, Qodd))
9411 summary[1] = 'O';
9412 dcb.fParity = TRUE;
9413 dcb.Parity = ODDPARITY;
9414 dcb.fErrorChar = TRUE;
9416 childp2 = Fplist_put (childp2, QCparity, tem);
9418 /* Configure stopbits. */
9419 if (!NILP (Fplist_member (contact, QCstopbits)))
9420 tem = Fplist_get (contact, QCstopbits);
9421 else
9422 tem = Fplist_get (p->childp, QCstopbits);
9423 if (NILP (tem))
9424 tem = make_number (1);
9425 CHECK_NUMBER (tem);
9426 if (XINT (tem) != 1 && XINT (tem) != 2)
9427 error (":stopbits must be nil (1 stopbit), 1, or 2");
9428 summary[2] = XINT (tem) + '0';
9429 if (XINT (tem) == 1)
9430 dcb.StopBits = ONESTOPBIT;
9431 else if (XINT (tem) == 2)
9432 dcb.StopBits = TWOSTOPBITS;
9433 childp2 = Fplist_put (childp2, QCstopbits, tem);
9435 /* Configure flowcontrol. */
9436 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9437 tem = Fplist_get (contact, QCflowcontrol);
9438 else
9439 tem = Fplist_get (p->childp, QCflowcontrol);
9440 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9441 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9442 dcb.fOutxCtsFlow = FALSE;
9443 dcb.fOutxDsrFlow = FALSE;
9444 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9445 dcb.fDsrSensitivity = FALSE;
9446 dcb.fTXContinueOnXoff = FALSE;
9447 dcb.fOutX = FALSE;
9448 dcb.fInX = FALSE;
9449 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9450 dcb.XonChar = 17; /* Control-Q */
9451 dcb.XoffChar = 19; /* Control-S */
9452 if (NILP (tem))
9454 /* Already configured. */
9456 else if (EQ (tem, Qhw))
9458 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9459 dcb.fOutxCtsFlow = TRUE;
9461 else if (EQ (tem, Qsw))
9463 dcb.fOutX = TRUE;
9464 dcb.fInX = TRUE;
9466 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9468 /* Activate configuration. */
9469 if (!SetCommState (hnd, &dcb))
9470 error ("SetCommState() failed");
9472 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9473 pset_childp (p, childp2);
9476 #ifdef HAVE_GNUTLS
9478 ssize_t
9479 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9481 int n, err;
9482 struct Lisp_Process *process = (struct Lisp_Process *)p;
9483 int fd = process->infd;
9485 n = sys_read (fd, (char*)buf, sz);
9487 if (n >= 0)
9488 return n;
9490 err = errno;
9492 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9493 if (err == EWOULDBLOCK)
9494 err = EAGAIN;
9496 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9498 return -1;
9501 ssize_t
9502 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9504 struct Lisp_Process *process = (struct Lisp_Process *)p;
9505 int fd = process->outfd;
9506 ssize_t n = sys_write (fd, buf, sz);
9508 /* 0 or more bytes written means everything went fine. */
9509 if (n >= 0)
9510 return n;
9512 /* Negative bytes written means we got an error in errno.
9513 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9514 emacs_gnutls_transport_set_errno (process->gnutls_state,
9515 errno == EWOULDBLOCK ? EAGAIN : errno);
9517 return -1;
9519 #endif /* HAVE_GNUTLS */
9521 /* end of w32.c */