custom-buffer-style doc fix
[emacs.git] / src / w32.c
blobc26f14593f1e0adf1170869253540cc5fac021c0
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #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 PATH_EXEC */
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 attaching 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 <wincrypt.h>
229 #include <c-strcase.h>
231 #include "w32.h"
232 #include <dirent.h>
233 #include "w32common.h"
234 #include "w32select.h"
235 #include "systime.h" /* for current_timespec, struct timespec */
236 #include "dispextern.h" /* for xstrcasecmp */
237 #include "coding.h" /* for Vlocale_coding_system */
239 #include "careadlinkat.h"
240 #include "allocator.h"
242 /* For Lisp_Process, serial_configure and serial_open. */
243 #include "process.h"
244 #include "systty.h"
246 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
247 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
249 void globals_of_w32 (void);
250 static DWORD get_rid (PSID);
251 static int is_symlink (const char *);
252 static char * chase_symlinks (const char *);
253 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
254 static int restore_privilege (TOKEN_PRIVILEGES *);
255 static BOOL WINAPI revert_to_self (void);
257 static int sys_access (const char *, int);
258 extern void *e_malloc (size_t);
259 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
260 struct timespec *, void *);
261 extern int sys_dup (int);
266 /* Initialization states.
268 WARNING: If you add any more such variables for additional APIs,
269 you MUST add initialization for them to globals_of_w32
270 below. This is because these variables might get set
271 to non-NULL values during dumping, but the dumped Emacs
272 cannot reuse those values, because it could be run on a
273 different version of the OS, where API addresses are
274 different. */
275 static BOOL g_b_init_is_windows_9x;
276 static BOOL g_b_init_open_process_token;
277 static BOOL g_b_init_get_token_information;
278 static BOOL g_b_init_lookup_account_sid;
279 static BOOL g_b_init_get_sid_sub_authority;
280 static BOOL g_b_init_get_sid_sub_authority_count;
281 static BOOL g_b_init_get_security_info;
282 static BOOL g_b_init_get_file_security_w;
283 static BOOL g_b_init_get_file_security_a;
284 static BOOL g_b_init_get_security_descriptor_owner;
285 static BOOL g_b_init_get_security_descriptor_group;
286 static BOOL g_b_init_is_valid_sid;
287 static BOOL g_b_init_create_toolhelp32_snapshot;
288 static BOOL g_b_init_process32_first;
289 static BOOL g_b_init_process32_next;
290 static BOOL g_b_init_open_thread_token;
291 static BOOL g_b_init_impersonate_self;
292 static BOOL g_b_init_revert_to_self;
293 static BOOL g_b_init_get_process_memory_info;
294 static BOOL g_b_init_get_process_working_set_size;
295 static BOOL g_b_init_global_memory_status;
296 static BOOL g_b_init_global_memory_status_ex;
297 static BOOL g_b_init_get_length_sid;
298 static BOOL g_b_init_equal_sid;
299 static BOOL g_b_init_copy_sid;
300 static BOOL g_b_init_get_native_system_info;
301 static BOOL g_b_init_get_system_times;
302 static BOOL g_b_init_create_symbolic_link_w;
303 static BOOL g_b_init_create_symbolic_link_a;
304 static BOOL g_b_init_get_security_descriptor_dacl;
305 static BOOL g_b_init_convert_sd_to_sddl;
306 static BOOL g_b_init_convert_sddl_to_sd;
307 static BOOL g_b_init_is_valid_security_descriptor;
308 static BOOL g_b_init_set_file_security_w;
309 static BOOL g_b_init_set_file_security_a;
310 static BOOL g_b_init_set_named_security_info_w;
311 static BOOL g_b_init_set_named_security_info_a;
312 static BOOL g_b_init_get_adapters_info;
314 BOOL g_b_init_compare_string_w;
317 BEGIN: Wrapper functions around OpenProcessToken
318 and other functions in advapi32.dll that are only
319 supported in Windows NT / 2k / XP
321 /* ** Function pointer typedefs ** */
322 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
323 HANDLE ProcessHandle,
324 DWORD DesiredAccess,
325 PHANDLE TokenHandle);
326 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
327 HANDLE TokenHandle,
328 TOKEN_INFORMATION_CLASS TokenInformationClass,
329 LPVOID TokenInformation,
330 DWORD TokenInformationLength,
331 PDWORD ReturnLength);
332 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
333 HANDLE process_handle,
334 LPFILETIME creation_time,
335 LPFILETIME exit_time,
336 LPFILETIME kernel_time,
337 LPFILETIME user_time);
339 GetProcessTimes_Proc get_process_times_fn = NULL;
341 #ifdef _UNICODE
342 const char * const LookupAccountSid_Name = "LookupAccountSidW";
343 #else
344 const char * const LookupAccountSid_Name = "LookupAccountSidA";
345 #endif
346 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
347 LPCTSTR lpSystemName,
348 PSID Sid,
349 LPTSTR Name,
350 LPDWORD cbName,
351 LPTSTR DomainName,
352 LPDWORD cbDomainName,
353 PSID_NAME_USE peUse);
354 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
355 PSID pSid,
356 DWORD n);
357 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
358 PSID pSid);
359 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
360 HANDLE handle,
361 SE_OBJECT_TYPE ObjectType,
362 SECURITY_INFORMATION SecurityInfo,
363 PSID *ppsidOwner,
364 PSID *ppsidGroup,
365 PACL *ppDacl,
366 PACL *ppSacl,
367 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
368 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
369 LPCWSTR lpFileName,
370 SECURITY_INFORMATION RequestedInformation,
371 PSECURITY_DESCRIPTOR pSecurityDescriptor,
372 DWORD nLength,
373 LPDWORD lpnLengthNeeded);
374 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
375 LPCSTR lpFileName,
376 SECURITY_INFORMATION RequestedInformation,
377 PSECURITY_DESCRIPTOR pSecurityDescriptor,
378 DWORD nLength,
379 LPDWORD lpnLengthNeeded);
380 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
381 LPCWSTR lpFileName,
382 SECURITY_INFORMATION SecurityInformation,
383 PSECURITY_DESCRIPTOR pSecurityDescriptor);
384 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
385 LPCSTR lpFileName,
386 SECURITY_INFORMATION SecurityInformation,
387 PSECURITY_DESCRIPTOR pSecurityDescriptor);
388 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
389 LPCWSTR lpObjectName,
390 SE_OBJECT_TYPE ObjectType,
391 SECURITY_INFORMATION SecurityInformation,
392 PSID psidOwner,
393 PSID psidGroup,
394 PACL pDacl,
395 PACL pSacl);
396 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
397 LPCSTR lpObjectName,
398 SE_OBJECT_TYPE ObjectType,
399 SECURITY_INFORMATION SecurityInformation,
400 PSID psidOwner,
401 PSID psidGroup,
402 PACL pDacl,
403 PACL pSacl);
404 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
405 PSECURITY_DESCRIPTOR pSecurityDescriptor,
406 PSID *pOwner,
407 LPBOOL lpbOwnerDefaulted);
408 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
409 PSECURITY_DESCRIPTOR pSecurityDescriptor,
410 PSID *pGroup,
411 LPBOOL lpbGroupDefaulted);
412 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
413 PSECURITY_DESCRIPTOR pSecurityDescriptor,
414 LPBOOL lpbDaclPresent,
415 PACL *pDacl,
416 LPBOOL lpbDaclDefaulted);
417 typedef BOOL (WINAPI * IsValidSid_Proc) (
418 PSID sid);
419 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
420 DWORD dwFlags,
421 DWORD th32ProcessID);
422 typedef BOOL (WINAPI * Process32First_Proc) (
423 HANDLE hSnapshot,
424 LPPROCESSENTRY32 lppe);
425 typedef BOOL (WINAPI * Process32Next_Proc) (
426 HANDLE hSnapshot,
427 LPPROCESSENTRY32 lppe);
428 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
429 HANDLE ThreadHandle,
430 DWORD DesiredAccess,
431 BOOL OpenAsSelf,
432 PHANDLE TokenHandle);
433 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
434 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
435 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
436 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
437 HANDLE Process,
438 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
439 DWORD cb);
440 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
441 HANDLE hProcess,
442 PSIZE_T lpMinimumWorkingSetSize,
443 PSIZE_T lpMaximumWorkingSetSize);
444 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
445 LPMEMORYSTATUS lpBuffer);
446 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
447 LPMEMORY_STATUS_EX lpBuffer);
448 typedef BOOL (WINAPI * CopySid_Proc) (
449 DWORD nDestinationSidLength,
450 PSID pDestinationSid,
451 PSID pSourceSid);
452 typedef BOOL (WINAPI * EqualSid_Proc) (
453 PSID pSid1,
454 PSID pSid2);
455 typedef DWORD (WINAPI * GetLengthSid_Proc) (
456 PSID pSid);
457 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
458 LPSYSTEM_INFO lpSystemInfo);
459 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
460 LPFILETIME lpIdleTime,
461 LPFILETIME lpKernelTime,
462 LPFILETIME lpUserTime);
463 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
464 LPCWSTR lpSymlinkFileName,
465 LPCWSTR lpTargetFileName,
466 DWORD dwFlags);
467 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
468 LPCSTR lpSymlinkFileName,
469 LPCSTR lpTargetFileName,
470 DWORD dwFlags);
471 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
472 LPCTSTR StringSecurityDescriptor,
473 DWORD StringSDRevision,
474 PSECURITY_DESCRIPTOR *SecurityDescriptor,
475 PULONG SecurityDescriptorSize);
476 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
477 PSECURITY_DESCRIPTOR SecurityDescriptor,
478 DWORD RequestedStringSDRevision,
479 SECURITY_INFORMATION SecurityInformation,
480 LPTSTR *StringSecurityDescriptor,
481 PULONG StringSecurityDescriptorLen);
482 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
483 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
484 PIP_ADAPTER_INFO pAdapterInfo,
485 PULONG pOutBufLen);
487 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
488 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
489 DWORD multiByteToWideCharFlags;
491 /* ** A utility function ** */
492 static BOOL
493 is_windows_9x (void)
495 static BOOL s_b_ret = 0;
496 OSVERSIONINFO os_ver;
497 if (g_b_init_is_windows_9x == 0)
499 g_b_init_is_windows_9x = 1;
500 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
501 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
502 if (GetVersionEx (&os_ver))
504 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
507 return s_b_ret;
510 static Lisp_Object ltime (ULONGLONG);
512 /* Get total user and system times for get-internal-run-time.
513 Returns a list of integers if the times are provided by the OS
514 (NT derivatives), otherwise it returns the result of current-time. */
515 Lisp_Object
516 w32_get_internal_run_time (void)
518 if (get_process_times_fn)
520 FILETIME create, exit, kernel, user;
521 HANDLE proc = GetCurrentProcess ();
522 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
524 LARGE_INTEGER user_int, kernel_int, total;
525 user_int.LowPart = user.dwLowDateTime;
526 user_int.HighPart = user.dwHighDateTime;
527 kernel_int.LowPart = kernel.dwLowDateTime;
528 kernel_int.HighPart = kernel.dwHighDateTime;
529 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
530 return ltime (total.QuadPart);
534 return Fcurrent_time ();
537 /* ** The wrapper functions ** */
539 static BOOL WINAPI
540 open_process_token (HANDLE ProcessHandle,
541 DWORD DesiredAccess,
542 PHANDLE TokenHandle)
544 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
545 HMODULE hm_advapi32 = NULL;
546 if (is_windows_9x () == TRUE)
548 return FALSE;
550 if (g_b_init_open_process_token == 0)
552 g_b_init_open_process_token = 1;
553 hm_advapi32 = LoadLibrary ("Advapi32.dll");
554 s_pfn_Open_Process_Token =
555 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
557 if (s_pfn_Open_Process_Token == NULL)
559 return FALSE;
561 return (
562 s_pfn_Open_Process_Token (
563 ProcessHandle,
564 DesiredAccess,
565 TokenHandle)
569 static BOOL WINAPI
570 get_token_information (HANDLE TokenHandle,
571 TOKEN_INFORMATION_CLASS TokenInformationClass,
572 LPVOID TokenInformation,
573 DWORD TokenInformationLength,
574 PDWORD ReturnLength)
576 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
577 HMODULE hm_advapi32 = NULL;
578 if (is_windows_9x () == TRUE)
580 return FALSE;
582 if (g_b_init_get_token_information == 0)
584 g_b_init_get_token_information = 1;
585 hm_advapi32 = LoadLibrary ("Advapi32.dll");
586 s_pfn_Get_Token_Information =
587 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
589 if (s_pfn_Get_Token_Information == NULL)
591 return FALSE;
593 return (
594 s_pfn_Get_Token_Information (
595 TokenHandle,
596 TokenInformationClass,
597 TokenInformation,
598 TokenInformationLength,
599 ReturnLength)
603 static BOOL WINAPI
604 lookup_account_sid (LPCTSTR lpSystemName,
605 PSID Sid,
606 LPTSTR Name,
607 LPDWORD cbName,
608 LPTSTR DomainName,
609 LPDWORD cbDomainName,
610 PSID_NAME_USE peUse)
612 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
613 HMODULE hm_advapi32 = NULL;
614 if (is_windows_9x () == TRUE)
616 return FALSE;
618 if (g_b_init_lookup_account_sid == 0)
620 g_b_init_lookup_account_sid = 1;
621 hm_advapi32 = LoadLibrary ("Advapi32.dll");
622 s_pfn_Lookup_Account_Sid =
623 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
625 if (s_pfn_Lookup_Account_Sid == NULL)
627 return FALSE;
629 return (
630 s_pfn_Lookup_Account_Sid (
631 lpSystemName,
632 Sid,
633 Name,
634 cbName,
635 DomainName,
636 cbDomainName,
637 peUse)
641 static PDWORD WINAPI
642 get_sid_sub_authority (PSID pSid, DWORD n)
644 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
645 static DWORD zero = 0U;
646 HMODULE hm_advapi32 = NULL;
647 if (is_windows_9x () == TRUE)
649 return &zero;
651 if (g_b_init_get_sid_sub_authority == 0)
653 g_b_init_get_sid_sub_authority = 1;
654 hm_advapi32 = LoadLibrary ("Advapi32.dll");
655 s_pfn_Get_Sid_Sub_Authority =
656 (GetSidSubAuthority_Proc) GetProcAddress (
657 hm_advapi32, "GetSidSubAuthority");
659 if (s_pfn_Get_Sid_Sub_Authority == NULL)
661 return &zero;
663 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
666 static PUCHAR WINAPI
667 get_sid_sub_authority_count (PSID pSid)
669 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
670 static UCHAR zero = 0U;
671 HMODULE hm_advapi32 = NULL;
672 if (is_windows_9x () == TRUE)
674 return &zero;
676 if (g_b_init_get_sid_sub_authority_count == 0)
678 g_b_init_get_sid_sub_authority_count = 1;
679 hm_advapi32 = LoadLibrary ("Advapi32.dll");
680 s_pfn_Get_Sid_Sub_Authority_Count =
681 (GetSidSubAuthorityCount_Proc) GetProcAddress (
682 hm_advapi32, "GetSidSubAuthorityCount");
684 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
686 return &zero;
688 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
691 static DWORD WINAPI
692 get_security_info (HANDLE handle,
693 SE_OBJECT_TYPE ObjectType,
694 SECURITY_INFORMATION SecurityInfo,
695 PSID *ppsidOwner,
696 PSID *ppsidGroup,
697 PACL *ppDacl,
698 PACL *ppSacl,
699 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
701 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
702 HMODULE hm_advapi32 = NULL;
703 if (is_windows_9x () == TRUE)
705 return FALSE;
707 if (g_b_init_get_security_info == 0)
709 g_b_init_get_security_info = 1;
710 hm_advapi32 = LoadLibrary ("Advapi32.dll");
711 s_pfn_Get_Security_Info =
712 (GetSecurityInfo_Proc) GetProcAddress (
713 hm_advapi32, "GetSecurityInfo");
715 if (s_pfn_Get_Security_Info == NULL)
717 return FALSE;
719 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
720 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
721 ppSecurityDescriptor));
724 static BOOL WINAPI
725 get_file_security (const char *lpFileName,
726 SECURITY_INFORMATION RequestedInformation,
727 PSECURITY_DESCRIPTOR pSecurityDescriptor,
728 DWORD nLength,
729 LPDWORD lpnLengthNeeded)
731 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
732 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
733 HMODULE hm_advapi32 = NULL;
734 if (is_windows_9x () == TRUE)
736 errno = ENOTSUP;
737 return FALSE;
739 if (w32_unicode_filenames)
741 wchar_t filename_w[MAX_PATH];
743 if (g_b_init_get_file_security_w == 0)
745 g_b_init_get_file_security_w = 1;
746 hm_advapi32 = LoadLibrary ("Advapi32.dll");
747 s_pfn_Get_File_SecurityW =
748 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
749 "GetFileSecurityW");
751 if (s_pfn_Get_File_SecurityW == NULL)
753 errno = ENOTSUP;
754 return FALSE;
756 filename_to_utf16 (lpFileName, filename_w);
757 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
758 pSecurityDescriptor, nLength,
759 lpnLengthNeeded));
761 else
763 char filename_a[MAX_PATH];
765 if (g_b_init_get_file_security_a == 0)
767 g_b_init_get_file_security_a = 1;
768 hm_advapi32 = LoadLibrary ("Advapi32.dll");
769 s_pfn_Get_File_SecurityA =
770 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
771 "GetFileSecurityA");
773 if (s_pfn_Get_File_SecurityA == NULL)
775 errno = ENOTSUP;
776 return FALSE;
778 filename_to_ansi (lpFileName, filename_a);
779 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
780 pSecurityDescriptor, nLength,
781 lpnLengthNeeded));
785 static BOOL WINAPI
786 set_file_security (const char *lpFileName,
787 SECURITY_INFORMATION SecurityInformation,
788 PSECURITY_DESCRIPTOR pSecurityDescriptor)
790 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
791 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
792 HMODULE hm_advapi32 = NULL;
793 if (is_windows_9x () == TRUE)
795 errno = ENOTSUP;
796 return FALSE;
798 if (w32_unicode_filenames)
800 wchar_t filename_w[MAX_PATH];
802 if (g_b_init_set_file_security_w == 0)
804 g_b_init_set_file_security_w = 1;
805 hm_advapi32 = LoadLibrary ("Advapi32.dll");
806 s_pfn_Set_File_SecurityW =
807 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
808 "SetFileSecurityW");
810 if (s_pfn_Set_File_SecurityW == NULL)
812 errno = ENOTSUP;
813 return FALSE;
815 filename_to_utf16 (lpFileName, filename_w);
816 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
817 pSecurityDescriptor));
819 else
821 char filename_a[MAX_PATH];
823 if (g_b_init_set_file_security_a == 0)
825 g_b_init_set_file_security_a = 1;
826 hm_advapi32 = LoadLibrary ("Advapi32.dll");
827 s_pfn_Set_File_SecurityA =
828 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
829 "SetFileSecurityA");
831 if (s_pfn_Set_File_SecurityA == NULL)
833 errno = ENOTSUP;
834 return FALSE;
836 filename_to_ansi (lpFileName, filename_a);
837 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
838 pSecurityDescriptor));
842 static DWORD WINAPI
843 set_named_security_info (LPCTSTR lpObjectName,
844 SE_OBJECT_TYPE ObjectType,
845 SECURITY_INFORMATION SecurityInformation,
846 PSID psidOwner,
847 PSID psidGroup,
848 PACL pDacl,
849 PACL pSacl)
851 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
852 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
853 HMODULE hm_advapi32 = NULL;
854 if (is_windows_9x () == TRUE)
856 errno = ENOTSUP;
857 return ENOTSUP;
859 if (w32_unicode_filenames)
861 wchar_t filename_w[MAX_PATH];
863 if (g_b_init_set_named_security_info_w == 0)
865 g_b_init_set_named_security_info_w = 1;
866 hm_advapi32 = LoadLibrary ("Advapi32.dll");
867 s_pfn_Set_Named_Security_InfoW =
868 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
869 "SetNamedSecurityInfoW");
871 if (s_pfn_Set_Named_Security_InfoW == NULL)
873 errno = ENOTSUP;
874 return ENOTSUP;
876 filename_to_utf16 (lpObjectName, filename_w);
877 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
878 SecurityInformation, psidOwner,
879 psidGroup, pDacl, pSacl));
881 else
883 char filename_a[MAX_PATH];
885 if (g_b_init_set_named_security_info_a == 0)
887 g_b_init_set_named_security_info_a = 1;
888 hm_advapi32 = LoadLibrary ("Advapi32.dll");
889 s_pfn_Set_Named_Security_InfoA =
890 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
891 "SetNamedSecurityInfoA");
893 if (s_pfn_Set_Named_Security_InfoA == NULL)
895 errno = ENOTSUP;
896 return ENOTSUP;
898 filename_to_ansi (lpObjectName, filename_a);
899 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
900 SecurityInformation, psidOwner,
901 psidGroup, pDacl, pSacl));
905 static BOOL WINAPI
906 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
907 PSID *pOwner,
908 LPBOOL lpbOwnerDefaulted)
910 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
911 HMODULE hm_advapi32 = NULL;
912 if (is_windows_9x () == TRUE)
914 errno = ENOTSUP;
915 return FALSE;
917 if (g_b_init_get_security_descriptor_owner == 0)
919 g_b_init_get_security_descriptor_owner = 1;
920 hm_advapi32 = LoadLibrary ("Advapi32.dll");
921 s_pfn_Get_Security_Descriptor_Owner =
922 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
923 hm_advapi32, "GetSecurityDescriptorOwner");
925 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
927 errno = ENOTSUP;
928 return FALSE;
930 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
931 lpbOwnerDefaulted));
934 static BOOL WINAPI
935 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
936 PSID *pGroup,
937 LPBOOL lpbGroupDefaulted)
939 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
940 HMODULE hm_advapi32 = NULL;
941 if (is_windows_9x () == TRUE)
943 errno = ENOTSUP;
944 return FALSE;
946 if (g_b_init_get_security_descriptor_group == 0)
948 g_b_init_get_security_descriptor_group = 1;
949 hm_advapi32 = LoadLibrary ("Advapi32.dll");
950 s_pfn_Get_Security_Descriptor_Group =
951 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
952 hm_advapi32, "GetSecurityDescriptorGroup");
954 if (s_pfn_Get_Security_Descriptor_Group == NULL)
956 errno = ENOTSUP;
957 return FALSE;
959 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
960 lpbGroupDefaulted));
963 static BOOL WINAPI
964 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
965 LPBOOL lpbDaclPresent,
966 PACL *pDacl,
967 LPBOOL lpbDaclDefaulted)
969 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
970 HMODULE hm_advapi32 = NULL;
971 if (is_windows_9x () == TRUE)
973 errno = ENOTSUP;
974 return FALSE;
976 if (g_b_init_get_security_descriptor_dacl == 0)
978 g_b_init_get_security_descriptor_dacl = 1;
979 hm_advapi32 = LoadLibrary ("Advapi32.dll");
980 s_pfn_Get_Security_Descriptor_Dacl =
981 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
982 hm_advapi32, "GetSecurityDescriptorDacl");
984 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
986 errno = ENOTSUP;
987 return FALSE;
989 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
990 lpbDaclPresent, pDacl,
991 lpbDaclDefaulted));
994 static BOOL WINAPI
995 is_valid_sid (PSID sid)
997 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
998 HMODULE hm_advapi32 = NULL;
999 if (is_windows_9x () == TRUE)
1001 return FALSE;
1003 if (g_b_init_is_valid_sid == 0)
1005 g_b_init_is_valid_sid = 1;
1006 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1007 s_pfn_Is_Valid_Sid =
1008 (IsValidSid_Proc) GetProcAddress (
1009 hm_advapi32, "IsValidSid");
1011 if (s_pfn_Is_Valid_Sid == NULL)
1013 return FALSE;
1015 return (s_pfn_Is_Valid_Sid (sid));
1018 static BOOL WINAPI
1019 equal_sid (PSID sid1, PSID sid2)
1021 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1022 HMODULE hm_advapi32 = NULL;
1023 if (is_windows_9x () == TRUE)
1025 return FALSE;
1027 if (g_b_init_equal_sid == 0)
1029 g_b_init_equal_sid = 1;
1030 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1031 s_pfn_Equal_Sid =
1032 (EqualSid_Proc) GetProcAddress (
1033 hm_advapi32, "EqualSid");
1035 if (s_pfn_Equal_Sid == NULL)
1037 return FALSE;
1039 return (s_pfn_Equal_Sid (sid1, sid2));
1042 static DWORD WINAPI
1043 get_length_sid (PSID sid)
1045 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1046 HMODULE hm_advapi32 = NULL;
1047 if (is_windows_9x () == TRUE)
1049 return 0;
1051 if (g_b_init_get_length_sid == 0)
1053 g_b_init_get_length_sid = 1;
1054 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1055 s_pfn_Get_Length_Sid =
1056 (GetLengthSid_Proc) GetProcAddress (
1057 hm_advapi32, "GetLengthSid");
1059 if (s_pfn_Get_Length_Sid == NULL)
1061 return 0;
1063 return (s_pfn_Get_Length_Sid (sid));
1066 static BOOL WINAPI
1067 copy_sid (DWORD destlen, PSID dest, PSID src)
1069 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1070 HMODULE hm_advapi32 = NULL;
1071 if (is_windows_9x () == TRUE)
1073 return FALSE;
1075 if (g_b_init_copy_sid == 0)
1077 g_b_init_copy_sid = 1;
1078 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1079 s_pfn_Copy_Sid =
1080 (CopySid_Proc) GetProcAddress (
1081 hm_advapi32, "CopySid");
1083 if (s_pfn_Copy_Sid == NULL)
1085 return FALSE;
1087 return (s_pfn_Copy_Sid (destlen, dest, src));
1091 END: Wrapper functions around OpenProcessToken
1092 and other functions in advapi32.dll that are only
1093 supported in Windows NT / 2k / XP
1096 static void WINAPI
1097 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1099 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1100 if (is_windows_9x () != TRUE)
1102 if (g_b_init_get_native_system_info == 0)
1104 g_b_init_get_native_system_info = 1;
1105 s_pfn_Get_Native_System_Info =
1106 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1107 "GetNativeSystemInfo");
1109 if (s_pfn_Get_Native_System_Info != NULL)
1110 s_pfn_Get_Native_System_Info (lpSystemInfo);
1112 else
1113 lpSystemInfo->dwNumberOfProcessors = -1;
1116 static BOOL WINAPI
1117 get_system_times (LPFILETIME lpIdleTime,
1118 LPFILETIME lpKernelTime,
1119 LPFILETIME lpUserTime)
1121 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1122 if (is_windows_9x () == TRUE)
1124 return FALSE;
1126 if (g_b_init_get_system_times == 0)
1128 g_b_init_get_system_times = 1;
1129 s_pfn_Get_System_times =
1130 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1131 "GetSystemTimes");
1133 if (s_pfn_Get_System_times == NULL)
1134 return FALSE;
1135 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1138 static BOOLEAN WINAPI
1139 create_symbolic_link (LPCSTR lpSymlinkFilename,
1140 LPCSTR lpTargetFileName,
1141 DWORD dwFlags)
1143 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1144 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1145 BOOLEAN retval;
1147 if (is_windows_9x () == TRUE)
1149 errno = ENOSYS;
1150 return 0;
1152 if (w32_unicode_filenames)
1154 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1156 if (g_b_init_create_symbolic_link_w == 0)
1158 g_b_init_create_symbolic_link_w = 1;
1159 s_pfn_Create_Symbolic_LinkW =
1160 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1161 "CreateSymbolicLinkW");
1163 if (s_pfn_Create_Symbolic_LinkW == NULL)
1165 errno = ENOSYS;
1166 return 0;
1169 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1170 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1171 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1172 /* If we were denied creation of the symlink, try again after
1173 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1174 if (!retval)
1176 TOKEN_PRIVILEGES priv_current;
1178 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1179 &priv_current))
1181 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1182 restore_privilege (&priv_current);
1183 revert_to_self ();
1187 else
1189 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1191 if (g_b_init_create_symbolic_link_a == 0)
1193 g_b_init_create_symbolic_link_a = 1;
1194 s_pfn_Create_Symbolic_LinkA =
1195 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1196 "CreateSymbolicLinkA");
1198 if (s_pfn_Create_Symbolic_LinkA == NULL)
1200 errno = ENOSYS;
1201 return 0;
1204 filename_to_ansi (lpSymlinkFilename, symfn_a);
1205 filename_to_ansi (lpTargetFileName, tgtfn_a);
1206 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1207 /* If we were denied creation of the symlink, try again after
1208 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1209 if (!retval)
1211 TOKEN_PRIVILEGES priv_current;
1213 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1214 &priv_current))
1216 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1217 restore_privilege (&priv_current);
1218 revert_to_self ();
1222 return retval;
1225 static BOOL WINAPI
1226 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1228 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1230 if (is_windows_9x () == TRUE)
1232 errno = ENOTSUP;
1233 return FALSE;
1236 if (g_b_init_is_valid_security_descriptor == 0)
1238 g_b_init_is_valid_security_descriptor = 1;
1239 s_pfn_Is_Valid_Security_Descriptor_Proc =
1240 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1241 "IsValidSecurityDescriptor");
1243 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1245 errno = ENOTSUP;
1246 return FALSE;
1249 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1252 static BOOL WINAPI
1253 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1254 DWORD RequestedStringSDRevision,
1255 SECURITY_INFORMATION SecurityInformation,
1256 LPTSTR *StringSecurityDescriptor,
1257 PULONG StringSecurityDescriptorLen)
1259 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1260 BOOL retval;
1262 if (is_windows_9x () == TRUE)
1264 errno = ENOTSUP;
1265 return FALSE;
1268 if (g_b_init_convert_sd_to_sddl == 0)
1270 g_b_init_convert_sd_to_sddl = 1;
1271 #ifdef _UNICODE
1272 s_pfn_Convert_SD_To_SDDL =
1273 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1274 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1275 #else
1276 s_pfn_Convert_SD_To_SDDL =
1277 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1278 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1279 #endif
1281 if (s_pfn_Convert_SD_To_SDDL == NULL)
1283 errno = ENOTSUP;
1284 return FALSE;
1287 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1288 RequestedStringSDRevision,
1289 SecurityInformation,
1290 StringSecurityDescriptor,
1291 StringSecurityDescriptorLen);
1293 return retval;
1296 static BOOL WINAPI
1297 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1298 DWORD StringSDRevision,
1299 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1300 PULONG SecurityDescriptorSize)
1302 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1303 BOOL retval;
1305 if (is_windows_9x () == TRUE)
1307 errno = ENOTSUP;
1308 return FALSE;
1311 if (g_b_init_convert_sddl_to_sd == 0)
1313 g_b_init_convert_sddl_to_sd = 1;
1314 #ifdef _UNICODE
1315 s_pfn_Convert_SDDL_To_SD =
1316 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1317 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1318 #else
1319 s_pfn_Convert_SDDL_To_SD =
1320 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1321 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1322 #endif
1324 if (s_pfn_Convert_SDDL_To_SD == NULL)
1326 errno = ENOTSUP;
1327 return FALSE;
1330 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1331 StringSDRevision,
1332 SecurityDescriptor,
1333 SecurityDescriptorSize);
1335 return retval;
1338 static DWORD WINAPI
1339 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1341 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1342 HMODULE hm_iphlpapi = NULL;
1344 if (is_windows_9x () == TRUE)
1345 return ERROR_NOT_SUPPORTED;
1347 if (g_b_init_get_adapters_info == 0)
1349 g_b_init_get_adapters_info = 1;
1350 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1351 if (hm_iphlpapi)
1352 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1353 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1355 if (s_pfn_Get_Adapters_Info == NULL)
1356 return ERROR_NOT_SUPPORTED;
1357 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1362 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1363 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1365 This is called from alloc.c:valid_pointer_p. */
1367 w32_valid_pointer_p (void *p, int size)
1369 SIZE_T done;
1370 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1372 if (h)
1374 unsigned char *buf = alloca (size);
1375 int retval = ReadProcessMemory (h, p, buf, size, &done);
1377 CloseHandle (h);
1378 return retval;
1380 else
1381 return -1;
1386 /* Here's an overview of how the Windows build supports file names
1387 that cannot be encoded by the current system codepage.
1389 From the POV of Lisp and layers of C code above the functions here,
1390 Emacs on Windows pretends that its file names are encoded in UTF-8;
1391 see encode_file and decode_file on coding.c. Any file name that is
1392 passed as a unibyte string to C functions defined here is assumed
1393 to be in UTF-8 encoding. Any file name returned by functions
1394 defined here must be in UTF-8 encoding, with only a few exceptions
1395 reserved for a couple of special cases. (Be sure to use
1396 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1397 as they can be much longer than MAX_PATH!)
1399 The UTF-8 encoded file names cannot be passed to system APIs, as
1400 Windows does not support that. Therefore, they are converted
1401 either to UTF-16 or to the ANSI codepage, depending on the value of
1402 w32-unicode-filenames, before calling any system APIs or CRT library
1403 functions. The default value of that variable is determined by the
1404 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1405 user can change that default (although I don't see why would she
1406 want to).
1408 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1409 filename_from_utf16, and filename_from_ansi, are the workhorses of
1410 these conversions. They rely on Windows native APIs
1411 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1412 functions from coding.c here, because they allocate memory, which
1413 is a bad idea on the level of libc, which is what the functions
1414 here emulate. (If you worry about performance due to constant
1415 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1416 it was measured to take only a few microseconds on a not-so-fast
1417 machine, and second, that's exactly what the ANSI APIs we used
1418 before did anyway, because they are just thin wrappers around the
1419 Unicode APIs.)
1421 The variables file-name-coding-system and default-file-name-coding-system
1422 still exist, but are actually used only when a file name needs to
1423 be converted to the ANSI codepage. This happens all the time when
1424 w32-unicode-filenames is nil, but can also happen from time to time
1425 when it is t. Otherwise, these variables have no effect on file-name
1426 encoding when w32-unicode-filenames is t; this is similar to
1427 selection-coding-system.
1429 This arrangement works very well, but it has a few gotchas and
1430 limitations:
1432 . Lisp code that encodes or decodes file names manually should
1433 normally use 'utf-8' as the coding-system on Windows,
1434 disregarding file-name-coding-system. This is a somewhat
1435 unpleasant consequence, but it cannot be avoided. Fortunately,
1436 very few Lisp packages need to do that.
1438 More generally, passing to library functions (e.g., fopen or
1439 opendir) file names already encoded in the ANSI codepage is
1440 explicitly *verboten*, as all those functions, as shadowed and
1441 emulated here, assume they will receive UTF-8 encoded file names.
1443 For the same reasons, no CRT function or Win32 API can be called
1444 directly in Emacs sources, without either converting the file
1445 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1446 some shadowing function defined here.
1448 . Environment variables stored in Vprocess_environment are encoded
1449 in the ANSI codepage, so if getenv/egetenv is used for a variable
1450 whose value is a file name or a list of directories, it needs to
1451 be converted to UTF-8, before it is used as argument to functions
1452 or decoded into a Lisp string.
1454 . File names passed to external libraries, like the image libraries
1455 and GnuTLS, need special handling. These libraries generally
1456 don't support UTF-16 or UTF-8 file names, so they must get file
1457 names encoded in the ANSI codepage. To facilitate using these
1458 libraries with file names that are not encodable in the ANSI
1459 codepage, use the function ansi_encode_filename, which will try
1460 to use the short 8+3 alias of a file name if that file name is
1461 not encodable in the ANSI codepage. See image.c and gnutls.c for
1462 examples of how this should be done.
1464 . Running subprocesses in non-ASCII directories and with non-ASCII
1465 file arguments is limited to the current codepage (even though
1466 Emacs is perfectly capable of finding an executable program file
1467 in a directory whose name cannot be encoded in the current
1468 codepage). This is because the command-line arguments are
1469 encoded _before_ they get to the w32-specific level, and the
1470 encoding is not known in advance (it doesn't have to be the
1471 current ANSI codepage), so w32proc.c functions cannot re-encode
1472 them in UTF-16. This should be fixed, but will also require
1473 changes in cmdproxy. The current limitation is not terribly bad
1474 anyway, since very few, if any, Windows console programs that are
1475 likely to be invoked by Emacs support UTF-16 encoded command
1476 lines.
1478 . For similar reasons, server.el and emacsclient are also limited
1479 to the current ANSI codepage for now.
1481 . Emacs itself can only handle command-line arguments encoded in
1482 the current codepage.
1484 . Turning on w32-unicode-filename on Windows 9X (if it at all
1485 works) requires UNICOWS.DLL, which is thus a requirement even in
1486 non-GUI sessions, something the we previously avoided. */
1490 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1491 codepage defined by file-name-coding-system. */
1493 /* Current codepage for encoding file names. */
1494 static int file_name_codepage;
1496 /* Produce a Windows ANSI codepage suitable for encoding file names.
1497 Return the information about that codepage in CP_INFO. */
1499 codepage_for_filenames (CPINFO *cp_info)
1501 /* A simple cache to avoid calling GetCPInfo every time we need to
1502 encode/decode a file name. The file-name encoding is not
1503 supposed to be changed too frequently, if ever. */
1504 static Lisp_Object last_file_name_encoding;
1505 static CPINFO cp;
1506 Lisp_Object current_encoding;
1508 current_encoding = Vfile_name_coding_system;
1509 if (NILP (current_encoding))
1510 current_encoding = Vdefault_file_name_coding_system;
1512 if (!EQ (last_file_name_encoding, current_encoding))
1514 /* Default to the current ANSI codepage. */
1515 file_name_codepage = w32_ansi_code_page;
1517 if (NILP (current_encoding))
1519 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1520 char *cp = NULL, *end;
1521 int cpnum;
1523 if (strncmp (cpname, "cp", 2) == 0)
1524 cp = cpname + 2;
1525 else if (strncmp (cpname, "windows-", 8) == 0)
1526 cp = cpname + 8;
1528 if (cp)
1530 end = cp;
1531 cpnum = strtol (cp, &end, 10);
1532 if (cpnum && *end == '\0' && end - cp >= 2)
1533 file_name_codepage = cpnum;
1537 if (!file_name_codepage)
1538 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1540 if (!GetCPInfo (file_name_codepage, &cp))
1542 file_name_codepage = CP_ACP;
1543 if (!GetCPInfo (file_name_codepage, &cp))
1544 emacs_abort ();
1547 if (cp_info)
1548 *cp_info = cp;
1550 return file_name_codepage;
1554 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1556 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1557 -1, fn_out, MAX_PATH);
1559 if (!result)
1561 DWORD err = GetLastError ();
1563 switch (err)
1565 case ERROR_INVALID_FLAGS:
1566 case ERROR_INVALID_PARAMETER:
1567 errno = EINVAL;
1568 break;
1569 case ERROR_INSUFFICIENT_BUFFER:
1570 case ERROR_NO_UNICODE_TRANSLATION:
1571 default:
1572 errno = ENOENT;
1573 break;
1575 return -1;
1577 return 0;
1581 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1583 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1584 fn_out, MAX_UTF8_PATH, NULL, NULL);
1586 if (!result)
1588 DWORD err = GetLastError ();
1590 switch (err)
1592 case ERROR_INVALID_FLAGS:
1593 case ERROR_INVALID_PARAMETER:
1594 errno = EINVAL;
1595 break;
1596 case ERROR_INSUFFICIENT_BUFFER:
1597 case ERROR_NO_UNICODE_TRANSLATION:
1598 default:
1599 errno = ENOENT;
1600 break;
1602 return -1;
1604 return 0;
1608 filename_to_ansi (const char *fn_in, char *fn_out)
1610 wchar_t fn_utf16[MAX_PATH];
1612 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1614 int result;
1615 int codepage = codepage_for_filenames (NULL);
1617 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1618 fn_out, MAX_PATH, NULL, NULL);
1619 if (!result)
1621 DWORD err = GetLastError ();
1623 switch (err)
1625 case ERROR_INVALID_FLAGS:
1626 case ERROR_INVALID_PARAMETER:
1627 errno = EINVAL;
1628 break;
1629 case ERROR_INSUFFICIENT_BUFFER:
1630 case ERROR_NO_UNICODE_TRANSLATION:
1631 default:
1632 errno = ENOENT;
1633 break;
1635 return -1;
1637 return 0;
1639 return -1;
1643 filename_from_ansi (const char *fn_in, char *fn_out)
1645 wchar_t fn_utf16[MAX_PATH];
1646 int codepage = codepage_for_filenames (NULL);
1647 int result = pMultiByteToWideChar (codepage, multiByteToWideCharFlags, fn_in,
1648 -1, fn_utf16, MAX_PATH);
1650 if (!result)
1652 DWORD err = GetLastError ();
1654 switch (err)
1656 case ERROR_INVALID_FLAGS:
1657 case ERROR_INVALID_PARAMETER:
1658 errno = EINVAL;
1659 break;
1660 case ERROR_INSUFFICIENT_BUFFER:
1661 case ERROR_NO_UNICODE_TRANSLATION:
1662 default:
1663 errno = ENOENT;
1664 break;
1666 return -1;
1668 return filename_from_utf16 (fn_utf16, fn_out);
1673 /* The directory where we started, in UTF-8. */
1674 static char startup_dir[MAX_UTF8_PATH];
1676 /* Get the current working directory. */
1677 char *
1678 getcwd (char *dir, int dirsize)
1680 if (!dirsize)
1682 errno = EINVAL;
1683 return NULL;
1685 if (dirsize <= strlen (startup_dir))
1687 errno = ERANGE;
1688 return NULL;
1690 #if 0
1691 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1692 return dir;
1693 return NULL;
1694 #else
1695 /* Emacs doesn't actually change directory itself, it stays in the
1696 same directory where it was started. */
1697 strcpy (dir, startup_dir);
1698 return dir;
1699 #endif
1702 /* Emulate getloadavg. */
1704 struct load_sample {
1705 time_t sample_time;
1706 ULONGLONG idle;
1707 ULONGLONG kernel;
1708 ULONGLONG user;
1711 /* Number of processors on this machine. */
1712 static unsigned num_of_processors;
1714 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1715 static struct load_sample samples[16*60];
1716 static int first_idx = -1, last_idx = -1;
1717 static int max_idx = ARRAYELTS (samples);
1719 static int
1720 buf_next (int from)
1722 int next_idx = from + 1;
1724 if (next_idx >= max_idx)
1725 next_idx = 0;
1727 return next_idx;
1730 static int
1731 buf_prev (int from)
1733 int prev_idx = from - 1;
1735 if (prev_idx < 0)
1736 prev_idx = max_idx - 1;
1738 return prev_idx;
1741 static void
1742 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1744 SYSTEM_INFO sysinfo;
1745 FILETIME ft_idle, ft_user, ft_kernel;
1747 /* Initialize the number of processors on this machine. */
1748 if (num_of_processors <= 0)
1750 get_native_system_info (&sysinfo);
1751 num_of_processors = sysinfo.dwNumberOfProcessors;
1752 if (num_of_processors <= 0)
1754 GetSystemInfo (&sysinfo);
1755 num_of_processors = sysinfo.dwNumberOfProcessors;
1757 if (num_of_processors <= 0)
1758 num_of_processors = 1;
1761 /* TODO: Take into account threads that are ready to run, by
1762 sampling the "\System\Processor Queue Length" performance
1763 counter. The code below accounts only for threads that are
1764 actually running. */
1766 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1768 ULARGE_INTEGER uidle, ukernel, uuser;
1770 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1771 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1772 memcpy (&uuser, &ft_user, sizeof (ft_user));
1773 *idle = uidle.QuadPart;
1774 *kernel = ukernel.QuadPart;
1775 *user = uuser.QuadPart;
1777 else
1779 *idle = 0;
1780 *kernel = 0;
1781 *user = 0;
1785 /* Produce the load average for a given time interval, using the
1786 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1787 1-minute, 5-minute, or 15-minute average, respectively. */
1788 static double
1789 getavg (int which)
1791 double retval = -1.0;
1792 double tdiff;
1793 int idx;
1794 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1795 time_t now = samples[last_idx].sample_time;
1797 if (first_idx != last_idx)
1799 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1801 tdiff = difftime (now, samples[idx].sample_time);
1802 if (tdiff >= span - 2*DBL_EPSILON*now)
1804 long double sys =
1805 samples[last_idx].kernel + samples[last_idx].user
1806 - (samples[idx].kernel + samples[idx].user);
1807 long double idl = samples[last_idx].idle - samples[idx].idle;
1809 retval = (1.0 - idl / sys) * num_of_processors;
1810 break;
1812 if (idx == first_idx)
1813 break;
1817 return retval;
1821 getloadavg (double loadavg[], int nelem)
1823 int elem;
1824 ULONGLONG idle, kernel, user;
1825 time_t now = time (NULL);
1827 /* If system time jumped back for some reason, delete all samples
1828 whose time is later than the current wall-clock time. This
1829 prevents load average figures from becoming frozen for prolonged
1830 periods of time, when system time is reset backwards. */
1831 if (last_idx >= 0)
1833 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1835 if (last_idx == first_idx)
1837 first_idx = last_idx = -1;
1838 break;
1840 last_idx = buf_prev (last_idx);
1844 /* Store another sample. We ignore samples that are less than 1 sec
1845 apart. */
1846 if (last_idx < 0
1847 || (difftime (now, samples[last_idx].sample_time)
1848 >= 1.0 - 2*DBL_EPSILON*now))
1850 sample_system_load (&idle, &kernel, &user);
1851 last_idx = buf_next (last_idx);
1852 samples[last_idx].sample_time = now;
1853 samples[last_idx].idle = idle;
1854 samples[last_idx].kernel = kernel;
1855 samples[last_idx].user = user;
1856 /* If the buffer has more that 15 min worth of samples, discard
1857 the old ones. */
1858 if (first_idx == -1)
1859 first_idx = last_idx;
1860 while (first_idx != last_idx
1861 && (difftime (now, samples[first_idx].sample_time)
1862 >= 15.0*60 + 2*DBL_EPSILON*now))
1863 first_idx = buf_next (first_idx);
1866 for (elem = 0; elem < nelem; elem++)
1868 double avg = getavg (elem);
1870 if (avg < 0)
1871 break;
1872 loadavg[elem] = avg;
1875 return elem;
1878 /* Emulate getpwuid, getpwnam and others. */
1880 #define PASSWD_FIELD_SIZE 256
1882 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1883 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1884 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1885 static char dflt_passwd_dir[MAX_UTF8_PATH];
1886 static char dflt_passwd_shell[MAX_UTF8_PATH];
1888 static struct passwd dflt_passwd =
1890 dflt_passwd_name,
1891 dflt_passwd_passwd,
1895 dflt_passwd_gecos,
1896 dflt_passwd_dir,
1897 dflt_passwd_shell,
1900 static char dflt_group_name[GNLEN+1];
1902 static struct group dflt_group =
1904 /* When group information is not available, we return this as the
1905 group for all files. */
1906 dflt_group_name,
1910 unsigned
1911 getuid (void)
1913 return dflt_passwd.pw_uid;
1916 unsigned
1917 geteuid (void)
1919 /* I could imagine arguing for checking to see whether the user is
1920 in the Administrators group and returning a UID of 0 for that
1921 case, but I don't know how wise that would be in the long run. */
1922 return getuid ();
1925 unsigned
1926 getgid (void)
1928 return dflt_passwd.pw_gid;
1931 unsigned
1932 getegid (void)
1934 return getgid ();
1937 struct passwd *
1938 getpwuid (unsigned uid)
1940 if (uid == dflt_passwd.pw_uid)
1941 return &dflt_passwd;
1942 return NULL;
1945 struct group *
1946 getgrgid (gid_t gid)
1948 return &dflt_group;
1951 struct passwd *
1952 getpwnam (char *name)
1954 struct passwd *pw;
1956 pw = getpwuid (getuid ());
1957 if (!pw)
1958 return pw;
1960 if (xstrcasecmp (name, pw->pw_name))
1961 return NULL;
1963 return pw;
1966 static void
1967 init_user_info (void)
1969 /* Find the user's real name by opening the process token and
1970 looking up the name associated with the user-sid in that token.
1972 Use the relative portion of the identifier authority value from
1973 the user-sid as the user id value (same for group id using the
1974 primary group sid from the process token). */
1976 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1977 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1978 DWORD glength = sizeof (gname);
1979 HANDLE token = NULL;
1980 SID_NAME_USE user_type;
1981 unsigned char *buf = NULL;
1982 DWORD blen = 0;
1983 TOKEN_USER user_token;
1984 TOKEN_PRIMARY_GROUP group_token;
1985 BOOL result;
1987 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1988 if (result)
1990 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1991 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1993 buf = xmalloc (blen);
1994 result = get_token_information (token, TokenUser,
1995 (LPVOID)buf, blen, &needed);
1996 if (result)
1998 memcpy (&user_token, buf, sizeof (user_token));
1999 result = lookup_account_sid (NULL, user_token.User.Sid,
2000 uname, &ulength,
2001 domain, &dlength, &user_type);
2004 else
2005 result = FALSE;
2007 if (result)
2009 strcpy (dflt_passwd.pw_name, uname);
2010 /* Determine a reasonable uid value. */
2011 if (xstrcasecmp ("administrator", uname) == 0)
2013 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2014 dflt_passwd.pw_gid = 513; /* well-known None gid */
2016 else
2018 /* Use the last sub-authority value of the RID, the relative
2019 portion of the SID, as user/group ID. */
2020 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2022 /* Get group id and name. */
2023 result = get_token_information (token, TokenPrimaryGroup,
2024 (LPVOID)buf, blen, &needed);
2025 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2027 buf = xrealloc (buf, blen = needed);
2028 result = get_token_information (token, TokenPrimaryGroup,
2029 (LPVOID)buf, blen, &needed);
2031 if (result)
2033 memcpy (&group_token, buf, sizeof (group_token));
2034 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2035 dlength = sizeof (domain);
2036 /* If we can get at the real Primary Group name, use that.
2037 Otherwise, the default group name was already set to
2038 "None" in globals_of_w32. */
2039 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2040 gname, &glength, NULL, &dlength,
2041 &user_type))
2042 strcpy (dflt_group_name, gname);
2044 else
2045 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2048 /* If security calls are not supported (presumably because we
2049 are running under Windows 9X), fallback to this: */
2050 else if (GetUserName (uname, &ulength))
2052 strcpy (dflt_passwd.pw_name, uname);
2053 if (xstrcasecmp ("administrator", uname) == 0)
2054 dflt_passwd.pw_uid = 0;
2055 else
2056 dflt_passwd.pw_uid = 123;
2057 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2059 else
2061 strcpy (dflt_passwd.pw_name, "unknown");
2062 dflt_passwd.pw_uid = 123;
2063 dflt_passwd.pw_gid = 123;
2065 dflt_group.gr_gid = dflt_passwd.pw_gid;
2067 /* Set dir and shell from environment variables. */
2068 if (w32_unicode_filenames)
2070 wchar_t *home = _wgetenv (L"HOME");
2071 wchar_t *shell = _wgetenv (L"SHELL");
2073 /* Ensure HOME and SHELL are defined. */
2074 if (home == NULL)
2075 emacs_abort ();
2076 if (shell == NULL)
2077 emacs_abort ();
2078 filename_from_utf16 (home, dflt_passwd.pw_dir);
2079 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2081 else
2083 char *home = getenv ("HOME");
2084 char *shell = getenv ("SHELL");
2086 if (home == NULL)
2087 emacs_abort ();
2088 if (shell == NULL)
2089 emacs_abort ();
2090 filename_from_ansi (home, dflt_passwd.pw_dir);
2091 filename_from_ansi (shell, dflt_passwd.pw_shell);
2094 xfree (buf);
2095 if (token)
2096 CloseHandle (token);
2099 static HCRYPTPROV w32_crypto_hprov;
2100 static int
2101 w32_init_crypt_random (void)
2103 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2104 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2106 DebPrint (("CryptAcquireContext failed with error %x\n",
2107 GetLastError ()));
2108 w32_crypto_hprov = 0;
2109 return -1;
2111 return 0;
2115 w32_init_random (void *buf, ptrdiff_t buflen)
2117 if (!w32_crypto_hprov)
2118 w32_init_crypt_random ();
2119 if (w32_crypto_hprov)
2121 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2122 return 0;
2124 return -1;
2128 random (void)
2130 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2131 return ((rand () << 15) | rand ());
2134 void
2135 srandom (int seed)
2137 srand (seed);
2140 /* Return the maximum length in bytes of a multibyte character
2141 sequence encoded in the current ANSI codepage. This is required to
2142 correctly walk the encoded file names one character at a time. */
2143 static int
2144 max_filename_mbslen (void)
2146 CPINFO cp_info;
2148 codepage_for_filenames (&cp_info);
2149 return cp_info.MaxCharSize;
2152 /* Normalize filename by converting in-place all of its path
2153 separators to the separator specified by PATH_SEP. */
2155 static void
2156 normalize_filename (register char *fp, char path_sep)
2158 char *p2;
2160 /* Always lower-case drive letters a-z, even if the filesystem
2161 preserves case in filenames.
2162 This is so filenames can be compared by string comparison
2163 functions that are case-sensitive. Even case-preserving filesystems
2164 do not distinguish case in drive letters. */
2165 p2 = fp + 1;
2167 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2169 *fp += 'a' - 'A';
2170 fp += 2;
2173 while (*fp)
2175 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2176 *fp = path_sep;
2177 fp++;
2181 /* Destructively turn backslashes into slashes. */
2182 void
2183 dostounix_filename (register char *p)
2185 normalize_filename (p, '/');
2188 /* Destructively turn slashes into backslashes. */
2189 void
2190 unixtodos_filename (register char *p)
2192 normalize_filename (p, '\\');
2195 /* Remove all CR's that are followed by a LF.
2196 (From msdos.c...probably should figure out a way to share it,
2197 although this code isn't going to ever change.) */
2198 static int
2199 crlf_to_lf (register int n, register char *buf)
2201 unsigned char *np = (unsigned char *)buf;
2202 unsigned char *startp = np;
2203 char *endp = buf + n;
2205 if (n == 0)
2206 return n;
2207 while (buf < endp - 1)
2209 if (*buf == 0x0d)
2211 if (*(++buf) != 0x0a)
2212 *np++ = 0x0d;
2214 else
2215 *np++ = *buf++;
2217 if (buf < endp)
2218 *np++ = *buf++;
2219 return np - startp;
2222 /* Parse the root part of file name, if present. Return length and
2223 optionally store pointer to char after root. */
2224 static int
2225 parse_root (const char * name, const char ** pPath)
2227 const char * start = name;
2229 if (name == NULL)
2230 return 0;
2232 /* find the root name of the volume if given */
2233 if (isalpha (name[0]) && name[1] == ':')
2235 /* skip past drive specifier */
2236 name += 2;
2237 if (IS_DIRECTORY_SEP (name[0]))
2238 name++;
2240 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2242 int slashes = 2;
2244 name += 2;
2247 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2248 break;
2249 name++;
2251 while ( *name );
2252 if (IS_DIRECTORY_SEP (name[0]))
2253 name++;
2256 if (pPath)
2257 *pPath = name;
2259 return name - start;
2262 /* Get long base name for name; name is assumed to be absolute. */
2263 static int
2264 get_long_basename (char * name, char * buf, int size)
2266 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2267 char fname_utf8[MAX_UTF8_PATH];
2268 int len = 0;
2269 int cstatus = -1;
2271 /* Must be valid filename, no wild cards or other invalid characters. */
2272 if (strpbrk (name, "*?|<>\""))
2273 return 0;
2275 if (w32_unicode_filenames)
2277 wchar_t fname_utf16[MAX_PATH];
2278 WIN32_FIND_DATAW find_data_wide;
2280 filename_to_utf16 (name, fname_utf16);
2281 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2282 if (dir_handle != INVALID_HANDLE_VALUE)
2283 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2285 else
2287 char fname_ansi[MAX_PATH];
2288 WIN32_FIND_DATAA find_data_ansi;
2290 filename_to_ansi (name, fname_ansi);
2291 /* If the ANSI name includes ? characters, it is not encodable
2292 in the ANSI codepage. In that case, we deliver the question
2293 marks to the caller; calling FindFirstFileA in this case
2294 could return some unrelated file name in the same
2295 directory. */
2296 if (_mbspbrk (fname_ansi, "?"))
2298 /* Find the basename of fname_ansi. */
2299 char *p = strrchr (fname_ansi, '\\');
2301 if (!p)
2302 p = fname_ansi;
2303 else
2304 p++;
2305 cstatus = filename_from_ansi (p, fname_utf8);
2307 else
2309 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2310 if (dir_handle != INVALID_HANDLE_VALUE)
2311 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2315 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2316 memcpy (buf, fname_utf8, len + 1);
2317 else
2318 len = 0;
2320 if (dir_handle != INVALID_HANDLE_VALUE)
2321 FindClose (dir_handle);
2323 return len;
2326 /* Get long name for file, if possible (assumed to be absolute). */
2327 BOOL
2328 w32_get_long_filename (const char * name, char * buf, int size)
2330 char * o = buf;
2331 char * p;
2332 const char * q;
2333 char full[ MAX_UTF8_PATH ];
2334 int len;
2336 len = strlen (name);
2337 if (len >= MAX_UTF8_PATH)
2338 return FALSE;
2340 /* Use local copy for destructive modification. */
2341 memcpy (full, name, len+1);
2342 unixtodos_filename (full);
2344 /* Copy root part verbatim. */
2345 len = parse_root (full, (const char **)&p);
2346 memcpy (o, full, len);
2347 o += len;
2348 *o = '\0';
2349 size -= len;
2351 while (p != NULL && *p)
2353 q = p;
2354 p = strchr (q, '\\');
2355 if (p) *p = '\0';
2356 len = get_long_basename (full, o, size);
2357 if (len > 0)
2359 o += len;
2360 size -= len;
2361 if (p != NULL)
2363 *p++ = '\\';
2364 if (size < 2)
2365 return FALSE;
2366 *o++ = '\\';
2367 size--;
2368 *o = '\0';
2371 else
2372 return FALSE;
2375 return TRUE;
2378 unsigned int
2379 w32_get_short_filename (const char * name, char * buf, int size)
2381 if (w32_unicode_filenames)
2383 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2384 unsigned int retval;
2386 filename_to_utf16 (name, name_utf16);
2387 retval = GetShortPathNameW (name_utf16, short_name, size);
2388 if (retval && retval < size)
2389 filename_from_utf16 (short_name, buf);
2390 return retval;
2392 else
2394 char name_ansi[MAX_PATH];
2396 filename_to_ansi (name, name_ansi);
2397 return GetShortPathNameA (name_ansi, buf, size);
2401 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2402 MS-Windows ANSI codepage. If FILENAME includes characters not
2403 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2404 if it exists. This is needed because the w32 build wants to
2405 support file names outside of the system locale, but image
2406 libraries typically don't support wide (a.k.a. "Unicode") APIs
2407 required for that. */
2409 Lisp_Object
2410 ansi_encode_filename (Lisp_Object filename)
2412 Lisp_Object encoded_filename;
2413 char fname[MAX_PATH];
2415 filename_to_ansi (SSDATA (filename), fname);
2416 if (_mbspbrk (fname, "?"))
2418 char shortname[MAX_PATH];
2420 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2422 dostounix_filename (shortname);
2423 encoded_filename = build_string (shortname);
2425 else
2426 encoded_filename = build_unibyte_string (fname);
2428 else
2429 encoded_filename = build_unibyte_string (fname);
2430 return encoded_filename;
2433 static int
2434 is_unc_volume (const char *filename)
2436 const char *ptr = filename;
2438 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2439 return 0;
2441 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2442 return 0;
2444 return 1;
2447 /* Emulate the Posix unsetenv. */
2449 unsetenv (const char *name)
2451 char *var;
2452 size_t name_len;
2454 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2456 errno = EINVAL;
2457 return -1;
2459 name_len = strlen (name);
2460 /* MS docs says an environment variable cannot be longer than 32K. */
2461 if (name_len > 32767)
2463 errno = ENOMEM;
2464 return 0;
2466 /* It is safe to use 'alloca' with 32K size, since the stack is at
2467 least 2MB, and we set it to 8MB in the link command line. */
2468 var = alloca (name_len + 2);
2469 strncpy (var, name, name_len);
2470 var[name_len++] = '=';
2471 var[name_len] = '\0';
2472 return _putenv (var);
2475 /* MS _putenv doesn't support removing a variable when the argument
2476 does not include the '=' character, so we fix that here. */
2478 sys_putenv (char *str)
2480 const char *const name_end = strchr (str, '=');
2482 if (name_end == NULL)
2484 /* Remove the variable from the environment. */
2485 return unsetenv (str);
2488 return _putenv (str);
2491 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2493 LPBYTE
2494 w32_get_resource (char *key, LPDWORD lpdwtype)
2496 LPBYTE lpvalue;
2497 HKEY hrootkey = NULL;
2498 DWORD cbData;
2500 /* Check both the current user and the local machine to see if
2501 we have any resources. */
2503 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2505 lpvalue = NULL;
2507 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2508 && (lpvalue = xmalloc (cbData)) != NULL
2509 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2511 RegCloseKey (hrootkey);
2512 return (lpvalue);
2515 xfree (lpvalue);
2517 RegCloseKey (hrootkey);
2520 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2522 lpvalue = NULL;
2524 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2525 && (lpvalue = xmalloc (cbData)) != NULL
2526 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2528 RegCloseKey (hrootkey);
2529 return (lpvalue);
2532 xfree (lpvalue);
2534 RegCloseKey (hrootkey);
2537 return (NULL);
2540 /* The argv[] array holds ANSI-encoded strings, and so this function
2541 works with ANS_encoded strings. */
2542 void
2543 init_environment (char ** argv)
2545 static const char * const tempdirs[] = {
2546 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2549 int i;
2551 const int imax = ARRAYELTS (tempdirs);
2553 /* Implementation note: This function explicitly works with ANSI
2554 file names, not with UTF-8 encoded file names. This is because
2555 this function pushes variables into the Emacs's environment, and
2556 the environment variables are always assumed to be in the
2557 locale-specific encoding. Do NOT call any functions that accept
2558 UTF-8 file names from this function! */
2560 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2561 temporary files and assume "/tmp" if $TMPDIR is unset, which
2562 will break on DOS/Windows. Refuse to work if we cannot find
2563 a directory, not even "c:/", usable for that purpose. */
2564 for (i = 0; i < imax ; i++)
2566 const char *tmp = tempdirs[i];
2568 if (*tmp == '$')
2569 tmp = getenv (tmp + 1);
2570 /* Note that `access' can lie to us if the directory resides on a
2571 read-only filesystem, like CD-ROM or a write-protected floppy.
2572 The only way to be really sure is to actually create a file and
2573 see if it succeeds. But I think that's too much to ask. */
2575 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2576 if (tmp && sys_access (tmp, D_OK) == 0)
2578 char * var = alloca (strlen (tmp) + 8);
2579 sprintf (var, "TMPDIR=%s", tmp);
2580 _putenv (strdup (var));
2581 break;
2584 if (i >= imax)
2585 cmd_error_internal
2586 (Fcons (Qerror,
2587 Fcons (build_string ("no usable temporary directories found!!"),
2588 Qnil)),
2589 "While setting TMPDIR: ");
2591 /* Check for environment variables and use registry settings if they
2592 don't exist. Fallback on default values where applicable. */
2594 int i;
2595 LPBYTE lpval;
2596 DWORD dwType;
2597 char locale_name[32];
2598 char default_home[MAX_PATH];
2599 int appdata = 0;
2601 static const struct env_entry
2603 char * name;
2604 char * def_value;
2605 } dflt_envvars[] =
2607 /* If the default value is NULL, we will use the value from the
2608 outside environment or the Registry, but will not push the
2609 variable into the Emacs environment if it is defined neither
2610 in the Registry nor in the outside environment. */
2611 {"HOME", "C:/"},
2612 {"PRELOAD_WINSOCK", NULL},
2613 {"emacs_dir", "C:/emacs"},
2614 {"EMACSLOADPATH", NULL},
2615 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2616 {"EMACSDATA", NULL},
2617 {"EMACSPATH", NULL},
2618 {"INFOPATH", NULL},
2619 {"EMACSDOC", NULL},
2620 {"TERM", "cmd"},
2621 {"LANG", NULL},
2624 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2626 /* We need to copy dflt_envvars[] and work on the copy because we
2627 don't want the dumped Emacs to inherit the values of
2628 environment variables we saw during dumping (which could be on
2629 a different system). The defaults above must be left intact. */
2630 struct env_entry env_vars[N_ENV_VARS];
2632 for (i = 0; i < N_ENV_VARS; i++)
2633 env_vars[i] = dflt_envvars[i];
2635 /* For backwards compatibility, check if a .emacs file exists in C:/
2636 If not, then we can try to default to the appdata directory under the
2637 user's profile, which is more likely to be writable. */
2638 if (sys_access ("C:/.emacs", F_OK) != 0)
2640 HRESULT profile_result;
2641 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2642 of Windows 95 and NT4 that have not been updated to include
2643 MSIE 5. */
2644 ShGetFolderPath_fn get_folder_path;
2645 get_folder_path = (ShGetFolderPath_fn)
2646 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2648 if (get_folder_path != NULL)
2650 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2651 0, default_home);
2653 /* If we can't get the appdata dir, revert to old behavior. */
2654 if (profile_result == S_OK)
2656 env_vars[0].def_value = default_home;
2657 appdata = 1;
2662 /* Get default locale info and use it for LANG. */
2663 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2664 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2665 locale_name, sizeof (locale_name)))
2667 for (i = 0; i < N_ENV_VARS; i++)
2669 if (strcmp (env_vars[i].name, "LANG") == 0)
2671 env_vars[i].def_value = locale_name;
2672 break;
2677 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2679 /* Treat emacs_dir specially: set it unconditionally based on our
2680 location. */
2682 char *p;
2683 char modname[MAX_PATH];
2685 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2686 emacs_abort ();
2687 if ((p = _mbsrchr (modname, '\\')) == NULL)
2688 emacs_abort ();
2689 *p = 0;
2691 if ((p = _mbsrchr (modname, '\\'))
2692 /* From bin means installed Emacs, from src means uninstalled. */
2693 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2695 char buf[SET_ENV_BUF_SIZE];
2696 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2698 *p = 0;
2699 for (p = modname; *p; p = CharNext (p))
2700 if (*p == '\\') *p = '/';
2702 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2703 _putenv (strdup (buf));
2704 /* If we are running from the Posix-like build tree, define
2705 SHELL to point to our own cmdproxy. The loop below will
2706 then disregard PATH_EXEC and the default value. */
2707 if (within_build_tree)
2709 _snprintf (buf, sizeof (buf) - 1,
2710 "SHELL=%s/nt/cmdproxy.exe", modname);
2711 _putenv (strdup (buf));
2716 for (i = 0; i < N_ENV_VARS; i++)
2718 if (!getenv (env_vars[i].name))
2720 int dont_free = 0;
2721 char bufc[SET_ENV_BUF_SIZE];
2723 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2724 /* Also ignore empty environment variables. */
2725 || *lpval == 0)
2727 xfree (lpval);
2728 dont_free = 1;
2729 if (strcmp (env_vars[i].name, "SHELL") == 0)
2731 /* Look for cmdproxy.exe in every directory in
2732 PATH_EXEC. FIXME: This does not find cmdproxy
2733 in nt/ when we run uninstalled. */
2734 char fname[MAX_PATH];
2735 const char *pstart = PATH_EXEC, *pend;
2737 do {
2738 pend = _mbschr (pstart, ';');
2739 if (!pend)
2740 pend = pstart + strlen (pstart);
2741 /* Be defensive against series of ;;; characters. */
2742 if (pend > pstart)
2744 strncpy (fname, pstart, pend - pstart);
2745 fname[pend - pstart] = '/';
2746 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2747 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2748 sizeof (bufc));
2749 if (sys_access (bufc, F_OK) == 0)
2751 lpval = bufc;
2752 dwType = REG_SZ;
2753 break;
2756 if (*pend)
2757 pstart = pend + 1;
2758 else
2759 pstart = pend;
2760 if (!*pstart)
2762 /* If not found in any directory, use the
2763 default as the last resort. */
2764 lpval = env_vars[i].def_value;
2765 dwType = REG_EXPAND_SZ;
2767 } while (*pstart);
2769 else
2771 lpval = env_vars[i].def_value;
2772 dwType = REG_EXPAND_SZ;
2774 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2775 Vdelayed_warnings_list
2776 = Fcons (listn (CONSTYPE_HEAP, 2,
2777 intern ("initialization"),
2778 build_string ("Setting HOME to C:\\ by default is deprecated")),
2779 Vdelayed_warnings_list);
2782 if (lpval)
2784 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2786 if (dwType == REG_EXPAND_SZ)
2787 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2788 else if (dwType == REG_SZ)
2789 strcpy (buf1, lpval);
2790 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2792 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2793 buf1);
2794 _putenv (strdup (buf2));
2797 if (!dont_free)
2798 xfree (lpval);
2804 /* Rebuild system configuration to reflect invoking system. */
2805 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2807 /* Another special case: on NT, the PATH variable is actually named
2808 "Path" although cmd.exe (perhaps NT itself) arranges for
2809 environment variable lookup and setting to be case insensitive.
2810 However, Emacs assumes a fully case sensitive environment, so we
2811 need to change "Path" to "PATH" to match the expectations of
2812 various elisp packages. We do this by the sneaky method of
2813 modifying the string in the C runtime environ entry.
2815 The same applies to COMSPEC. */
2817 char ** envp;
2819 for (envp = environ; *envp; envp++)
2820 if (_strnicmp (*envp, "PATH=", 5) == 0)
2821 memcpy (*envp, "PATH=", 5);
2822 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2823 memcpy (*envp, "COMSPEC=", 8);
2826 /* Remember the initial working directory for getcwd. */
2827 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2828 Does it matter anywhere in Emacs? */
2829 if (w32_unicode_filenames)
2831 wchar_t wstartup_dir[MAX_PATH];
2833 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2834 emacs_abort ();
2835 filename_from_utf16 (wstartup_dir, startup_dir);
2837 else
2839 char astartup_dir[MAX_PATH];
2841 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2842 emacs_abort ();
2843 filename_from_ansi (astartup_dir, startup_dir);
2847 static char modname[MAX_PATH];
2849 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2850 emacs_abort ();
2851 argv[0] = modname;
2854 /* Determine if there is a middle mouse button, to allow parse_button
2855 to decide whether right mouse events should be mouse-2 or
2856 mouse-3. */
2857 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2859 init_user_info ();
2862 /* Called from expand-file-name when default-directory is not a string. */
2864 char *
2865 emacs_root_dir (void)
2867 static char root_dir[MAX_UTF8_PATH];
2868 const char *p;
2870 p = getenv ("emacs_dir");
2871 if (p == NULL)
2872 emacs_abort ();
2873 filename_from_ansi (p, root_dir);
2874 root_dir[parse_root (root_dir, NULL)] = '\0';
2875 dostounix_filename (root_dir);
2876 return root_dir;
2879 #include <sys/timeb.h>
2881 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2883 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2885 struct _timeb tb;
2886 _ftime (&tb);
2888 tv->tv_sec = tb.time;
2889 tv->tv_usec = tb.millitm * 1000L;
2890 /* Implementation note: _ftime sometimes doesn't update the dstflag
2891 according to the new timezone when the system timezone is
2892 changed. We could fix that by using GetSystemTime and
2893 GetTimeZoneInformation, but that doesn't seem necessary, since
2894 Emacs always calls gettimeofday with the 2nd argument NULL (see
2895 current_emacs_time). */
2896 if (tz)
2898 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2899 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2901 return 0;
2904 /* Emulate fdutimens. */
2906 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2907 TIMESPEC[0] and TIMESPEC[1], respectively.
2908 FD must be either negative -- in which case it is ignored --
2909 or a file descriptor that is open on FILE.
2910 If FD is nonnegative, then FILE can be NULL, which means
2911 use just futimes instead of utimes.
2912 If TIMESPEC is null, FAIL.
2913 Return 0 on success, -1 (setting errno) on failure. */
2916 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2918 if (!timespec)
2920 errno = ENOSYS;
2921 return -1;
2923 if (fd < 0 && !file)
2925 errno = EBADF;
2926 return -1;
2928 /* _futime's prototype defines 2nd arg as having the type 'struct
2929 _utimbuf', while utime needs to accept 'struct utimbuf' for
2930 compatibility with Posix. So we need to use 2 different (but
2931 equivalent) types to avoid compiler warnings, sigh. */
2932 if (fd >= 0)
2934 struct _utimbuf _ut;
2936 _ut.actime = timespec[0].tv_sec;
2937 _ut.modtime = timespec[1].tv_sec;
2938 return _futime (fd, &_ut);
2940 else
2942 struct utimbuf ut;
2944 ut.actime = timespec[0].tv_sec;
2945 ut.modtime = timespec[1].tv_sec;
2946 /* Call 'utime', which is implemented below, not the MS library
2947 function, which fails on directories. */
2948 return utime (file, &ut);
2953 /* ------------------------------------------------------------------------- */
2954 /* IO support and wrapper functions for the Windows API. */
2955 /* ------------------------------------------------------------------------- */
2957 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2958 on network directories, so we handle that case here.
2959 (Ulrich Leodolter, 1/11/95). */
2960 char *
2961 sys_ctime (const time_t *t)
2963 char *str = (char *) ctime (t);
2964 return (str ? str : "Sun Jan 01 00:00:00 1970");
2967 /* Emulate sleep...we could have done this with a define, but that
2968 would necessitate including windows.h in the files that used it.
2969 This is much easier. */
2970 void
2971 sys_sleep (int seconds)
2973 Sleep (seconds * 1000);
2976 /* Internal MSVC functions for low-level descriptor munging */
2977 extern int __cdecl _set_osfhnd (int fd, long h);
2978 extern int __cdecl _free_osfhnd (int fd);
2980 /* parallel array of private info on file handles */
2981 filedesc fd_info [ MAXDESC ];
2983 typedef struct volume_info_data {
2984 struct volume_info_data * next;
2986 /* time when info was obtained */
2987 DWORD timestamp;
2989 /* actual volume info */
2990 char * root_dir;
2991 DWORD serialnum;
2992 DWORD maxcomp;
2993 DWORD flags;
2994 char * name;
2995 char * type;
2996 } volume_info_data;
2998 /* Global referenced by various functions. */
2999 static volume_info_data volume_info;
3001 /* Vector to indicate which drives are local and fixed (for which cached
3002 data never expires). */
3003 static BOOL fixed_drives[26];
3005 /* Consider cached volume information to be stale if older than 10s,
3006 at least for non-local drives. Info for fixed drives is never stale. */
3007 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3008 #define VOLINFO_STILL_VALID( root_dir, info ) \
3009 ( ( isalpha (root_dir[0]) && \
3010 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3011 || GetTickCount () - info->timestamp < 10000 )
3013 /* Cache support functions. */
3015 /* Simple linked list with linear search is sufficient. */
3016 static volume_info_data *volume_cache = NULL;
3018 static volume_info_data *
3019 lookup_volume_info (char * root_dir)
3021 volume_info_data * info;
3023 for (info = volume_cache; info; info = info->next)
3024 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3025 break;
3026 return info;
3029 static void
3030 add_volume_info (char * root_dir, volume_info_data * info)
3032 info->root_dir = xstrdup (root_dir);
3033 unixtodos_filename (info->root_dir);
3034 info->next = volume_cache;
3035 volume_cache = info;
3039 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3040 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3041 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3042 static volume_info_data *
3043 GetCachedVolumeInformation (char * root_dir)
3045 volume_info_data * info;
3046 char default_root[ MAX_UTF8_PATH ];
3047 char name[MAX_PATH+1];
3048 char type[MAX_PATH+1];
3050 /* NULL for root_dir means use root from current directory. */
3051 if (root_dir == NULL)
3053 if (w32_unicode_filenames)
3055 wchar_t curdirw[MAX_PATH];
3057 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3058 return NULL;
3059 filename_from_utf16 (curdirw, default_root);
3061 else
3063 char curdira[MAX_PATH];
3065 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3066 return NULL;
3067 filename_from_ansi (curdira, default_root);
3069 parse_root (default_root, (const char **)&root_dir);
3070 *root_dir = 0;
3071 root_dir = default_root;
3074 /* Local fixed drives can be cached permanently. Removable drives
3075 cannot be cached permanently, since the volume name and serial
3076 number (if nothing else) can change. Remote drives should be
3077 treated as if they are removable, since there is no sure way to
3078 tell whether they are or not. Also, the UNC association of drive
3079 letters mapped to remote volumes can be changed at any time (even
3080 by other processes) without notice.
3082 As a compromise, so we can benefit from caching info for remote
3083 volumes, we use a simple expiry mechanism to invalidate cache
3084 entries that are more than ten seconds old. */
3086 #if 0
3087 /* No point doing this, because WNetGetConnection is even slower than
3088 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3089 GetDriveType is about the only call of this type which does not
3090 involve network access, and so is extremely quick). */
3092 /* Map drive letter to UNC if remote. */
3093 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3095 char remote_name[ 256 ];
3096 char drive[3] = { root_dir[0], ':' };
3098 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3099 == NO_ERROR)
3100 /* do something */ ;
3102 #endif
3104 info = lookup_volume_info (root_dir);
3106 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3108 DWORD serialnum;
3109 DWORD maxcomp;
3110 DWORD flags;
3112 /* Info is not cached, or is stale. */
3113 if (w32_unicode_filenames)
3115 wchar_t root_w[MAX_PATH];
3116 wchar_t name_w[MAX_PATH+1];
3117 wchar_t type_w[MAX_PATH+1];
3119 filename_to_utf16 (root_dir, root_w);
3120 if (!GetVolumeInformationW (root_w,
3121 name_w, sizeof (name_w),
3122 &serialnum,
3123 &maxcomp,
3124 &flags,
3125 type_w, sizeof (type_w)))
3126 return NULL;
3127 /* Hmm... not really 100% correct, as these 2 are not file
3128 names... */
3129 filename_from_utf16 (name_w, name);
3130 filename_from_utf16 (type_w, type);
3132 else
3134 char root_a[MAX_PATH];
3135 char name_a[MAX_PATH+1];
3136 char type_a[MAX_PATH+1];
3138 filename_to_ansi (root_dir, root_a);
3139 if (!GetVolumeInformationA (root_a,
3140 name_a, sizeof (name_a),
3141 &serialnum,
3142 &maxcomp,
3143 &flags,
3144 type_a, sizeof (type_a)))
3145 return NULL;
3146 filename_from_ansi (name_a, name);
3147 filename_from_ansi (type_a, type);
3150 /* Cache the volume information for future use, overwriting existing
3151 entry if present. */
3152 if (info == NULL)
3154 info = xmalloc (sizeof (volume_info_data));
3155 add_volume_info (root_dir, info);
3157 else
3159 xfree (info->name);
3160 xfree (info->type);
3163 info->name = xstrdup (name);
3164 unixtodos_filename (info->name);
3165 info->serialnum = serialnum;
3166 info->maxcomp = maxcomp;
3167 info->flags = flags;
3168 info->type = xstrdup (type);
3169 info->timestamp = GetTickCount ();
3172 return info;
3175 /* Get information on the volume where NAME is held; set path pointer to
3176 start of pathname in NAME (past UNC header\volume header if present),
3177 if pPath is non-NULL.
3179 Note: if NAME includes symlinks, the information is for the volume
3180 of the symlink, not of its target. That's because, even though
3181 GetVolumeInformation returns information about the symlink target
3182 of its argument, we only pass the root directory to
3183 GetVolumeInformation, not the full NAME. */
3184 static int
3185 get_volume_info (const char * name, const char ** pPath)
3187 char temp[MAX_UTF8_PATH];
3188 char *rootname = NULL; /* default to current volume */
3189 volume_info_data * info;
3190 int root_len = parse_root (name, pPath);
3192 if (name == NULL)
3193 return FALSE;
3195 /* Copy the root name of the volume, if given. */
3196 if (root_len)
3198 strncpy (temp, name, root_len);
3199 temp[root_len] = '\0';
3200 unixtodos_filename (temp);
3201 rootname = temp;
3204 info = GetCachedVolumeInformation (rootname);
3205 if (info != NULL)
3207 /* Set global referenced by other functions. */
3208 volume_info = *info;
3209 return TRUE;
3211 return FALSE;
3214 /* Determine if volume is FAT format (ie. only supports short 8.3
3215 names); also set path pointer to start of pathname in name, if
3216 pPath is non-NULL. */
3217 static int
3218 is_fat_volume (const char * name, const char ** pPath)
3220 if (get_volume_info (name, pPath))
3221 return (volume_info.maxcomp == 12);
3222 return FALSE;
3225 /* Convert all slashes in a filename to backslashes, and map filename
3226 to a valid 8.3 name if necessary. The result is a pointer to a
3227 static buffer, so CAVEAT EMPTOR! */
3228 const char *
3229 map_w32_filename (const char * name, const char ** pPath)
3231 static char shortname[MAX_UTF8_PATH];
3232 char * str = shortname;
3233 char c;
3234 char * path;
3235 const char * save_name = name;
3237 if (strlen (name) >= sizeof (shortname))
3239 /* Return a filename which will cause callers to fail. */
3240 strcpy (shortname, "?");
3241 return shortname;
3244 if (!fatal_error_in_progress /* disable fancy processing during crash */
3245 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3247 register int left = 8; /* maximum number of chars in part */
3248 register int extn = 0; /* extension added? */
3249 register int dots = 2; /* maximum number of dots allowed */
3251 while (name < path)
3252 *str++ = *name++; /* skip past UNC header */
3254 while ((c = *name++))
3256 switch ( c )
3258 case ':':
3259 case '\\':
3260 case '/':
3261 *str++ = (c == ':' ? ':' : '\\');
3262 extn = 0; /* reset extension flags */
3263 dots = 2; /* max 2 dots */
3264 left = 8; /* max length 8 for main part */
3265 break;
3266 case '.':
3267 if ( dots )
3269 /* Convert path components of the form .xxx to _xxx,
3270 but leave . and .. as they are. This allows .emacs
3271 to be read as _emacs, for example. */
3273 if (! *name ||
3274 *name == '.' ||
3275 IS_DIRECTORY_SEP (*name))
3277 *str++ = '.';
3278 dots--;
3280 else
3282 *str++ = '_';
3283 left--;
3284 dots = 0;
3287 else if ( !extn )
3289 *str++ = '.';
3290 extn = 1; /* we've got an extension */
3291 left = 3; /* 3 chars in extension */
3293 else
3295 /* any embedded dots after the first are converted to _ */
3296 *str++ = '_';
3298 break;
3299 case '~':
3300 case '#': /* don't lose these, they're important */
3301 if ( ! left )
3302 str[-1] = c; /* replace last character of part */
3303 /* FALLTHRU */
3304 default:
3305 if ( left && 'A' <= c && c <= 'Z' )
3307 *str++ = tolower (c); /* map to lower case (looks nicer) */
3308 left--;
3309 dots = 0; /* started a path component */
3311 break;
3314 *str = '\0';
3316 else
3318 strcpy (shortname, name);
3319 unixtodos_filename (shortname);
3322 if (pPath)
3323 *pPath = shortname + (path - save_name);
3325 return shortname;
3328 static int
3329 is_exec (const char * name)
3331 char * p = strrchr (name, '.');
3332 return
3333 (p != NULL
3334 && (xstrcasecmp (p, ".exe") == 0 ||
3335 xstrcasecmp (p, ".com") == 0 ||
3336 xstrcasecmp (p, ".bat") == 0 ||
3337 xstrcasecmp (p, ".cmd") == 0));
3340 /* Emulate the Unix directory procedures opendir, closedir, and
3341 readdir. We rename them to sys_* names because some versions of
3342 MinGW startup code call opendir and readdir to glob wildcards, and
3343 the code that calls them doesn't grok UTF-8 encoded file names we
3344 produce in dirent->d_name[]. */
3346 struct dirent dir_static; /* simulated directory contents */
3347 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3348 static int dir_is_fat;
3349 static char dir_pathname[MAX_UTF8_PATH];
3350 static WIN32_FIND_DATAW dir_find_data_w;
3351 static WIN32_FIND_DATAA dir_find_data_a;
3352 #define DIR_FIND_DATA_W 1
3353 #define DIR_FIND_DATA_A 2
3354 static int last_dir_find_data = -1;
3356 /* Support shares on a network resource as subdirectories of a read-only
3357 root directory. */
3358 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3359 static HANDLE open_unc_volume (const char *);
3360 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3361 static void close_unc_volume (HANDLE);
3363 DIR *
3364 sys_opendir (const char *filename)
3366 DIR *dirp;
3368 /* Opening is done by FindFirstFile. However, a read is inherent to
3369 this operation, so we defer the open until read time. */
3371 if (dir_find_handle != INVALID_HANDLE_VALUE)
3372 return NULL;
3373 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3374 return NULL;
3376 /* Note: We don't support traversal of UNC volumes via symlinks.
3377 Doing so would mean punishing 99.99% of use cases by resolving
3378 all the possible symlinks in FILENAME, recursively. */
3379 if (is_unc_volume (filename))
3381 wnet_enum_handle = open_unc_volume (filename);
3382 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3383 return NULL;
3386 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3387 return NULL;
3389 dirp->dd_fd = 0;
3390 dirp->dd_loc = 0;
3391 dirp->dd_size = 0;
3393 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3394 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3395 /* Note: We don't support symlinks to file names on FAT volumes.
3396 Doing so would mean punishing 99.99% of use cases by resolving
3397 all the possible symlinks in FILENAME, recursively. */
3398 dir_is_fat = is_fat_volume (filename, NULL);
3400 return dirp;
3403 void
3404 sys_closedir (DIR *dirp)
3406 /* If we have a find-handle open, close it. */
3407 if (dir_find_handle != INVALID_HANDLE_VALUE)
3409 FindClose (dir_find_handle);
3410 dir_find_handle = INVALID_HANDLE_VALUE;
3412 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3414 close_unc_volume (wnet_enum_handle);
3415 wnet_enum_handle = INVALID_HANDLE_VALUE;
3417 xfree ((char *) dirp);
3420 struct dirent *
3421 sys_readdir (DIR *dirp)
3423 int downcase = !NILP (Vw32_downcase_file_names);
3425 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3427 if (!read_unc_volume (wnet_enum_handle,
3428 dir_find_data_w.cFileName,
3429 dir_find_data_a.cFileName,
3430 MAX_PATH))
3431 return NULL;
3433 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3434 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3436 char filename[MAX_UTF8_PATH];
3437 int ln;
3438 bool last_slash = true;
3440 /* Note: We don't need to worry about dir_pathname being longer
3441 than MAX_UTF8_PATH, as sys_opendir already took care of that
3442 when it called map_w32_filename: that function will put a "?"
3443 in its return value in that case, thus failing all the calls
3444 below. */
3445 strcpy (filename, dir_pathname);
3446 ln = strlen (filename);
3447 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3448 last_slash = false;
3450 /* Note: No need to resolve symlinks in FILENAME, because
3451 FindFirst opens the directory that is the target of a
3452 symlink. */
3453 if (w32_unicode_filenames)
3455 wchar_t fnw[MAX_PATH + 2];
3457 filename_to_utf16 (filename, fnw);
3458 if (!last_slash)
3459 wcscat (fnw, L"\\");
3460 wcscat (fnw, L"*");
3461 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3463 else
3465 char fna[MAX_PATH + 2];
3467 filename_to_ansi (filename, fna);
3468 if (!last_slash)
3469 strcat (fna, "\\");
3470 strcat (fna, "*");
3471 /* If FILENAME is not representable by the current ANSI
3472 codepage, we don't want FindFirstFileA to interpret the
3473 '?' characters as a wildcard. */
3474 if (_mbspbrk (fna, "?"))
3475 dir_find_handle = INVALID_HANDLE_VALUE;
3476 else
3477 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3480 if (dir_find_handle == INVALID_HANDLE_VALUE)
3482 /* Any changes in the value of errno here should be in sync
3483 with what directory_files_internal does when it calls
3484 readdir. */
3485 switch (GetLastError ())
3487 /* Windows uses this value when FindFirstFile finds no
3488 files that match the wildcard. This is not supposed
3489 to happen, since our wildcard is "*", but just in
3490 case, if there's some weird empty directory with not
3491 even "." and ".." entries... */
3492 case ERROR_FILE_NOT_FOUND:
3493 errno = 0;
3494 /* FALLTHRU */
3495 default:
3496 break;
3497 case ERROR_ACCESS_DENIED:
3498 case ERROR_NETWORK_ACCESS_DENIED:
3499 errno = EACCES;
3500 break;
3501 case ERROR_PATH_NOT_FOUND:
3502 case ERROR_INVALID_DRIVE:
3503 case ERROR_NOT_READY:
3504 case ERROR_BAD_NETPATH:
3505 case ERROR_BAD_NET_NAME:
3506 errno = ENOENT;
3507 break;
3509 return NULL;
3512 else if (w32_unicode_filenames)
3514 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3516 errno = 0;
3517 return NULL;
3520 else
3522 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3524 errno = 0;
3525 return NULL;
3529 /* Emacs never uses this value, so don't bother making it match
3530 value returned by stat(). */
3531 dir_static.d_ino = 1;
3533 if (w32_unicode_filenames)
3535 if (downcase || dir_is_fat)
3537 wchar_t tem[MAX_PATH];
3539 wcscpy (tem, dir_find_data_w.cFileName);
3540 CharLowerW (tem);
3541 filename_from_utf16 (tem, dir_static.d_name);
3543 else
3544 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3545 last_dir_find_data = DIR_FIND_DATA_W;
3547 else
3549 char tem[MAX_PATH];
3551 /* If the file name in cFileName[] includes `?' characters, it
3552 means the original file name used characters that cannot be
3553 represented by the current ANSI codepage. To avoid total
3554 lossage, retrieve the short 8+3 alias of the long file
3555 name. */
3556 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3558 strcpy (tem, dir_find_data_a.cAlternateFileName);
3559 /* 8+3 aliases are returned in all caps, which could break
3560 various alists that look at filenames' extensions. */
3561 downcase = 1;
3563 else if (downcase || dir_is_fat)
3564 strcpy (tem, dir_find_data_a.cFileName);
3565 else
3566 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3567 if (downcase || dir_is_fat)
3569 _mbslwr (tem);
3570 filename_from_ansi (tem, dir_static.d_name);
3572 last_dir_find_data = DIR_FIND_DATA_A;
3575 dir_static.d_namlen = strlen (dir_static.d_name);
3576 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3577 dir_static.d_namlen - dir_static.d_namlen % 4;
3579 return &dir_static;
3582 static HANDLE
3583 open_unc_volume (const char *path)
3585 const char *fn = map_w32_filename (path, NULL);
3586 DWORD result;
3587 HANDLE henum;
3589 if (w32_unicode_filenames)
3591 NETRESOURCEW nrw;
3592 wchar_t fnw[MAX_PATH];
3594 nrw.dwScope = RESOURCE_GLOBALNET;
3595 nrw.dwType = RESOURCETYPE_DISK;
3596 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3597 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3598 nrw.lpLocalName = NULL;
3599 filename_to_utf16 (fn, fnw);
3600 nrw.lpRemoteName = fnw;
3601 nrw.lpComment = NULL;
3602 nrw.lpProvider = NULL;
3604 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3605 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3607 else
3609 NETRESOURCEA nra;
3610 char fna[MAX_PATH];
3612 nra.dwScope = RESOURCE_GLOBALNET;
3613 nra.dwType = RESOURCETYPE_DISK;
3614 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3615 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3616 nra.lpLocalName = NULL;
3617 filename_to_ansi (fn, fna);
3618 nra.lpRemoteName = fna;
3619 nra.lpComment = NULL;
3620 nra.lpProvider = NULL;
3622 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3623 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3625 if (result == NO_ERROR)
3626 return henum;
3627 else
3629 /* Make sure directory_files_internal reports a sensible error. */
3630 errno = ENOENT;
3631 return INVALID_HANDLE_VALUE;
3635 static void *
3636 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3638 DWORD count;
3639 int result;
3640 char *buffer;
3641 DWORD bufsize = 512;
3642 void *retval;
3644 count = 1;
3645 if (w32_unicode_filenames)
3647 wchar_t *ptrw;
3649 bufsize *= 2;
3650 buffer = alloca (bufsize);
3651 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3652 if (result != NO_ERROR)
3653 return NULL;
3654 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3655 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3656 ptrw += 2;
3657 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3658 ptrw++;
3659 wcsncpy (fname_w, ptrw, size);
3660 retval = fname_w;
3662 else
3664 int dbcs_p = max_filename_mbslen () > 1;
3665 char *ptra;
3667 buffer = alloca (bufsize);
3668 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3669 if (result != NO_ERROR)
3670 return NULL;
3671 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3672 ptra += 2;
3673 if (!dbcs_p)
3674 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3675 else
3677 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3678 ptra = CharNextExA (file_name_codepage, ptra, 0);
3680 ptra++;
3681 strncpy (fname_a, ptra, size);
3682 retval = fname_a;
3685 return retval;
3688 static void
3689 close_unc_volume (HANDLE henum)
3691 if (henum != INVALID_HANDLE_VALUE)
3692 WNetCloseEnum (henum);
3695 static DWORD
3696 unc_volume_file_attributes (const char *path)
3698 HANDLE henum;
3699 DWORD attrs;
3701 henum = open_unc_volume (path);
3702 if (henum == INVALID_HANDLE_VALUE)
3703 return -1;
3705 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3707 close_unc_volume (henum);
3709 return attrs;
3712 /* Ensure a network connection is authenticated. */
3713 static void
3714 logon_network_drive (const char *path)
3716 char share[MAX_UTF8_PATH];
3717 int n_slashes;
3718 char drive[4];
3719 UINT drvtype;
3720 char *p;
3721 DWORD val;
3723 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3724 drvtype = DRIVE_REMOTE;
3725 else if (path[0] == '\0' || path[1] != ':')
3726 drvtype = GetDriveType (NULL);
3727 else
3729 drive[0] = path[0];
3730 drive[1] = ':';
3731 drive[2] = '\\';
3732 drive[3] = '\0';
3733 drvtype = GetDriveType (drive);
3736 /* Only logon to networked drives. */
3737 if (drvtype != DRIVE_REMOTE)
3738 return;
3740 n_slashes = 2;
3741 strncpy (share, path, MAX_UTF8_PATH);
3742 /* Truncate to just server and share name. */
3743 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3745 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3747 *p = '\0';
3748 break;
3752 if (w32_unicode_filenames)
3754 NETRESOURCEW resourcew;
3755 wchar_t share_w[MAX_PATH];
3757 resourcew.dwScope = RESOURCE_GLOBALNET;
3758 resourcew.dwType = RESOURCETYPE_DISK;
3759 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3760 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3761 resourcew.lpLocalName = NULL;
3762 filename_to_utf16 (share, share_w);
3763 resourcew.lpRemoteName = share_w;
3764 resourcew.lpProvider = NULL;
3766 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3768 else
3770 NETRESOURCEA resourcea;
3771 char share_a[MAX_PATH];
3773 resourcea.dwScope = RESOURCE_GLOBALNET;
3774 resourcea.dwType = RESOURCETYPE_DISK;
3775 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3776 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3777 resourcea.lpLocalName = NULL;
3778 filename_to_ansi (share, share_a);
3779 resourcea.lpRemoteName = share_a;
3780 resourcea.lpProvider = NULL;
3782 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3785 switch (val)
3787 case NO_ERROR:
3788 case ERROR_ALREADY_ASSIGNED:
3789 break;
3790 case ERROR_ACCESS_DENIED:
3791 case ERROR_LOGON_FAILURE:
3792 errno = EACCES;
3793 break;
3794 case ERROR_BUSY:
3795 errno = EAGAIN;
3796 break;
3797 case ERROR_BAD_NET_NAME:
3798 case ERROR_NO_NET_OR_BAD_PATH:
3799 case ERROR_NO_NETWORK:
3800 case ERROR_CANCELLED:
3801 default:
3802 errno = ENOENT;
3803 break;
3807 /* Emulate faccessat(2). */
3809 faccessat (int dirfd, const char * path, int mode, int flags)
3811 DWORD attributes;
3813 if (dirfd != AT_FDCWD
3814 && !(IS_DIRECTORY_SEP (path[0])
3815 || IS_DEVICE_SEP (path[1])))
3817 errno = EBADF;
3818 return -1;
3821 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3822 newer versions blow up when passed D_OK. */
3823 path = map_w32_filename (path, NULL);
3824 /* If the last element of PATH is a symlink, we need to resolve it
3825 to get the attributes of its target file. Note: any symlinks in
3826 PATH elements other than the last one are transparently resolved
3827 by GetFileAttributes below. */
3828 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3829 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3830 path = chase_symlinks (path);
3832 if (w32_unicode_filenames)
3834 wchar_t path_w[MAX_PATH];
3836 filename_to_utf16 (path, path_w);
3837 attributes = GetFileAttributesW (path_w);
3839 else
3841 char path_a[MAX_PATH];
3843 filename_to_ansi (path, path_a);
3844 attributes = GetFileAttributesA (path_a);
3847 if (attributes == -1)
3849 DWORD w32err = GetLastError ();
3851 switch (w32err)
3853 case ERROR_INVALID_NAME:
3854 case ERROR_BAD_PATHNAME:
3855 if (is_unc_volume (path))
3857 attributes = unc_volume_file_attributes (path);
3858 if (attributes == -1)
3860 errno = EACCES;
3861 return -1;
3863 goto check_attrs;
3865 /* FALLTHROUGH */
3866 case ERROR_FILE_NOT_FOUND:
3867 case ERROR_BAD_NETPATH:
3868 errno = ENOENT;
3869 break;
3870 default:
3871 errno = EACCES;
3872 break;
3874 return -1;
3877 check_attrs:
3878 if ((mode & X_OK) != 0
3879 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3881 errno = EACCES;
3882 return -1;
3884 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3886 errno = EACCES;
3887 return -1;
3889 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3891 errno = EACCES;
3892 return -1;
3894 return 0;
3897 /* A special test for DIRNAME being a directory accessible by the
3898 current user. This is needed because the security permissions in
3899 directory's ACLs are not visible in the Posix-style mode bits
3900 returned by 'stat' and in attributes returned by GetFileAttributes.
3901 So a directory would seem like it's readable by the current user,
3902 but will in fact error out with EACCES when they actually try. */
3904 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3906 char pattern[MAX_UTF8_PATH];
3907 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3908 HANDLE dh;
3910 /* Network volumes need a different reading method. */
3911 if (is_unc_volume (dirname))
3913 void *read_result = NULL;
3914 wchar_t fnw[MAX_PATH];
3915 char fna[MAX_PATH];
3917 dh = open_unc_volume (dirname);
3918 if (dh != INVALID_HANDLE_VALUE)
3920 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
3921 close_unc_volume (dh);
3923 /* Treat empty volumes as accessible. */
3924 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
3927 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3928 MAX_UTF8_PATH. */
3929 strcpy (pattern, map_w32_filename (dirname, NULL));
3931 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3932 opens the directory that is the target of a symlink. */
3933 if (w32_unicode_filenames)
3935 wchar_t pat_w[MAX_PATH + 2];
3936 WIN32_FIND_DATAW dfd_w;
3938 filename_to_utf16 (pattern, pat_w);
3939 if (!last_slash)
3940 wcscat (pat_w, L"\\");
3941 wcscat (pat_w, L"*");
3942 dh = FindFirstFileW (pat_w, &dfd_w);
3944 else
3946 char pat_a[MAX_PATH + 2];
3947 WIN32_FIND_DATAA dfd_a;
3949 filename_to_ansi (pattern, pat_a);
3950 if (!last_slash)
3951 strcpy (pat_a, "\\");
3952 strcat (pat_a, "*");
3953 /* In case DIRNAME cannot be expressed in characters from the
3954 current ANSI codepage. */
3955 if (_mbspbrk (pat_a, "?"))
3956 dh = INVALID_HANDLE_VALUE;
3957 else
3958 dh = FindFirstFileA (pat_a, &dfd_a);
3961 if (dh == INVALID_HANDLE_VALUE)
3962 return 0;
3963 FindClose (dh);
3964 return 1;
3967 /* A version of 'access' to be used locally with file names in
3968 locale-specific encoding. Does not resolve symlinks and does not
3969 support file names on FAT12 and FAT16 volumes, but that's OK, since
3970 we only invoke this function for files inside the Emacs source or
3971 installation tree, on directories (so any symlinks should have the
3972 directory bit set), and on short file names such as "C:/.emacs". */
3973 static int
3974 sys_access (const char *fname, int mode)
3976 char fname_copy[MAX_PATH], *p;
3977 DWORD attributes;
3979 strcpy (fname_copy, fname);
3980 /* Do the equivalent of unixtodos_filename. */
3981 for (p = fname_copy; *p; p = CharNext (p))
3982 if (*p == '/')
3983 *p = '\\';
3985 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
3987 DWORD w32err = GetLastError ();
3989 switch (w32err)
3991 case ERROR_INVALID_NAME:
3992 case ERROR_BAD_PATHNAME:
3993 case ERROR_FILE_NOT_FOUND:
3994 case ERROR_BAD_NETPATH:
3995 errno = ENOENT;
3996 break;
3997 default:
3998 errno = EACCES;
3999 break;
4001 return -1;
4003 if ((mode & X_OK) != 0
4004 && !(is_exec (fname_copy)
4005 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4007 errno = EACCES;
4008 return -1;
4010 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4012 errno = EACCES;
4013 return -1;
4015 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4017 errno = EACCES;
4018 return -1;
4020 return 0;
4023 /* Shadow some MSVC runtime functions to map requests for long filenames
4024 to reasonable short names if necessary. This was originally added to
4025 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4026 long file names. */
4029 sys_chdir (const char * path)
4031 path = map_w32_filename (path, NULL);
4032 if (w32_unicode_filenames)
4034 wchar_t newdir_w[MAX_PATH];
4036 if (filename_to_utf16 (path, newdir_w) == 0)
4037 return _wchdir (newdir_w);
4038 return -1;
4040 else
4042 char newdir_a[MAX_PATH];
4044 if (filename_to_ansi (path, newdir_a) == 0)
4045 return _chdir (newdir_a);
4046 return -1;
4051 sys_chmod (const char * path, int mode)
4053 path = chase_symlinks (map_w32_filename (path, NULL));
4054 if (w32_unicode_filenames)
4056 wchar_t path_w[MAX_PATH];
4058 filename_to_utf16 (path, path_w);
4059 return _wchmod (path_w, mode);
4061 else
4063 char path_a[MAX_PATH];
4065 filename_to_ansi (path, path_a);
4066 return _chmod (path_a, mode);
4071 sys_creat (const char * path, int mode)
4073 path = map_w32_filename (path, NULL);
4074 if (w32_unicode_filenames)
4076 wchar_t path_w[MAX_PATH];
4078 filename_to_utf16 (path, path_w);
4079 return _wcreat (path_w, mode);
4081 else
4083 char path_a[MAX_PATH];
4085 filename_to_ansi (path, path_a);
4086 return _creat (path_a, mode);
4090 FILE *
4091 sys_fopen (const char * path, const char * mode)
4093 int fd;
4094 int oflag;
4095 const char * mode_save = mode;
4097 /* Force all file handles to be non-inheritable. This is necessary to
4098 ensure child processes don't unwittingly inherit handles that might
4099 prevent future file access. */
4101 if (mode[0] == 'r')
4102 oflag = O_RDONLY;
4103 else if (mode[0] == 'w' || mode[0] == 'a')
4104 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4105 else
4106 return NULL;
4108 /* Only do simplistic option parsing. */
4109 while (*++mode)
4110 if (mode[0] == '+')
4112 oflag &= ~(O_RDONLY | O_WRONLY);
4113 oflag |= O_RDWR;
4115 else if (mode[0] == 'b')
4117 oflag &= ~O_TEXT;
4118 oflag |= O_BINARY;
4120 else if (mode[0] == 't')
4122 oflag &= ~O_BINARY;
4123 oflag |= O_TEXT;
4125 else break;
4127 path = map_w32_filename (path, NULL);
4128 if (w32_unicode_filenames)
4130 wchar_t path_w[MAX_PATH];
4132 filename_to_utf16 (path, path_w);
4133 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4135 else
4137 char path_a[MAX_PATH];
4139 filename_to_ansi (path, path_a);
4140 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4142 if (fd < 0)
4143 return NULL;
4145 return _fdopen (fd, mode_save);
4148 /* This only works on NTFS volumes, but is useful to have. */
4150 sys_link (const char * old, const char * new)
4152 HANDLE fileh;
4153 int result = -1;
4154 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4155 wchar_t oldname_w[MAX_PATH];
4156 char oldname_a[MAX_PATH];
4158 if (old == NULL || new == NULL)
4160 errno = ENOENT;
4161 return -1;
4164 strcpy (oldname, map_w32_filename (old, NULL));
4165 strcpy (newname, map_w32_filename (new, NULL));
4167 if (w32_unicode_filenames)
4169 filename_to_utf16 (oldname, oldname_w);
4170 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4171 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4173 else
4175 filename_to_ansi (oldname, oldname_a);
4176 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4177 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4179 if (fileh != INVALID_HANDLE_VALUE)
4181 int wlen;
4183 /* Confusingly, the "alternate" stream name field does not apply
4184 when restoring a hard link, and instead contains the actual
4185 stream data for the link (ie. the name of the link to create).
4186 The WIN32_STREAM_ID structure before the cStreamName field is
4187 the stream header, which is then immediately followed by the
4188 stream data. */
4190 struct {
4191 WIN32_STREAM_ID wid;
4192 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4193 } data;
4195 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4196 indicates that flag is unsupported for CP_UTF8, and OTOH says
4197 it is the default anyway. */
4198 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4199 data.wid.cStreamName, MAX_PATH);
4200 if (wlen > 0)
4202 LPVOID context = NULL;
4203 DWORD wbytes = 0;
4205 data.wid.dwStreamId = BACKUP_LINK;
4206 data.wid.dwStreamAttributes = 0;
4207 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4208 data.wid.Size.HighPart = 0;
4209 data.wid.dwStreamNameSize = 0;
4211 if (BackupWrite (fileh, (LPBYTE)&data,
4212 offsetof (WIN32_STREAM_ID, cStreamName)
4213 + data.wid.Size.LowPart,
4214 &wbytes, FALSE, FALSE, &context)
4215 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4217 /* succeeded */
4218 result = 0;
4220 else
4222 DWORD err = GetLastError ();
4223 DWORD attributes;
4225 switch (err)
4227 case ERROR_ACCESS_DENIED:
4228 /* This is what happens when OLDNAME is a directory,
4229 since Windows doesn't support hard links to
4230 directories. Posix says to set errno to EPERM in
4231 that case. */
4232 if (w32_unicode_filenames)
4233 attributes = GetFileAttributesW (oldname_w);
4234 else
4235 attributes = GetFileAttributesA (oldname_a);
4236 if (attributes != -1
4237 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4238 errno = EPERM;
4239 else if (attributes == -1
4240 && is_unc_volume (oldname)
4241 && unc_volume_file_attributes (oldname) != -1)
4242 errno = EPERM;
4243 else
4244 errno = EACCES;
4245 break;
4246 case ERROR_TOO_MANY_LINKS:
4247 errno = EMLINK;
4248 break;
4249 case ERROR_NOT_SAME_DEVICE:
4250 errno = EXDEV;
4251 break;
4252 default:
4253 errno = EINVAL;
4254 break;
4259 CloseHandle (fileh);
4261 else
4262 errno = ENOENT;
4264 return result;
4268 sys_mkdir (const char * path)
4270 path = map_w32_filename (path, NULL);
4272 if (w32_unicode_filenames)
4274 wchar_t path_w[MAX_PATH];
4276 filename_to_utf16 (path, path_w);
4277 return _wmkdir (path_w);
4279 else
4281 char path_a[MAX_PATH];
4283 filename_to_ansi (path, path_a);
4284 return _mkdir (path_a);
4289 sys_open (const char * path, int oflag, int mode)
4291 const char* mpath = map_w32_filename (path, NULL);
4292 int res = -1;
4294 if (w32_unicode_filenames)
4296 wchar_t mpath_w[MAX_PATH];
4298 filename_to_utf16 (mpath, mpath_w);
4299 /* If possible, try to open file without _O_CREAT, to be able to
4300 write to existing hidden and system files. Force all file
4301 handles to be non-inheritable. */
4302 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4303 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4304 if (res < 0)
4305 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4307 else
4309 char mpath_a[MAX_PATH];
4311 filename_to_ansi (mpath, mpath_a);
4312 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4313 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4314 if (res < 0)
4315 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4318 return res;
4321 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4322 when using mktemp.
4324 Standard algorithm for generating a temporary file name seems to be
4325 use pid or tid with a letter on the front (in place of the 6 X's)
4326 and cycle through the letters to find a unique name. We extend
4327 that to allow any reasonable character as the first of the 6 X's,
4328 so that the number of simultaneously used temporary files will be
4329 greater. */
4332 mkostemp (char * template, int flags)
4334 char * p;
4335 int i, fd = -1;
4336 unsigned uid = GetCurrentThreadId ();
4337 int save_errno = errno;
4338 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4340 errno = EINVAL;
4341 if (template == NULL)
4342 return -1;
4344 p = template + strlen (template);
4345 i = 5;
4346 /* replace up to the last 5 X's with uid in decimal */
4347 while (--p >= template && p[0] == 'X' && --i >= 0)
4349 p[0] = '0' + uid % 10;
4350 uid /= 10;
4353 if (i < 0 && p[0] == 'X')
4355 i = 0;
4358 p[0] = first_char[i];
4359 if ((fd = sys_open (template,
4360 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4361 S_IRUSR | S_IWUSR)) >= 0
4362 || errno != EEXIST)
4364 if (fd >= 0)
4365 errno = save_errno;
4366 return fd;
4369 while (++i < sizeof (first_char));
4372 /* Template is badly formed or else we can't generate a unique name. */
4373 return -1;
4377 fchmod (int fd, mode_t mode)
4379 return 0;
4383 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4385 BOOL result;
4386 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4387 int newname_dev;
4388 int oldname_dev;
4389 bool have_temp_a = false;
4391 /* MoveFile on Windows 95 doesn't correctly change the short file name
4392 alias in a number of circumstances (it is not easy to predict when
4393 just by looking at oldname and newname, unfortunately). In these
4394 cases, renaming through a temporary name avoids the problem.
4396 A second problem on Windows 95 is that renaming through a temp name when
4397 newname is uppercase fails (the final long name ends up in
4398 lowercase, although the short alias might be uppercase) UNLESS the
4399 long temp name is not 8.3.
4401 So, on Windows 95 we always rename through a temp name, and we make sure
4402 the temp name has a long extension to ensure correct renaming. */
4404 strcpy (temp, map_w32_filename (oldname, NULL));
4406 /* volume_info is set indirectly by map_w32_filename. */
4407 oldname_dev = volume_info.serialnum;
4409 if (os_subtype == OS_9X)
4411 char * o;
4412 char * p;
4413 int i = 0;
4414 char oldname_a[MAX_PATH];
4416 oldname = map_w32_filename (oldname, NULL);
4417 filename_to_ansi (oldname, oldname_a);
4418 filename_to_ansi (temp, temp_a);
4419 if ((o = strrchr (oldname_a, '\\')))
4420 o++;
4421 else
4422 o = (char *) oldname_a;
4424 if ((p = strrchr (temp_a, '\\')))
4425 p++;
4426 else
4427 p = temp_a;
4431 /* Force temp name to require a manufactured 8.3 alias - this
4432 seems to make the second rename work properly. */
4433 sprintf (p, "_.%s.%u", o, i);
4434 i++;
4435 result = rename (oldname_a, temp_a);
4437 /* This loop must surely terminate! */
4438 while (result < 0 && errno == EEXIST);
4439 if (result < 0)
4440 return -1;
4441 have_temp_a = true;
4444 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4445 (at least if it is a file; don't do this for directories).
4447 Since we mustn't do this if we are just changing the case of the
4448 file name (we would end up deleting the file we are trying to
4449 rename!), we let rename detect if the destination file already
4450 exists - that way we avoid the possible pitfalls of trying to
4451 determine ourselves whether two names really refer to the same
4452 file, which is not always possible in the general case. (Consider
4453 all the permutations of shared or subst'd drives, etc.) */
4455 newname = map_w32_filename (newname, NULL);
4457 /* volume_info is set indirectly by map_w32_filename. */
4458 newname_dev = volume_info.serialnum;
4460 if (w32_unicode_filenames)
4462 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4464 filename_to_utf16 (temp, temp_w);
4465 filename_to_utf16 (newname, newname_w);
4466 result = _wrename (temp_w, newname_w);
4467 if (result < 0 && force)
4469 DWORD w32err = GetLastError ();
4471 if (errno == EACCES
4472 && newname_dev != oldname_dev)
4474 /* The implementation of `rename' on Windows does not return
4475 errno = EXDEV when you are moving a directory to a
4476 different storage device (ex. logical disk). It returns
4477 EACCES instead. So here we handle such situations and
4478 return EXDEV. */
4479 DWORD attributes;
4481 if ((attributes = GetFileAttributesW (temp_w)) != -1
4482 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4483 errno = EXDEV;
4485 else if (errno == EEXIST)
4487 if (_wchmod (newname_w, 0666) != 0)
4488 return result;
4489 if (_wunlink (newname_w) != 0)
4490 return result;
4491 result = _wrename (temp_w, newname_w);
4493 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4494 && is_symlink (temp))
4496 /* This is Windows prohibiting the user from creating a
4497 symlink in another place, since that requires
4498 privileges. */
4499 errno = EPERM;
4503 else
4505 char newname_a[MAX_PATH];
4507 if (!have_temp_a)
4508 filename_to_ansi (temp, temp_a);
4509 filename_to_ansi (newname, newname_a);
4510 result = rename (temp_a, newname_a);
4511 if (result < 0 && force)
4513 DWORD w32err = GetLastError ();
4515 if (errno == EACCES
4516 && newname_dev != oldname_dev)
4518 DWORD attributes;
4520 if ((attributes = GetFileAttributesA (temp_a)) != -1
4521 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4522 errno = EXDEV;
4524 else if (errno == EEXIST)
4526 if (_chmod (newname_a, 0666) != 0)
4527 return result;
4528 if (_unlink (newname_a) != 0)
4529 return result;
4530 result = rename (temp_a, newname_a);
4532 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4533 && is_symlink (temp))
4534 errno = EPERM;
4538 return result;
4542 sys_rename (char const *old, char const *new)
4544 return sys_rename_replace (old, new, TRUE);
4548 sys_rmdir (const char * path)
4550 path = map_w32_filename (path, NULL);
4552 if (w32_unicode_filenames)
4554 wchar_t path_w[MAX_PATH];
4556 filename_to_utf16 (path, path_w);
4557 return _wrmdir (path_w);
4559 else
4561 char path_a[MAX_PATH];
4563 filename_to_ansi (path, path_a);
4564 return _rmdir (path_a);
4569 sys_unlink (const char * path)
4571 int rmstatus, e;
4573 path = map_w32_filename (path, NULL);
4575 if (w32_unicode_filenames)
4577 wchar_t path_w[MAX_PATH];
4579 filename_to_utf16 (path, path_w);
4580 /* On Unix, unlink works without write permission. */
4581 _wchmod (path_w, 0666);
4582 rmstatus = _wunlink (path_w);
4583 e = errno;
4584 /* Symlinks to directories can only be deleted by _rmdir;
4585 _unlink returns EACCES. */
4586 if (rmstatus != 0
4587 && errno == EACCES
4588 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4589 rmstatus = _wrmdir (path_w);
4590 else
4591 errno = e;
4593 else
4595 char path_a[MAX_PATH];
4597 filename_to_ansi (path, path_a);
4598 _chmod (path_a, 0666);
4599 rmstatus = _unlink (path_a);
4600 e = errno;
4601 if (rmstatus != 0
4602 && errno == EACCES
4603 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4604 rmstatus = _rmdir (path_a);
4605 else
4606 errno = e;
4609 return rmstatus;
4612 static FILETIME utc_base_ft;
4613 static ULONGLONG utc_base; /* In 100ns units */
4614 static int init = 0;
4616 #define FILETIME_TO_U64(result, ft) \
4617 do { \
4618 ULARGE_INTEGER uiTemp; \
4619 uiTemp.LowPart = (ft).dwLowDateTime; \
4620 uiTemp.HighPart = (ft).dwHighDateTime; \
4621 result = uiTemp.QuadPart; \
4622 } while (0)
4624 static void
4625 initialize_utc_base (void)
4627 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4628 SYSTEMTIME st;
4630 st.wYear = 1970;
4631 st.wMonth = 1;
4632 st.wDay = 1;
4633 st.wHour = 0;
4634 st.wMinute = 0;
4635 st.wSecond = 0;
4636 st.wMilliseconds = 0;
4638 SystemTimeToFileTime (&st, &utc_base_ft);
4639 FILETIME_TO_U64 (utc_base, utc_base_ft);
4642 static time_t
4643 convert_time (FILETIME ft)
4645 ULONGLONG tmp;
4647 if (!init)
4649 initialize_utc_base ();
4650 init = 1;
4653 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4654 return 0;
4656 FILETIME_TO_U64 (tmp, ft);
4657 return (time_t) ((tmp - utc_base) / 10000000L);
4660 static void
4661 convert_from_time_t (time_t time, FILETIME * pft)
4663 ULARGE_INTEGER tmp;
4665 if (!init)
4667 initialize_utc_base ();
4668 init = 1;
4671 /* time in 100ns units since 1-Jan-1601 */
4672 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4673 pft->dwHighDateTime = tmp.HighPart;
4674 pft->dwLowDateTime = tmp.LowPart;
4677 static PSECURITY_DESCRIPTOR
4678 get_file_security_desc_by_handle (HANDLE h)
4680 PSECURITY_DESCRIPTOR psd = NULL;
4681 DWORD err;
4682 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4683 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4685 err = get_security_info (h, SE_FILE_OBJECT, si,
4686 NULL, NULL, NULL, NULL, &psd);
4687 if (err != ERROR_SUCCESS)
4688 return NULL;
4690 return psd;
4693 static PSECURITY_DESCRIPTOR
4694 get_file_security_desc_by_name (const char *fname)
4696 PSECURITY_DESCRIPTOR psd = NULL;
4697 DWORD sd_len, err;
4698 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4699 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4701 if (!get_file_security (fname, si, psd, 0, &sd_len))
4703 err = GetLastError ();
4704 if (err != ERROR_INSUFFICIENT_BUFFER)
4705 return NULL;
4708 psd = xmalloc (sd_len);
4709 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4711 xfree (psd);
4712 return NULL;
4715 return psd;
4718 static DWORD
4719 get_rid (PSID sid)
4721 unsigned n_subauthorities;
4723 /* Use the last sub-authority value of the RID, the relative
4724 portion of the SID, as user/group ID. */
4725 n_subauthorities = *get_sid_sub_authority_count (sid);
4726 if (n_subauthorities < 1)
4727 return 0; /* the "World" RID */
4728 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4731 /* Caching SID and account values for faster lokup. */
4733 struct w32_id {
4734 unsigned rid;
4735 struct w32_id *next;
4736 char name[GNLEN+1];
4737 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4740 static struct w32_id *w32_idlist;
4742 static int
4743 w32_cached_id (PSID sid, unsigned *id, char *name)
4745 struct w32_id *tail, *found;
4747 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4749 if (equal_sid ((PSID)tail->sid, sid))
4751 found = tail;
4752 break;
4755 if (found)
4757 *id = found->rid;
4758 strcpy (name, found->name);
4759 return 1;
4761 else
4762 return 0;
4765 static void
4766 w32_add_to_cache (PSID sid, unsigned id, char *name)
4768 DWORD sid_len;
4769 struct w32_id *new_entry;
4771 /* We don't want to leave behind stale cache from when Emacs was
4772 dumped. */
4773 if (initialized)
4775 sid_len = get_length_sid (sid);
4776 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4777 if (new_entry)
4779 new_entry->rid = id;
4780 strcpy (new_entry->name, name);
4781 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4782 new_entry->next = w32_idlist;
4783 w32_idlist = new_entry;
4788 #define UID 1
4789 #define GID 2
4791 static int
4792 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4794 PSID sid = NULL;
4795 BOOL dflt;
4796 SID_NAME_USE ignore;
4797 char name[UNLEN+1];
4798 DWORD name_len = sizeof (name);
4799 char domain[1024];
4800 DWORD domain_len = sizeof (domain);
4801 int use_dflt = 0;
4802 int result;
4804 if (what == UID)
4805 result = get_security_descriptor_owner (psd, &sid, &dflt);
4806 else if (what == GID)
4807 result = get_security_descriptor_group (psd, &sid, &dflt);
4808 else
4809 result = 0;
4811 if (!result || !is_valid_sid (sid))
4812 use_dflt = 1;
4813 else if (!w32_cached_id (sid, id, nm))
4815 if (!lookup_account_sid (NULL, sid, name, &name_len,
4816 domain, &domain_len, &ignore)
4817 || name_len > UNLEN+1)
4818 use_dflt = 1;
4819 else
4821 *id = get_rid (sid);
4822 strcpy (nm, name);
4823 w32_add_to_cache (sid, *id, name);
4826 return use_dflt;
4829 static void
4830 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4832 int dflt_usr = 0, dflt_grp = 0;
4834 if (!psd)
4836 dflt_usr = 1;
4837 dflt_grp = 1;
4839 else
4841 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4842 dflt_usr = 1;
4843 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4844 dflt_grp = 1;
4846 /* Consider files to belong to current user/group, if we cannot get
4847 more accurate information. */
4848 if (dflt_usr)
4850 st->st_uid = dflt_passwd.pw_uid;
4851 strcpy (st->st_uname, dflt_passwd.pw_name);
4853 if (dflt_grp)
4855 st->st_gid = dflt_passwd.pw_gid;
4856 strcpy (st->st_gname, dflt_group.gr_name);
4860 /* Return non-zero if NAME is a potentially slow filesystem. */
4862 is_slow_fs (const char *name)
4864 char drive_root[4];
4865 UINT devtype;
4867 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4868 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4869 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4870 devtype = GetDriveType (NULL); /* use root of current drive */
4871 else
4873 /* GetDriveType needs the root directory of the drive. */
4874 strncpy (drive_root, name, 2);
4875 drive_root[2] = '\\';
4876 drive_root[3] = '\0';
4877 devtype = GetDriveType (drive_root);
4879 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4882 /* If this is non-zero, the caller wants accurate information about
4883 file's owner and group, which could be expensive to get. dired.c
4884 uses this flag when needed for the job at hand. */
4885 int w32_stat_get_owner_group;
4887 /* MSVC stat function can't cope with UNC names and has other bugs, so
4888 replace it with our own. This also allows us to calculate consistent
4889 inode values and owner/group without hacks in the main Emacs code,
4890 and support file names encoded in UTF-8. */
4892 static int
4893 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4895 char *name, *save_name, *r;
4896 WIN32_FIND_DATAW wfd_w;
4897 WIN32_FIND_DATAA wfd_a;
4898 HANDLE fh;
4899 unsigned __int64 fake_inode = 0;
4900 int permission;
4901 int len;
4902 int rootdir = FALSE;
4903 PSECURITY_DESCRIPTOR psd = NULL;
4904 int is_a_symlink = 0;
4905 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4906 DWORD access_rights = 0;
4907 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4908 FILETIME ctime, atime, wtime;
4909 wchar_t name_w[MAX_PATH];
4910 char name_a[MAX_PATH];
4912 if (path == NULL || buf == NULL)
4914 errno = EFAULT;
4915 return -1;
4918 save_name = name = (char *) map_w32_filename (path, &path);
4919 /* Must be valid filename, no wild cards or other invalid
4920 characters. */
4921 if (strpbrk (name, "*?|<>\""))
4923 errno = ENOENT;
4924 return -1;
4927 len = strlen (name);
4928 /* Allocate 1 extra byte so that we could append a slash to a root
4929 directory, down below. */
4930 name = strcpy (alloca (len + 2), name);
4932 /* Avoid a somewhat costly call to is_symlink if the filesystem
4933 doesn't support symlinks. */
4934 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4935 is_a_symlink = is_symlink (name);
4937 /* Plan A: Open the file and get all the necessary information via
4938 the resulting handle. This solves several issues in one blow:
4940 . retrieves attributes for the target of a symlink, if needed
4941 . gets attributes of root directories and symlinks pointing to
4942 root directories, thus avoiding the need for special-casing
4943 these and detecting them by examining the file-name format
4944 . retrieves more accurate attributes (e.g., non-zero size for
4945 some directories, esp. directories that are junction points)
4946 . correctly resolves "c:/..", "/.." and similar file names
4947 . avoids run-time penalties for 99% of use cases
4949 Plan A is always tried first, unless the user asked not to (but
4950 if the file is a symlink and we need to follow links, we try Plan
4951 A even if the user asked not to).
4953 If Plan A fails, we go to Plan B (below), where various
4954 potentially expensive techniques must be used to handle "special"
4955 files such as UNC volumes etc. */
4956 if (!(NILP (Vw32_get_true_file_attributes)
4957 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4958 /* Following symlinks requires getting the info by handle. */
4959 || (is_a_symlink && follow_symlinks))
4961 BY_HANDLE_FILE_INFORMATION info;
4963 if (is_a_symlink && !follow_symlinks)
4964 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4965 /* READ_CONTROL access rights are required to get security info
4966 by handle. But if the OS doesn't support security in the
4967 first place, we don't need to try. */
4968 if (is_windows_9x () != TRUE)
4969 access_rights |= READ_CONTROL;
4971 if (w32_unicode_filenames)
4973 filename_to_utf16 (name, name_w);
4974 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4975 file_flags, NULL);
4976 /* If CreateFile fails with READ_CONTROL, try again with
4977 zero as access rights. */
4978 if (fh == INVALID_HANDLE_VALUE && access_rights)
4979 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
4980 file_flags, NULL);
4982 else
4984 filename_to_ansi (name, name_a);
4985 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
4986 file_flags, NULL);
4987 if (fh == INVALID_HANDLE_VALUE && access_rights)
4988 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
4989 file_flags, NULL);
4991 if (fh == INVALID_HANDLE_VALUE)
4992 goto no_true_file_attributes;
4994 /* This is more accurate in terms of getting the correct number
4995 of links, but is quite slow (it is noticeable when Emacs is
4996 making a list of file name completions). */
4997 if (GetFileInformationByHandle (fh, &info))
4999 nlinks = info.nNumberOfLinks;
5000 /* Might as well use file index to fake inode values, but this
5001 is not guaranteed to be unique unless we keep a handle open
5002 all the time (even then there are situations where it is
5003 not unique). Reputedly, there are at most 48 bits of info
5004 (on NTFS, presumably less on FAT). */
5005 fake_inode = info.nFileIndexHigh;
5006 fake_inode <<= 32;
5007 fake_inode += info.nFileIndexLow;
5008 serialnum = info.dwVolumeSerialNumber;
5009 fs_high = info.nFileSizeHigh;
5010 fs_low = info.nFileSizeLow;
5011 ctime = info.ftCreationTime;
5012 atime = info.ftLastAccessTime;
5013 wtime = info.ftLastWriteTime;
5014 fattrs = info.dwFileAttributes;
5016 else
5018 /* We don't go to Plan B here, because it's not clear that
5019 it's a good idea. The only known use case where
5020 CreateFile succeeds, but GetFileInformationByHandle fails
5021 (with ERROR_INVALID_FUNCTION) is for character devices
5022 such as NUL, PRN, etc. For these, switching to Plan B is
5023 a net loss, because we lose the character device
5024 attribute returned by GetFileType below (FindFirstFile
5025 doesn't set that bit in the attributes), and the other
5026 fields don't make sense for character devices anyway.
5027 Emacs doesn't really care for non-file entities in the
5028 context of l?stat, so neither do we. */
5030 /* w32err is assigned so one could put a breakpoint here and
5031 examine its value, when GetFileInformationByHandle
5032 fails. */
5033 DWORD w32err = GetLastError ();
5035 switch (w32err)
5037 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5038 errno = ENOENT;
5039 return -1;
5043 /* Test for a symlink before testing for a directory, since
5044 symlinks to directories have the directory bit set, but we
5045 don't want them to appear as directories. */
5046 if (is_a_symlink && !follow_symlinks)
5047 buf->st_mode = S_IFLNK;
5048 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5049 buf->st_mode = S_IFDIR;
5050 else
5052 DWORD ftype = GetFileType (fh);
5054 switch (ftype)
5056 case FILE_TYPE_DISK:
5057 buf->st_mode = S_IFREG;
5058 break;
5059 case FILE_TYPE_PIPE:
5060 buf->st_mode = S_IFIFO;
5061 break;
5062 case FILE_TYPE_CHAR:
5063 case FILE_TYPE_UNKNOWN:
5064 default:
5065 buf->st_mode = S_IFCHR;
5068 /* We produce the fallback owner and group data, based on the
5069 current user that runs Emacs, in the following cases:
5071 . caller didn't request owner and group info
5072 . this is Windows 9X
5073 . getting security by handle failed, and we need to produce
5074 information for the target of a symlink (this is better
5075 than producing a potentially misleading info about the
5076 symlink itself)
5078 If getting security by handle fails, and we don't need to
5079 resolve symlinks, we try getting security by name. */
5080 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5081 get_file_owner_and_group (NULL, buf);
5082 else
5084 psd = get_file_security_desc_by_handle (fh);
5085 if (psd)
5087 get_file_owner_and_group (psd, buf);
5088 LocalFree (psd);
5090 else if (!(is_a_symlink && follow_symlinks))
5092 psd = get_file_security_desc_by_name (name);
5093 get_file_owner_and_group (psd, buf);
5094 xfree (psd);
5096 else
5097 get_file_owner_and_group (NULL, buf);
5099 CloseHandle (fh);
5101 else
5103 no_true_file_attributes:
5104 /* Plan B: Either getting a handle on the file failed, or the
5105 caller explicitly asked us to not bother making this
5106 information more accurate.
5108 Implementation note: In Plan B, we never bother to resolve
5109 symlinks, even if we got here because we tried Plan A and
5110 failed. That's because, even if the caller asked for extra
5111 precision by setting Vw32_get_true_file_attributes to t,
5112 resolving symlinks requires acquiring a file handle to the
5113 symlink, which we already know will fail. And if the user
5114 did not ask for extra precision, resolving symlinks will fly
5115 in the face of that request, since the user then wants the
5116 lightweight version of the code. */
5117 rootdir = (path >= save_name + len - 1
5118 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5120 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5121 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5122 if (IS_DIRECTORY_SEP (r[0])
5123 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5124 r[1] = r[2] = '\0';
5126 /* Note: If NAME is a symlink to the root of a UNC volume
5127 (i.e. "\\SERVER"), we will not detect that here, and we will
5128 return data about the symlink as result of FindFirst below.
5129 This is unfortunate, but that marginal use case does not
5130 justify a call to chase_symlinks which would impose a penalty
5131 on all the other use cases. (We get here for symlinks to
5132 roots of UNC volumes because CreateFile above fails for them,
5133 unlike with symlinks to root directories X:\ of drives.) */
5134 if (is_unc_volume (name))
5136 fattrs = unc_volume_file_attributes (name);
5137 if (fattrs == -1)
5138 return -1;
5140 ctime = atime = wtime = utc_base_ft;
5142 else if (rootdir)
5144 /* Make sure root directories end in a slash. */
5145 if (!IS_DIRECTORY_SEP (name[len-1]))
5146 strcpy (name + len, "\\");
5147 if (GetDriveType (name) < 2)
5149 errno = ENOENT;
5150 return -1;
5153 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5154 ctime = atime = wtime = utc_base_ft;
5156 else
5158 int have_wfd = -1;
5160 /* Make sure non-root directories do NOT end in a slash,
5161 otherwise FindFirstFile might fail. */
5162 if (IS_DIRECTORY_SEP (name[len-1]))
5163 name[len - 1] = 0;
5165 /* (This is hacky, but helps when doing file completions on
5166 network drives.) Optimize by using information available from
5167 active readdir if possible. */
5168 len = strlen (dir_pathname);
5169 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5170 len--;
5171 if (dir_find_handle != INVALID_HANDLE_VALUE
5172 && last_dir_find_data != -1
5173 && !(is_a_symlink && follow_symlinks)
5174 /* The 2 file-name comparisons below support only ASCII
5175 characters, and will lose (compare not equal) when
5176 the file names include non-ASCII characters that are
5177 the same but for the case. However, doing this
5178 properly involves: (a) converting both file names to
5179 UTF-16, (b) lower-casing both names using CharLowerW,
5180 and (c) comparing the results; this would be quite a
5181 bit slower, whereas Plan B is for users who want
5182 lightweight albeit inaccurate version of 'stat'. */
5183 && c_strncasecmp (save_name, dir_pathname, len) == 0
5184 && IS_DIRECTORY_SEP (name[len])
5185 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5187 have_wfd = last_dir_find_data;
5188 /* This was the last entry returned by readdir. */
5189 if (last_dir_find_data == DIR_FIND_DATA_W)
5190 wfd_w = dir_find_data_w;
5191 else
5192 wfd_a = dir_find_data_a;
5194 else
5196 logon_network_drive (name);
5198 if (w32_unicode_filenames)
5200 filename_to_utf16 (name, name_w);
5201 fh = FindFirstFileW (name_w, &wfd_w);
5202 have_wfd = DIR_FIND_DATA_W;
5204 else
5206 filename_to_ansi (name, name_a);
5207 /* If NAME includes characters not representable by
5208 the current ANSI codepage, filename_to_ansi
5209 usually replaces them with a '?'. We don't want
5210 to let FindFirstFileA interpret those as wildcards,
5211 and "succeed", returning us data from some random
5212 file in the same directory. */
5213 if (_mbspbrk (name_a, "?"))
5214 fh = INVALID_HANDLE_VALUE;
5215 else
5216 fh = FindFirstFileA (name_a, &wfd_a);
5217 have_wfd = DIR_FIND_DATA_A;
5219 if (fh == INVALID_HANDLE_VALUE)
5221 errno = ENOENT;
5222 return -1;
5224 FindClose (fh);
5226 /* Note: if NAME is a symlink, the information we get from
5227 FindFirstFile is for the symlink, not its target. */
5228 if (have_wfd == DIR_FIND_DATA_W)
5230 fattrs = wfd_w.dwFileAttributes;
5231 ctime = wfd_w.ftCreationTime;
5232 atime = wfd_w.ftLastAccessTime;
5233 wtime = wfd_w.ftLastWriteTime;
5234 fs_high = wfd_w.nFileSizeHigh;
5235 fs_low = wfd_w.nFileSizeLow;
5237 else
5239 fattrs = wfd_a.dwFileAttributes;
5240 ctime = wfd_a.ftCreationTime;
5241 atime = wfd_a.ftLastAccessTime;
5242 wtime = wfd_a.ftLastWriteTime;
5243 fs_high = wfd_a.nFileSizeHigh;
5244 fs_low = wfd_a.nFileSizeLow;
5246 fake_inode = 0;
5247 nlinks = 1;
5248 serialnum = volume_info.serialnum;
5250 if (is_a_symlink && !follow_symlinks)
5251 buf->st_mode = S_IFLNK;
5252 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5253 buf->st_mode = S_IFDIR;
5254 else
5255 buf->st_mode = S_IFREG;
5257 get_file_owner_and_group (NULL, buf);
5260 buf->st_ino = fake_inode;
5262 buf->st_dev = serialnum;
5263 buf->st_rdev = serialnum;
5265 buf->st_size = fs_high;
5266 buf->st_size <<= 32;
5267 buf->st_size += fs_low;
5268 buf->st_nlink = nlinks;
5270 /* Convert timestamps to Unix format. */
5271 buf->st_mtime = convert_time (wtime);
5272 buf->st_atime = convert_time (atime);
5273 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5274 buf->st_ctime = convert_time (ctime);
5275 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5277 /* determine rwx permissions */
5278 if (is_a_symlink && !follow_symlinks)
5279 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5280 else
5282 if (fattrs & FILE_ATTRIBUTE_READONLY)
5283 permission = S_IREAD;
5284 else
5285 permission = S_IREAD | S_IWRITE;
5287 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5288 permission |= S_IEXEC;
5289 else if (is_exec (name))
5290 permission |= S_IEXEC;
5293 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5295 return 0;
5299 stat (const char * path, struct stat * buf)
5301 return stat_worker (path, buf, 1);
5305 lstat (const char * path, struct stat * buf)
5307 return stat_worker (path, buf, 0);
5311 fstatat (int fd, char const *name, struct stat *st, int flags)
5313 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5314 This is good enough for the current usage in Emacs, but is fragile.
5316 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5317 Gnulib does this and can serve as a model. */
5318 char fullname[MAX_UTF8_PATH];
5320 if (fd != AT_FDCWD)
5322 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5324 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5325 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5326 < 0)
5328 errno = ENAMETOOLONG;
5329 return -1;
5331 name = fullname;
5334 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5337 /* Provide fstat and utime as well as stat for consistent handling of
5338 file timestamps. */
5340 fstat (int desc, struct stat * buf)
5342 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5343 BY_HANDLE_FILE_INFORMATION info;
5344 unsigned __int64 fake_inode;
5345 int permission;
5347 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5349 case FILE_TYPE_DISK:
5350 buf->st_mode = S_IFREG;
5351 if (!GetFileInformationByHandle (fh, &info))
5353 errno = EACCES;
5354 return -1;
5356 break;
5357 case FILE_TYPE_PIPE:
5358 buf->st_mode = S_IFIFO;
5359 goto non_disk;
5360 case FILE_TYPE_CHAR:
5361 case FILE_TYPE_UNKNOWN:
5362 default:
5363 buf->st_mode = S_IFCHR;
5364 non_disk:
5365 memset (&info, 0, sizeof (info));
5366 info.dwFileAttributes = 0;
5367 info.ftCreationTime = utc_base_ft;
5368 info.ftLastAccessTime = utc_base_ft;
5369 info.ftLastWriteTime = utc_base_ft;
5372 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5373 buf->st_mode = S_IFDIR;
5375 buf->st_nlink = info.nNumberOfLinks;
5376 /* Might as well use file index to fake inode values, but this
5377 is not guaranteed to be unique unless we keep a handle open
5378 all the time (even then there are situations where it is
5379 not unique). Reputedly, there are at most 48 bits of info
5380 (on NTFS, presumably less on FAT). */
5381 fake_inode = info.nFileIndexHigh;
5382 fake_inode <<= 32;
5383 fake_inode += info.nFileIndexLow;
5385 /* MSVC defines _ino_t to be short; other libc's might not. */
5386 if (sizeof (buf->st_ino) == 2)
5387 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5388 else
5389 buf->st_ino = fake_inode;
5391 /* If the caller so requested, get the true file owner and group.
5392 Otherwise, consider the file to belong to the current user. */
5393 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5394 get_file_owner_and_group (NULL, buf);
5395 else
5397 PSECURITY_DESCRIPTOR psd = NULL;
5399 psd = get_file_security_desc_by_handle (fh);
5400 if (psd)
5402 get_file_owner_and_group (psd, buf);
5403 LocalFree (psd);
5405 else
5406 get_file_owner_and_group (NULL, buf);
5409 buf->st_dev = info.dwVolumeSerialNumber;
5410 buf->st_rdev = info.dwVolumeSerialNumber;
5412 buf->st_size = info.nFileSizeHigh;
5413 buf->st_size <<= 32;
5414 buf->st_size += info.nFileSizeLow;
5416 /* Convert timestamps to Unix format. */
5417 buf->st_mtime = convert_time (info.ftLastWriteTime);
5418 buf->st_atime = convert_time (info.ftLastAccessTime);
5419 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5420 buf->st_ctime = convert_time (info.ftCreationTime);
5421 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5423 /* determine rwx permissions */
5424 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5425 permission = S_IREAD;
5426 else
5427 permission = S_IREAD | S_IWRITE;
5429 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5430 permission |= S_IEXEC;
5431 else
5433 #if 0 /* no way of knowing the filename */
5434 char * p = strrchr (name, '.');
5435 if (p != NULL &&
5436 (xstrcasecmp (p, ".exe") == 0 ||
5437 xstrcasecmp (p, ".com") == 0 ||
5438 xstrcasecmp (p, ".bat") == 0 ||
5439 xstrcasecmp (p, ".cmd") == 0))
5440 permission |= S_IEXEC;
5441 #endif
5444 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5446 return 0;
5449 /* A version of 'utime' which handles directories as well as
5450 files. */
5453 utime (const char *name, struct utimbuf *times)
5455 struct utimbuf deftime;
5456 HANDLE fh;
5457 FILETIME mtime;
5458 FILETIME atime;
5460 if (times == NULL)
5462 deftime.modtime = deftime.actime = time (NULL);
5463 times = &deftime;
5466 if (w32_unicode_filenames)
5468 wchar_t name_utf16[MAX_PATH];
5470 if (filename_to_utf16 (name, name_utf16) != 0)
5471 return -1; /* errno set by filename_to_utf16 */
5473 /* Need write access to set times. */
5474 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5475 /* If NAME specifies a directory, FILE_SHARE_DELETE
5476 allows other processes to delete files inside it,
5477 while we have the directory open. */
5478 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5479 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5481 else
5483 char name_ansi[MAX_PATH];
5485 if (filename_to_ansi (name, name_ansi) != 0)
5486 return -1; /* errno set by filename_to_ansi */
5488 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5489 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5490 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5492 if (fh != INVALID_HANDLE_VALUE)
5494 convert_from_time_t (times->actime, &atime);
5495 convert_from_time_t (times->modtime, &mtime);
5496 if (!SetFileTime (fh, NULL, &atime, &mtime))
5498 CloseHandle (fh);
5499 errno = EACCES;
5500 return -1;
5502 CloseHandle (fh);
5504 else
5506 DWORD err = GetLastError ();
5508 switch (err)
5510 case ERROR_FILE_NOT_FOUND:
5511 case ERROR_PATH_NOT_FOUND:
5512 case ERROR_INVALID_DRIVE:
5513 case ERROR_BAD_NETPATH:
5514 case ERROR_DEV_NOT_EXIST:
5515 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5516 file name includes ?s, i.e. translation to ANSI failed. */
5517 case ERROR_INVALID_NAME:
5518 errno = ENOENT;
5519 break;
5520 case ERROR_TOO_MANY_OPEN_FILES:
5521 errno = ENFILE;
5522 break;
5523 case ERROR_ACCESS_DENIED:
5524 case ERROR_SHARING_VIOLATION:
5525 errno = EACCES;
5526 break;
5527 default:
5528 errno = EINVAL;
5529 break;
5531 return -1;
5533 return 0;
5537 sys_umask (int mode)
5539 static int current_mask;
5540 int retval, arg = 0;
5542 /* The only bit we really support is the write bit. Files are
5543 always readable on MS-Windows, and the execute bit does not exist
5544 at all. */
5545 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5546 to prevent access by other users on NTFS. */
5547 if ((mode & S_IWRITE) != 0)
5548 arg |= S_IWRITE;
5550 retval = _umask (arg);
5551 /* Merge into the return value the bits they've set the last time,
5552 which msvcrt.dll ignores and never returns. Emacs insists on its
5553 notion of mask being identical to what we return. */
5554 retval |= (current_mask & ~S_IWRITE);
5555 current_mask = mode;
5557 return retval;
5561 /* Symlink-related functions. */
5562 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5563 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5564 #endif
5567 symlink (char const *filename, char const *linkname)
5569 char linkfn[MAX_UTF8_PATH], *tgtfn;
5570 DWORD flags = 0;
5571 int dir_access, filename_ends_in_slash;
5573 /* Diagnostics follows Posix as much as possible. */
5574 if (filename == NULL || linkname == NULL)
5576 errno = EFAULT;
5577 return -1;
5579 if (!*filename)
5581 errno = ENOENT;
5582 return -1;
5584 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5586 errno = ENAMETOOLONG;
5587 return -1;
5590 strcpy (linkfn, map_w32_filename (linkname, NULL));
5591 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5593 errno = EPERM;
5594 return -1;
5597 /* Note: since empty FILENAME was already rejected, we can safely
5598 refer to FILENAME[1]. */
5599 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5601 /* Non-absolute FILENAME is understood as being relative to
5602 LINKNAME's directory. We need to prepend that directory to
5603 FILENAME to get correct results from faccessat below, since
5604 otherwise it will interpret FILENAME relative to the
5605 directory where the Emacs process runs. Note that
5606 make-symbolic-link always makes sure LINKNAME is a fully
5607 expanded file name. */
5608 char tem[MAX_UTF8_PATH];
5609 char *p = linkfn + strlen (linkfn);
5611 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5612 p--;
5613 if (p > linkfn)
5614 strncpy (tem, linkfn, p - linkfn);
5615 strcpy (tem + (p - linkfn), filename);
5616 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5618 else
5619 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5621 /* Since Windows distinguishes between symlinks to directories and
5622 to files, we provide a kludgy feature: if FILENAME doesn't
5623 exist, but ends in a slash, we create a symlink to directory. If
5624 FILENAME exists and is a directory, we always create a symlink to
5625 directory. */
5626 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5627 if (dir_access == 0 || filename_ends_in_slash)
5628 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5630 tgtfn = (char *)map_w32_filename (filename, NULL);
5631 if (filename_ends_in_slash)
5632 tgtfn[strlen (tgtfn) - 1] = '\0';
5634 errno = 0;
5635 if (!create_symbolic_link (linkfn, tgtfn, flags))
5637 /* ENOSYS is set by create_symbolic_link, when it detects that
5638 the OS doesn't support the CreateSymbolicLink API. */
5639 if (errno != ENOSYS)
5641 DWORD w32err = GetLastError ();
5643 switch (w32err)
5645 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5646 TGTFN point to the same file name, go figure. */
5647 case ERROR_SUCCESS:
5648 case ERROR_FILE_EXISTS:
5649 errno = EEXIST;
5650 break;
5651 case ERROR_ACCESS_DENIED:
5652 errno = EACCES;
5653 break;
5654 case ERROR_FILE_NOT_FOUND:
5655 case ERROR_PATH_NOT_FOUND:
5656 case ERROR_BAD_NETPATH:
5657 case ERROR_INVALID_REPARSE_DATA:
5658 errno = ENOENT;
5659 break;
5660 case ERROR_DIRECTORY:
5661 errno = EISDIR;
5662 break;
5663 case ERROR_PRIVILEGE_NOT_HELD:
5664 case ERROR_NOT_ALL_ASSIGNED:
5665 errno = EPERM;
5666 break;
5667 case ERROR_DISK_FULL:
5668 errno = ENOSPC;
5669 break;
5670 default:
5671 errno = EINVAL;
5672 break;
5675 return -1;
5677 return 0;
5680 /* A quick inexpensive test of whether FILENAME identifies a file that
5681 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5682 must already be in the normalized form returned by
5683 map_w32_filename. If the symlink is to a directory, the
5684 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5686 Note: for repeated operations on many files, it is best to test
5687 whether the underlying volume actually supports symlinks, by
5688 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5689 avoid the call to this function if it doesn't. That's because the
5690 call to GetFileAttributes takes a non-negligible time, especially
5691 on non-local or removable filesystems. See stat_worker for an
5692 example of how to do that. */
5693 static int
5694 is_symlink (const char *filename)
5696 DWORD attrs;
5697 wchar_t filename_w[MAX_PATH];
5698 char filename_a[MAX_PATH];
5699 WIN32_FIND_DATAW wfdw;
5700 WIN32_FIND_DATAA wfda;
5701 HANDLE fh;
5702 int attrs_mean_symlink;
5704 if (w32_unicode_filenames)
5706 filename_to_utf16 (filename, filename_w);
5707 attrs = GetFileAttributesW (filename_w);
5709 else
5711 filename_to_ansi (filename, filename_a);
5712 attrs = GetFileAttributesA (filename_a);
5714 if (attrs == -1)
5716 DWORD w32err = GetLastError ();
5718 switch (w32err)
5720 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5721 break;
5722 case ERROR_ACCESS_DENIED:
5723 errno = EACCES;
5724 break;
5725 case ERROR_FILE_NOT_FOUND:
5726 case ERROR_PATH_NOT_FOUND:
5727 default:
5728 errno = ENOENT;
5729 break;
5731 return 0;
5733 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5734 return 0;
5735 logon_network_drive (filename);
5736 if (w32_unicode_filenames)
5738 fh = FindFirstFileW (filename_w, &wfdw);
5739 attrs_mean_symlink =
5740 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5741 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5742 if (attrs_mean_symlink)
5743 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5745 else if (_mbspbrk (filename_a, "?"))
5747 /* filename_to_ansi failed to convert the file name. */
5748 errno = ENOENT;
5749 return 0;
5751 else
5753 fh = FindFirstFileA (filename_a, &wfda);
5754 attrs_mean_symlink =
5755 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5756 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5757 if (attrs_mean_symlink)
5758 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5760 if (fh == INVALID_HANDLE_VALUE)
5761 return 0;
5762 FindClose (fh);
5763 return attrs_mean_symlink;
5766 /* If NAME identifies a symbolic link, copy into BUF the file name of
5767 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5768 null-terminate the target name, even if it fits. Return the number
5769 of bytes copied, or -1 if NAME is not a symlink or any error was
5770 encountered while resolving it. The file name copied into BUF is
5771 encoded in the current ANSI codepage. */
5772 ssize_t
5773 readlink (const char *name, char *buf, size_t buf_size)
5775 const char *path;
5776 TOKEN_PRIVILEGES privs;
5777 int restore_privs = 0;
5778 HANDLE sh;
5779 ssize_t retval;
5780 char resolved[MAX_UTF8_PATH];
5782 if (name == NULL)
5784 errno = EFAULT;
5785 return -1;
5787 if (!*name)
5789 errno = ENOENT;
5790 return -1;
5793 path = map_w32_filename (name, NULL);
5795 if (strlen (path) > MAX_UTF8_PATH)
5797 errno = ENAMETOOLONG;
5798 return -1;
5801 errno = 0;
5802 if (is_windows_9x () == TRUE
5803 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5804 || !is_symlink (path))
5806 if (!errno)
5807 errno = EINVAL; /* not a symlink */
5808 return -1;
5811 /* Done with simple tests, now we're in for some _real_ work. */
5812 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5813 restore_privs = 1;
5814 /* Implementation note: From here and onward, don't return early,
5815 since that will fail to restore the original set of privileges of
5816 the calling thread. */
5818 retval = -1; /* not too optimistic, are we? */
5820 /* Note: In the next call to CreateFile, we use zero as the 2nd
5821 argument because, when the symlink is a hidden/system file,
5822 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5823 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5824 and directory symlinks. */
5825 if (w32_unicode_filenames)
5827 wchar_t path_w[MAX_PATH];
5829 filename_to_utf16 (path, path_w);
5830 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5831 FILE_FLAG_OPEN_REPARSE_POINT
5832 | FILE_FLAG_BACKUP_SEMANTICS,
5833 NULL);
5835 else
5837 char path_a[MAX_PATH];
5839 filename_to_ansi (path, path_a);
5840 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5841 FILE_FLAG_OPEN_REPARSE_POINT
5842 | FILE_FLAG_BACKUP_SEMANTICS,
5843 NULL);
5845 if (sh != INVALID_HANDLE_VALUE)
5847 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5848 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5849 DWORD retbytes;
5851 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5852 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5853 &retbytes, NULL))
5854 errno = EIO;
5855 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5856 errno = EINVAL;
5857 else
5859 /* Copy the link target name, in wide characters, from
5860 reparse_data, then convert it to multibyte encoding in
5861 the current locale's codepage. */
5862 WCHAR *lwname;
5863 size_t lname_size;
5864 USHORT lwname_len =
5865 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5866 WCHAR *lwname_src =
5867 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5868 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5869 size_t size_to_copy = buf_size;
5871 /* According to MSDN, PrintNameLength does not include the
5872 terminating null character. */
5873 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5874 memcpy (lwname, lwname_src, lwname_len);
5875 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5876 filename_from_utf16 (lwname, resolved);
5877 dostounix_filename (resolved);
5878 lname_size = strlen (resolved) + 1;
5879 if (lname_size <= buf_size)
5880 size_to_copy = lname_size;
5881 strncpy (buf, resolved, size_to_copy);
5882 /* Success! */
5883 retval = size_to_copy;
5885 CloseHandle (sh);
5887 else
5889 /* CreateFile failed. */
5890 DWORD w32err2 = GetLastError ();
5892 switch (w32err2)
5894 case ERROR_FILE_NOT_FOUND:
5895 case ERROR_PATH_NOT_FOUND:
5896 errno = ENOENT;
5897 break;
5898 case ERROR_ACCESS_DENIED:
5899 case ERROR_TOO_MANY_OPEN_FILES:
5900 errno = EACCES;
5901 break;
5902 default:
5903 errno = EPERM;
5904 break;
5907 if (restore_privs)
5909 restore_privilege (&privs);
5910 revert_to_self ();
5913 return retval;
5916 ssize_t
5917 readlinkat (int fd, char const *name, char *buffer,
5918 size_t buffer_size)
5920 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5921 as in fstatat. FIXME: Add proper support for readlinkat. */
5922 char fullname[MAX_UTF8_PATH];
5924 if (fd != AT_FDCWD)
5926 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5927 < 0)
5929 errno = ENAMETOOLONG;
5930 return -1;
5932 name = fullname;
5935 return readlink (name, buffer, buffer_size);
5938 /* If FILE is a symlink, return its target (stored in a static
5939 buffer); otherwise return FILE.
5941 This function repeatedly resolves symlinks in the last component of
5942 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5943 until it arrives at a file whose last component is not a symlink,
5944 or some error occurs. It returns the target of the last
5945 successfully resolved symlink in the chain. If it succeeds to
5946 resolve even a single symlink, the value returned is an absolute
5947 file name with backslashes (result of GetFullPathName). By
5948 contrast, if the original FILE is returned, it is unaltered.
5950 Note: This function can set errno even if it succeeds.
5952 Implementation note: we only resolve the last portion ("basename")
5953 of the argument FILE and of each following file in the chain,
5954 disregarding any possible symlinks in its leading directories.
5955 This is because Windows system calls and library functions
5956 transparently resolve symlinks in leading directories and return
5957 correct information, as long as the basename is not a symlink. */
5958 static char *
5959 chase_symlinks (const char *file)
5961 static char target[MAX_UTF8_PATH];
5962 char link[MAX_UTF8_PATH];
5963 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5964 char target_a[MAX_PATH], link_a[MAX_PATH];
5965 ssize_t res, link_len;
5966 int loop_count = 0;
5968 if (is_windows_9x () == TRUE || !is_symlink (file))
5969 return (char *)file;
5971 if (w32_unicode_filenames)
5973 wchar_t file_w[MAX_PATH];
5975 filename_to_utf16 (file, file_w);
5976 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5977 return (char *)file;
5978 filename_from_utf16 (link_w, link);
5980 else
5982 char file_a[MAX_PATH];
5984 filename_to_ansi (file, file_a);
5985 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
5986 return (char *)file;
5987 filename_from_ansi (link_a, link);
5989 link_len = strlen (link);
5991 target[0] = '\0';
5992 do {
5994 /* Remove trailing slashes, as we want to resolve the last
5995 non-trivial part of the link name. */
5996 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5997 link[link_len--] = '\0';
5999 res = readlink (link, target, MAX_UTF8_PATH);
6000 if (res > 0)
6002 target[res] = '\0';
6003 if (!(IS_DEVICE_SEP (target[1])
6004 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6006 /* Target is relative. Append it to the directory part of
6007 the symlink, then copy the result back to target. */
6008 char *p = link + link_len;
6010 while (p > link && !IS_ANY_SEP (p[-1]))
6011 p--;
6012 strcpy (p, target);
6013 strcpy (target, link);
6015 /* Resolve any "." and ".." to get a fully-qualified file name
6016 in link[] again. */
6017 if (w32_unicode_filenames)
6019 filename_to_utf16 (target, target_w);
6020 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6021 if (link_len > 0)
6022 filename_from_utf16 (link_w, link);
6024 else
6026 filename_to_ansi (target, target_a);
6027 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6028 if (link_len > 0)
6029 filename_from_ansi (link_a, link);
6031 link_len = strlen (link);
6033 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6035 if (loop_count > 100)
6036 errno = ELOOP;
6038 if (target[0] == '\0') /* not a single call to readlink succeeded */
6039 return (char *)file;
6040 return target;
6044 /* Posix ACL emulation. */
6047 acl_valid (acl_t acl)
6049 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6052 char *
6053 acl_to_text (acl_t acl, ssize_t *size)
6055 LPTSTR str_acl;
6056 SECURITY_INFORMATION flags =
6057 OWNER_SECURITY_INFORMATION |
6058 GROUP_SECURITY_INFORMATION |
6059 DACL_SECURITY_INFORMATION;
6060 char *retval = NULL;
6061 ULONG local_size;
6062 int e = errno;
6064 errno = 0;
6066 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6068 errno = e;
6069 /* We don't want to mix heaps, so we duplicate the string in our
6070 heap and free the one allocated by the API. */
6071 retval = xstrdup (str_acl);
6072 if (size)
6073 *size = local_size;
6074 LocalFree (str_acl);
6076 else if (errno != ENOTSUP)
6077 errno = EINVAL;
6079 return retval;
6082 acl_t
6083 acl_from_text (const char *acl_str)
6085 PSECURITY_DESCRIPTOR psd, retval = NULL;
6086 ULONG sd_size;
6087 int e = errno;
6089 errno = 0;
6091 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6093 errno = e;
6094 retval = xmalloc (sd_size);
6095 memcpy (retval, psd, sd_size);
6096 LocalFree (psd);
6098 else if (errno != ENOTSUP)
6099 errno = EINVAL;
6101 return retval;
6105 acl_free (void *ptr)
6107 xfree (ptr);
6108 return 0;
6111 acl_t
6112 acl_get_file (const char *fname, acl_type_t type)
6114 PSECURITY_DESCRIPTOR psd = NULL;
6115 const char *filename;
6117 if (type == ACL_TYPE_ACCESS)
6119 DWORD sd_len, err;
6120 SECURITY_INFORMATION si =
6121 OWNER_SECURITY_INFORMATION |
6122 GROUP_SECURITY_INFORMATION |
6123 DACL_SECURITY_INFORMATION ;
6124 int e = errno;
6126 filename = map_w32_filename (fname, NULL);
6127 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6128 fname = chase_symlinks (filename);
6129 else
6130 fname = filename;
6132 errno = 0;
6133 if (!get_file_security (fname, si, psd, 0, &sd_len)
6134 && errno != ENOTSUP)
6136 err = GetLastError ();
6137 if (err == ERROR_INSUFFICIENT_BUFFER)
6139 psd = xmalloc (sd_len);
6140 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6142 xfree (psd);
6143 errno = EIO;
6144 psd = NULL;
6147 else if (err == ERROR_FILE_NOT_FOUND
6148 || err == ERROR_PATH_NOT_FOUND
6149 /* ERROR_INVALID_NAME is what we get if
6150 w32-unicode-filenames is nil and the file cannot
6151 be encoded in the current ANSI codepage. */
6152 || err == ERROR_INVALID_NAME)
6153 errno = ENOENT;
6154 else
6155 errno = EIO;
6157 else if (!errno)
6158 errno = e;
6160 else if (type != ACL_TYPE_DEFAULT)
6161 errno = EINVAL;
6163 return psd;
6167 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6169 TOKEN_PRIVILEGES old1, old2;
6170 DWORD err;
6171 int st = 0, retval = -1;
6172 SECURITY_INFORMATION flags = 0;
6173 PSID psidOwner, psidGroup;
6174 PACL pacl;
6175 BOOL dflt;
6176 BOOL dacl_present;
6177 int e;
6178 const char *filename;
6180 if (acl_valid (acl) != 0
6181 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6183 errno = EINVAL;
6184 return -1;
6187 if (type == ACL_TYPE_DEFAULT)
6189 errno = ENOSYS;
6190 return -1;
6193 filename = map_w32_filename (fname, NULL);
6194 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6195 fname = chase_symlinks (filename);
6196 else
6197 fname = filename;
6199 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6200 &dflt)
6201 && psidOwner)
6202 flags |= OWNER_SECURITY_INFORMATION;
6203 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6204 &dflt)
6205 && psidGroup)
6206 flags |= GROUP_SECURITY_INFORMATION;
6207 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6208 &pacl, &dflt)
6209 && dacl_present)
6210 flags |= DACL_SECURITY_INFORMATION;
6211 if (!flags)
6212 return 0;
6214 /* According to KB-245153, setting the owner will succeed if either:
6215 (1) the caller is the user who will be the new owner, and has the
6216 SE_TAKE_OWNERSHIP privilege, or
6217 (2) the caller has the SE_RESTORE privilege, in which case she can
6218 set any valid user or group as the owner
6220 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6221 privileges, and disregard any failures in obtaining them. If
6222 these privileges cannot be obtained, and do not already exist in
6223 the calling thread's security token, this function could fail
6224 with EPERM. */
6225 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6226 st++;
6227 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6228 st++;
6230 e = errno;
6231 errno = 0;
6232 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6233 DACL inheritance is involved, but it seems to preserve ownership
6234 better than SetNamedSecurityInfo, which is important e.g., in
6235 copy-file. */
6236 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6238 err = GetLastError ();
6240 if (errno != ENOTSUP)
6241 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6242 psidOwner, psidGroup, pacl, NULL);
6244 else
6245 err = ERROR_SUCCESS;
6246 if (err != ERROR_SUCCESS)
6248 if (errno == ENOTSUP)
6250 else if (err == ERROR_INVALID_OWNER
6251 || err == ERROR_NOT_ALL_ASSIGNED
6252 || err == ERROR_ACCESS_DENIED)
6254 /* Maybe the requested ACL and the one the file already has
6255 are identical, in which case we can silently ignore the
6256 failure. (And no, Windows doesn't.) */
6257 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6259 errno = EPERM;
6260 if (current_acl)
6262 char *acl_from = acl_to_text (current_acl, NULL);
6263 char *acl_to = acl_to_text (acl, NULL);
6265 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6267 retval = 0;
6268 errno = e;
6270 if (acl_from)
6271 acl_free (acl_from);
6272 if (acl_to)
6273 acl_free (acl_to);
6274 acl_free (current_acl);
6277 else if (err == ERROR_FILE_NOT_FOUND
6278 || err == ERROR_PATH_NOT_FOUND
6279 /* ERROR_INVALID_NAME is what we get if
6280 w32-unicode-filenames is nil and the file cannot be
6281 encoded in the current ANSI codepage. */
6282 || err == ERROR_INVALID_NAME)
6283 errno = ENOENT;
6284 else
6285 errno = EACCES;
6287 else
6289 retval = 0;
6290 errno = e;
6293 if (st)
6295 if (st >= 2)
6296 restore_privilege (&old2);
6297 restore_privilege (&old1);
6298 revert_to_self ();
6301 return retval;
6305 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6306 have a fixed max size for file names, so we don't need the kind of
6307 alloc/malloc/realloc dance the gnulib version does. We also don't
6308 support FD-relative symlinks. */
6309 char *
6310 careadlinkat (int fd, char const *filename,
6311 char *buffer, size_t buffer_size,
6312 struct allocator const *alloc,
6313 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6315 char linkname[MAX_UTF8_PATH];
6316 ssize_t link_size;
6318 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6320 if (link_size > 0)
6322 char *retval = buffer;
6324 linkname[link_size++] = '\0';
6325 if (link_size > buffer_size)
6326 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6327 if (retval)
6328 memcpy (retval, linkname, link_size);
6330 return retval;
6332 return NULL;
6336 w32_copy_file (const char *from, const char *to,
6337 int keep_time, int preserve_ownership, int copy_acls)
6339 acl_t acl = NULL;
6340 BOOL copy_result;
6341 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6342 char from_a[MAX_PATH], to_a[MAX_PATH];
6344 /* We ignore preserve_ownership for now. */
6345 preserve_ownership = preserve_ownership;
6347 if (copy_acls)
6349 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6350 if (acl == NULL && acl_errno_valid (errno))
6351 return -2;
6353 if (w32_unicode_filenames)
6355 filename_to_utf16 (from, from_w);
6356 filename_to_utf16 (to, to_w);
6357 copy_result = CopyFileW (from_w, to_w, FALSE);
6359 else
6361 filename_to_ansi (from, from_a);
6362 filename_to_ansi (to, to_a);
6363 copy_result = CopyFileA (from_a, to_a, FALSE);
6365 if (!copy_result)
6367 /* CopyFile doesn't set errno when it fails. By far the most
6368 "popular" reason is that the target is read-only. */
6369 DWORD err = GetLastError ();
6371 switch (err)
6373 case ERROR_FILE_NOT_FOUND:
6374 errno = ENOENT;
6375 break;
6376 case ERROR_ACCESS_DENIED:
6377 errno = EACCES;
6378 break;
6379 case ERROR_ENCRYPTION_FAILED:
6380 errno = EIO;
6381 break;
6382 default:
6383 errno = EPERM;
6384 break;
6387 if (acl)
6388 acl_free (acl);
6389 return -1;
6391 /* CopyFile retains the timestamp by default. However, see
6392 "Community Additions" for CopyFile: it sounds like that is not
6393 entirely true. Testing on Windows XP confirms that modified time
6394 is copied, but creation and last-access times are not.
6395 FIXME? */
6396 else if (!keep_time)
6398 struct timespec now;
6399 DWORD attributes;
6401 if (w32_unicode_filenames)
6403 /* Ensure file is writable while its times are set. */
6404 attributes = GetFileAttributesW (to_w);
6405 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6406 now = current_timespec ();
6407 if (set_file_times (-1, to, now, now))
6409 /* Restore original attributes. */
6410 SetFileAttributesW (to_w, attributes);
6411 if (acl)
6412 acl_free (acl);
6413 return -3;
6415 /* Restore original attributes. */
6416 SetFileAttributesW (to_w, attributes);
6418 else
6420 attributes = GetFileAttributesA (to_a);
6421 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6422 now = current_timespec ();
6423 if (set_file_times (-1, to, now, now))
6425 SetFileAttributesA (to_a, attributes);
6426 if (acl)
6427 acl_free (acl);
6428 return -3;
6430 SetFileAttributesA (to_a, attributes);
6433 if (acl != NULL)
6435 bool fail =
6436 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6437 acl_free (acl);
6438 if (fail && acl_errno_valid (errno))
6439 return -4;
6442 return 0;
6446 /* Support for browsing other processes and their attributes. See
6447 process.c for the Lisp bindings. */
6449 /* Helper wrapper functions. */
6451 static HANDLE WINAPI
6452 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6454 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6456 if (g_b_init_create_toolhelp32_snapshot == 0)
6458 g_b_init_create_toolhelp32_snapshot = 1;
6459 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6460 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6461 "CreateToolhelp32Snapshot");
6463 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6465 return INVALID_HANDLE_VALUE;
6467 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6470 static BOOL WINAPI
6471 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6473 static Process32First_Proc s_pfn_Process32_First = NULL;
6475 if (g_b_init_process32_first == 0)
6477 g_b_init_process32_first = 1;
6478 s_pfn_Process32_First = (Process32First_Proc)
6479 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6480 "Process32First");
6482 if (s_pfn_Process32_First == NULL)
6484 return FALSE;
6486 return (s_pfn_Process32_First (hSnapshot, lppe));
6489 static BOOL WINAPI
6490 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6492 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6494 if (g_b_init_process32_next == 0)
6496 g_b_init_process32_next = 1;
6497 s_pfn_Process32_Next = (Process32Next_Proc)
6498 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6499 "Process32Next");
6501 if (s_pfn_Process32_Next == NULL)
6503 return FALSE;
6505 return (s_pfn_Process32_Next (hSnapshot, lppe));
6508 static BOOL WINAPI
6509 open_thread_token (HANDLE ThreadHandle,
6510 DWORD DesiredAccess,
6511 BOOL OpenAsSelf,
6512 PHANDLE TokenHandle)
6514 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6515 HMODULE hm_advapi32 = NULL;
6516 if (is_windows_9x () == TRUE)
6518 SetLastError (ERROR_NOT_SUPPORTED);
6519 return FALSE;
6521 if (g_b_init_open_thread_token == 0)
6523 g_b_init_open_thread_token = 1;
6524 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6525 s_pfn_Open_Thread_Token =
6526 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6528 if (s_pfn_Open_Thread_Token == NULL)
6530 SetLastError (ERROR_NOT_SUPPORTED);
6531 return FALSE;
6533 return (
6534 s_pfn_Open_Thread_Token (
6535 ThreadHandle,
6536 DesiredAccess,
6537 OpenAsSelf,
6538 TokenHandle)
6542 static BOOL WINAPI
6543 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6545 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6546 HMODULE hm_advapi32 = NULL;
6547 if (is_windows_9x () == TRUE)
6549 return FALSE;
6551 if (g_b_init_impersonate_self == 0)
6553 g_b_init_impersonate_self = 1;
6554 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6555 s_pfn_Impersonate_Self =
6556 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6558 if (s_pfn_Impersonate_Self == NULL)
6560 return FALSE;
6562 return s_pfn_Impersonate_Self (ImpersonationLevel);
6565 static BOOL WINAPI
6566 revert_to_self (void)
6568 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6569 HMODULE hm_advapi32 = NULL;
6570 if (is_windows_9x () == TRUE)
6572 return FALSE;
6574 if (g_b_init_revert_to_self == 0)
6576 g_b_init_revert_to_self = 1;
6577 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6578 s_pfn_Revert_To_Self =
6579 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6581 if (s_pfn_Revert_To_Self == NULL)
6583 return FALSE;
6585 return s_pfn_Revert_To_Self ();
6588 static BOOL WINAPI
6589 get_process_memory_info (HANDLE h_proc,
6590 PPROCESS_MEMORY_COUNTERS mem_counters,
6591 DWORD bufsize)
6593 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6594 HMODULE hm_psapi = NULL;
6595 if (is_windows_9x () == TRUE)
6597 return FALSE;
6599 if (g_b_init_get_process_memory_info == 0)
6601 g_b_init_get_process_memory_info = 1;
6602 hm_psapi = LoadLibrary ("Psapi.dll");
6603 if (hm_psapi)
6604 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6605 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6607 if (s_pfn_Get_Process_Memory_Info == NULL)
6609 return FALSE;
6611 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6614 static BOOL WINAPI
6615 get_process_working_set_size (HANDLE h_proc,
6616 PSIZE_T minrss,
6617 PSIZE_T maxrss)
6619 static GetProcessWorkingSetSize_Proc
6620 s_pfn_Get_Process_Working_Set_Size = NULL;
6622 if (is_windows_9x () == TRUE)
6624 return FALSE;
6626 if (g_b_init_get_process_working_set_size == 0)
6628 g_b_init_get_process_working_set_size = 1;
6629 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6630 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6631 "GetProcessWorkingSetSize");
6633 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6635 return FALSE;
6637 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6640 static BOOL WINAPI
6641 global_memory_status (MEMORYSTATUS *buf)
6643 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6645 if (is_windows_9x () == TRUE)
6647 return FALSE;
6649 if (g_b_init_global_memory_status == 0)
6651 g_b_init_global_memory_status = 1;
6652 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6653 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6654 "GlobalMemoryStatus");
6656 if (s_pfn_Global_Memory_Status == NULL)
6658 return FALSE;
6660 return s_pfn_Global_Memory_Status (buf);
6663 static BOOL WINAPI
6664 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6666 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6668 if (is_windows_9x () == TRUE)
6670 return FALSE;
6672 if (g_b_init_global_memory_status_ex == 0)
6674 g_b_init_global_memory_status_ex = 1;
6675 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6676 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6677 "GlobalMemoryStatusEx");
6679 if (s_pfn_Global_Memory_Status_Ex == NULL)
6681 return FALSE;
6683 return s_pfn_Global_Memory_Status_Ex (buf);
6686 Lisp_Object
6687 list_system_processes (void)
6689 Lisp_Object proclist = Qnil;
6690 HANDLE h_snapshot;
6692 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6694 if (h_snapshot != INVALID_HANDLE_VALUE)
6696 PROCESSENTRY32 proc_entry;
6697 DWORD proc_id;
6698 BOOL res;
6700 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6701 for (res = process32_first (h_snapshot, &proc_entry); res;
6702 res = process32_next (h_snapshot, &proc_entry))
6704 proc_id = proc_entry.th32ProcessID;
6705 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6708 CloseHandle (h_snapshot);
6709 proclist = Fnreverse (proclist);
6712 return proclist;
6715 static int
6716 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6718 TOKEN_PRIVILEGES priv;
6719 DWORD priv_size = sizeof (priv);
6720 DWORD opriv_size = sizeof (*old_priv);
6721 HANDLE h_token = NULL;
6722 HANDLE h_thread = GetCurrentThread ();
6723 int ret_val = 0;
6724 BOOL res;
6726 res = open_thread_token (h_thread,
6727 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6728 FALSE, &h_token);
6729 if (!res && GetLastError () == ERROR_NO_TOKEN)
6731 if (impersonate_self (SecurityImpersonation))
6732 res = open_thread_token (h_thread,
6733 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6734 FALSE, &h_token);
6736 if (res)
6738 priv.PrivilegeCount = 1;
6739 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6740 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6741 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6742 old_priv, &opriv_size)
6743 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6744 ret_val = 1;
6746 if (h_token)
6747 CloseHandle (h_token);
6749 return ret_val;
6752 static int
6753 restore_privilege (TOKEN_PRIVILEGES *priv)
6755 DWORD priv_size = sizeof (*priv);
6756 HANDLE h_token = NULL;
6757 int ret_val = 0;
6759 if (open_thread_token (GetCurrentThread (),
6760 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6761 FALSE, &h_token))
6763 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6764 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6765 ret_val = 1;
6767 if (h_token)
6768 CloseHandle (h_token);
6770 return ret_val;
6773 static Lisp_Object
6774 ltime (ULONGLONG time_100ns)
6776 ULONGLONG time_sec = time_100ns / 10000000;
6777 int subsec = time_100ns % 10000000;
6778 return list4i (time_sec >> 16, time_sec & 0xffff,
6779 subsec / 10, subsec % 10 * 100000);
6782 #define U64_TO_LISP_TIME(time) ltime (time)
6784 static int
6785 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6786 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6787 double *pcpu)
6789 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6790 ULONGLONG tem1, tem2, tem3, tem;
6792 if (!h_proc
6793 || !get_process_times_fn
6794 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6795 &ft_kernel, &ft_user))
6796 return 0;
6798 GetSystemTimeAsFileTime (&ft_current);
6800 FILETIME_TO_U64 (tem1, ft_kernel);
6801 *stime = U64_TO_LISP_TIME (tem1);
6803 FILETIME_TO_U64 (tem2, ft_user);
6804 *utime = U64_TO_LISP_TIME (tem2);
6806 tem3 = tem1 + tem2;
6807 *ttime = U64_TO_LISP_TIME (tem3);
6809 FILETIME_TO_U64 (tem, ft_creation);
6810 /* Process no 4 (System) returns zero creation time. */
6811 if (tem)
6812 tem -= utc_base;
6813 *ctime = U64_TO_LISP_TIME (tem);
6815 if (tem)
6817 FILETIME_TO_U64 (tem3, ft_current);
6818 tem = (tem3 - utc_base) - tem;
6820 *etime = U64_TO_LISP_TIME (tem);
6822 if (tem)
6824 *pcpu = 100.0 * (tem1 + tem2) / tem;
6825 if (*pcpu > 100)
6826 *pcpu = 100.0;
6828 else
6829 *pcpu = 0;
6831 return 1;
6834 Lisp_Object
6835 system_process_attributes (Lisp_Object pid)
6837 Lisp_Object attrs = Qnil;
6838 Lisp_Object cmd_str, decoded_cmd, tem;
6839 HANDLE h_snapshot, h_proc;
6840 DWORD proc_id;
6841 int found_proc = 0;
6842 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6843 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6844 DWORD glength = sizeof (gname);
6845 HANDLE token = NULL;
6846 SID_NAME_USE user_type;
6847 unsigned char *buf = NULL;
6848 DWORD blen = 0;
6849 TOKEN_USER user_token;
6850 TOKEN_PRIMARY_GROUP group_token;
6851 unsigned euid;
6852 unsigned egid;
6853 PROCESS_MEMORY_COUNTERS mem;
6854 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6855 SIZE_T minrss, maxrss;
6856 MEMORYSTATUS memst;
6857 MEMORY_STATUS_EX memstex;
6858 double totphys = 0.0;
6859 Lisp_Object ctime, stime, utime, etime, ttime;
6860 double pcpu;
6861 BOOL result = FALSE;
6863 CHECK_NUMBER_OR_FLOAT (pid);
6864 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6866 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6868 if (h_snapshot != INVALID_HANDLE_VALUE)
6870 PROCESSENTRY32 pe;
6871 BOOL res;
6873 pe.dwSize = sizeof (PROCESSENTRY32);
6874 for (res = process32_first (h_snapshot, &pe); res;
6875 res = process32_next (h_snapshot, &pe))
6877 if (proc_id == pe.th32ProcessID)
6879 if (proc_id == 0)
6880 decoded_cmd = build_string ("Idle");
6881 else
6883 /* Decode the command name from locale-specific
6884 encoding. */
6885 cmd_str = build_unibyte_string (pe.szExeFile);
6887 decoded_cmd =
6888 code_convert_string_norecord (cmd_str,
6889 Vlocale_coding_system, 0);
6891 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6892 attrs = Fcons (Fcons (Qppid,
6893 make_fixnum_or_float (pe.th32ParentProcessID)),
6894 attrs);
6895 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6896 attrs);
6897 attrs = Fcons (Fcons (Qthcount,
6898 make_fixnum_or_float (pe.cntThreads)),
6899 attrs);
6900 found_proc = 1;
6901 break;
6905 CloseHandle (h_snapshot);
6908 if (!found_proc)
6909 return Qnil;
6911 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6912 FALSE, proc_id);
6913 /* If we were denied a handle to the process, try again after
6914 enabling the SeDebugPrivilege in our process. */
6915 if (!h_proc)
6917 TOKEN_PRIVILEGES priv_current;
6919 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6921 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6922 FALSE, proc_id);
6923 restore_privilege (&priv_current);
6924 revert_to_self ();
6927 if (h_proc)
6929 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6930 if (result)
6932 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6933 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6935 buf = xmalloc (blen);
6936 result = get_token_information (token, TokenUser,
6937 (LPVOID)buf, blen, &needed);
6938 if (result)
6940 memcpy (&user_token, buf, sizeof (user_token));
6941 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6943 euid = get_rid (user_token.User.Sid);
6944 result = lookup_account_sid (NULL, user_token.User.Sid,
6945 uname, &ulength,
6946 domain, &dlength,
6947 &user_type);
6948 if (result)
6949 w32_add_to_cache (user_token.User.Sid, euid, uname);
6950 else
6952 strcpy (uname, "unknown");
6953 result = TRUE;
6956 ulength = strlen (uname);
6960 if (result)
6962 /* Determine a reasonable euid and gid values. */
6963 if (xstrcasecmp ("administrator", uname) == 0)
6965 euid = 500; /* well-known Administrator uid */
6966 egid = 513; /* well-known None gid */
6968 else
6970 /* Get group id and name. */
6971 result = get_token_information (token, TokenPrimaryGroup,
6972 (LPVOID)buf, blen, &needed);
6973 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6975 buf = xrealloc (buf, blen = needed);
6976 result = get_token_information (token, TokenPrimaryGroup,
6977 (LPVOID)buf, blen, &needed);
6979 if (result)
6981 memcpy (&group_token, buf, sizeof (group_token));
6982 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6984 egid = get_rid (group_token.PrimaryGroup);
6985 dlength = sizeof (domain);
6986 result =
6987 lookup_account_sid (NULL, group_token.PrimaryGroup,
6988 gname, &glength, NULL, &dlength,
6989 &user_type);
6990 if (result)
6991 w32_add_to_cache (group_token.PrimaryGroup,
6992 egid, gname);
6993 else
6995 strcpy (gname, "None");
6996 result = TRUE;
6999 glength = strlen (gname);
7003 xfree (buf);
7005 if (!result)
7007 if (!is_windows_9x ())
7009 /* We couldn't open the process token, presumably because of
7010 insufficient access rights. Assume this process is run
7011 by the system. */
7012 strcpy (uname, "SYSTEM");
7013 strcpy (gname, "None");
7014 euid = 18; /* SYSTEM */
7015 egid = 513; /* None */
7016 glength = strlen (gname);
7017 ulength = strlen (uname);
7019 /* If we are running under Windows 9X, where security calls are
7020 not supported, we assume all processes are run by the current
7021 user. */
7022 else if (GetUserName (uname, &ulength))
7024 if (xstrcasecmp ("administrator", uname) == 0)
7025 euid = 0;
7026 else
7027 euid = 123;
7028 egid = euid;
7029 strcpy (gname, "None");
7030 glength = strlen (gname);
7031 ulength = strlen (uname);
7033 else
7035 euid = 123;
7036 egid = 123;
7037 strcpy (uname, "administrator");
7038 ulength = strlen (uname);
7039 strcpy (gname, "None");
7040 glength = strlen (gname);
7042 if (token)
7043 CloseHandle (token);
7046 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7047 tem = make_unibyte_string (uname, ulength);
7048 attrs = Fcons (Fcons (Quser,
7049 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7050 attrs);
7051 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7052 tem = make_unibyte_string (gname, glength);
7053 attrs = Fcons (Fcons (Qgroup,
7054 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7055 attrs);
7057 if (global_memory_status_ex (&memstex))
7058 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7059 totphys = memstex.ullTotalPhys / 1024.0;
7060 #else
7061 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7062 double, so we need to do this for it... */
7064 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7065 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7066 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7068 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7070 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7071 else if (global_memory_status (&memst))
7072 totphys = memst.dwTotalPhys / 1024.0;
7074 if (h_proc
7075 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7076 sizeof (mem_ex)))
7078 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7080 attrs = Fcons (Fcons (Qmajflt,
7081 make_fixnum_or_float (mem_ex.PageFaultCount)),
7082 attrs);
7083 attrs = Fcons (Fcons (Qvsize,
7084 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7085 attrs);
7086 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7087 if (totphys)
7088 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7090 else if (h_proc
7091 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7093 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7095 attrs = Fcons (Fcons (Qmajflt,
7096 make_fixnum_or_float (mem.PageFaultCount)),
7097 attrs);
7098 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7099 if (totphys)
7100 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7102 else if (h_proc
7103 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7105 DWORD rss = maxrss / 1024;
7107 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7108 if (totphys)
7109 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7112 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7114 attrs = Fcons (Fcons (Qutime, utime), attrs);
7115 attrs = Fcons (Fcons (Qstime, stime), attrs);
7116 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7117 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7118 attrs = Fcons (Fcons (Qetime, etime), attrs);
7119 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7122 /* FIXME: Retrieve command line by walking the PEB of the process. */
7124 if (h_proc)
7125 CloseHandle (h_proc);
7126 return attrs;
7130 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7131 unsigned long long *totalswap, unsigned long long *freeswap)
7133 MEMORYSTATUS memst;
7134 MEMORY_STATUS_EX memstex;
7136 /* Use GlobalMemoryStatusEx if available, as it can report more than
7137 2GB of memory. */
7138 if (global_memory_status_ex (&memstex))
7140 *totalram = memstex.ullTotalPhys;
7141 *freeram = memstex.ullAvailPhys;
7142 *totalswap = memstex.ullTotalPageFile;
7143 *freeswap = memstex.ullAvailPageFile;
7144 return 0;
7146 else if (global_memory_status (&memst))
7148 *totalram = memst.dwTotalPhys;
7149 *freeram = memst.dwAvailPhys;
7150 *totalswap = memst.dwTotalPageFile;
7151 *freeswap = memst.dwAvailPageFile;
7152 return 0;
7154 else
7155 return -1;
7159 /* Wrappers for winsock functions to map between our file descriptors
7160 and winsock's handles; also set h_errno for convenience.
7162 To allow Emacs to run on systems which don't have winsock support
7163 installed, we dynamically link to winsock on startup if present, and
7164 otherwise provide the minimum necessary functionality
7165 (eg. gethostname). */
7167 /* function pointers for relevant socket functions */
7168 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7169 void (PASCAL *pfn_WSASetLastError) (int iError);
7170 int (PASCAL *pfn_WSAGetLastError) (void);
7171 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7172 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7173 WSANETWORKEVENTS *NetworkEvents);
7175 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7176 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7177 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7178 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7179 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7180 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7181 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7182 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7183 int (PASCAL *pfn_closesocket) (SOCKET s);
7184 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7185 int (PASCAL *pfn_WSACleanup) (void);
7187 u_short (PASCAL *pfn_htons) (u_short hostshort);
7188 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7189 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7190 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7191 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7192 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7193 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7194 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7195 const char * optval, int optlen);
7196 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7197 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7198 int * namelen);
7199 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7200 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7201 struct sockaddr * from, int * fromlen);
7202 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7203 const struct sockaddr * to, int tolen);
7205 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7206 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7207 #ifndef HANDLE_FLAG_INHERIT
7208 #define HANDLE_FLAG_INHERIT 1
7209 #endif
7211 HANDLE winsock_lib;
7212 static int winsock_inuse;
7214 BOOL
7215 term_winsock (void)
7217 if (winsock_lib != NULL && winsock_inuse == 0)
7219 release_listen_threads ();
7220 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7221 after WSAStartup returns successfully, but it seems reasonable
7222 to allow unloading winsock anyway in that case. */
7223 if (pfn_WSACleanup () == 0 ||
7224 pfn_WSAGetLastError () == WSAENETDOWN)
7226 if (FreeLibrary (winsock_lib))
7227 winsock_lib = NULL;
7228 return TRUE;
7231 return FALSE;
7234 BOOL
7235 init_winsock (int load_now)
7237 WSADATA winsockData;
7239 if (winsock_lib != NULL)
7240 return TRUE;
7242 pfn_SetHandleInformation
7243 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7244 "SetHandleInformation");
7246 winsock_lib = LoadLibrary ("Ws2_32.dll");
7248 if (winsock_lib != NULL)
7250 /* dynamically link to socket functions */
7252 #define LOAD_PROC(fn) \
7253 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7254 goto fail;
7256 LOAD_PROC (WSAStartup);
7257 LOAD_PROC (WSASetLastError);
7258 LOAD_PROC (WSAGetLastError);
7259 LOAD_PROC (WSAEventSelect);
7260 LOAD_PROC (WSAEnumNetworkEvents);
7261 LOAD_PROC (WSACreateEvent);
7262 LOAD_PROC (WSACloseEvent);
7263 LOAD_PROC (socket);
7264 LOAD_PROC (bind);
7265 LOAD_PROC (connect);
7266 LOAD_PROC (ioctlsocket);
7267 LOAD_PROC (recv);
7268 LOAD_PROC (send);
7269 LOAD_PROC (closesocket);
7270 LOAD_PROC (shutdown);
7271 LOAD_PROC (htons);
7272 LOAD_PROC (ntohs);
7273 LOAD_PROC (inet_addr);
7274 LOAD_PROC (gethostname);
7275 LOAD_PROC (gethostbyname);
7276 LOAD_PROC (getservbyname);
7277 LOAD_PROC (getpeername);
7278 LOAD_PROC (WSACleanup);
7279 LOAD_PROC (setsockopt);
7280 LOAD_PROC (listen);
7281 LOAD_PROC (getsockname);
7282 LOAD_PROC (accept);
7283 LOAD_PROC (recvfrom);
7284 LOAD_PROC (sendto);
7285 #undef LOAD_PROC
7287 /* specify version 1.1 of winsock */
7288 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7290 if (winsockData.wVersion != 0x101)
7291 goto fail;
7293 if (!load_now)
7295 /* Report that winsock exists and is usable, but leave
7296 socket functions disabled. I am assuming that calling
7297 WSAStartup does not require any network interaction,
7298 and in particular does not cause or require a dial-up
7299 connection to be established. */
7301 pfn_WSACleanup ();
7302 FreeLibrary (winsock_lib);
7303 winsock_lib = NULL;
7305 winsock_inuse = 0;
7306 return TRUE;
7309 fail:
7310 FreeLibrary (winsock_lib);
7311 winsock_lib = NULL;
7314 return FALSE;
7318 int h_errno = 0;
7320 /* Function to map winsock error codes to errno codes for those errno
7321 code defined in errno.h (errno values not defined by errno.h are
7322 already in nt/inc/sys/socket.h). */
7323 static void
7324 set_errno (void)
7326 int wsa_err;
7328 h_errno = 0;
7329 if (winsock_lib == NULL)
7330 wsa_err = EINVAL;
7331 else
7332 wsa_err = pfn_WSAGetLastError ();
7334 switch (wsa_err)
7336 case WSAEACCES: errno = EACCES; break;
7337 case WSAEBADF: errno = EBADF; break;
7338 case WSAEFAULT: errno = EFAULT; break;
7339 case WSAEINTR: errno = EINTR; break;
7340 case WSAEINVAL: errno = EINVAL; break;
7341 case WSAEMFILE: errno = EMFILE; break;
7342 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7343 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7344 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7345 case WSAENOTCONN: errno = ENOTCONN; break;
7346 default: errno = wsa_err; break;
7350 static void
7351 check_errno (void)
7353 h_errno = 0;
7354 if (winsock_lib != NULL)
7355 pfn_WSASetLastError (0);
7358 /* Extend strerror to handle the winsock-specific error codes. */
7359 struct {
7360 int errnum;
7361 char * msg;
7362 } _wsa_errlist[] = {
7363 {WSAEINTR , "Interrupted function call"},
7364 {WSAEBADF , "Bad file descriptor"},
7365 {WSAEACCES , "Permission denied"},
7366 {WSAEFAULT , "Bad address"},
7367 {WSAEINVAL , "Invalid argument"},
7368 {WSAEMFILE , "Too many open files"},
7370 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7371 {WSAEINPROGRESS , "Operation now in progress"},
7372 {WSAEALREADY , "Operation already in progress"},
7373 {WSAENOTSOCK , "Socket operation on non-socket"},
7374 {WSAEDESTADDRREQ , "Destination address required"},
7375 {WSAEMSGSIZE , "Message too long"},
7376 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7377 {WSAENOPROTOOPT , "Bad protocol option"},
7378 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7379 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7380 {WSAEOPNOTSUPP , "Operation not supported"},
7381 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7382 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7383 {WSAEADDRINUSE , "Address already in use"},
7384 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7385 {WSAENETDOWN , "Network is down"},
7386 {WSAENETUNREACH , "Network is unreachable"},
7387 {WSAENETRESET , "Network dropped connection on reset"},
7388 {WSAECONNABORTED , "Software caused connection abort"},
7389 {WSAECONNRESET , "Connection reset by peer"},
7390 {WSAENOBUFS , "No buffer space available"},
7391 {WSAEISCONN , "Socket is already connected"},
7392 {WSAENOTCONN , "Socket is not connected"},
7393 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7394 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7395 {WSAETIMEDOUT , "Connection timed out"},
7396 {WSAECONNREFUSED , "Connection refused"},
7397 {WSAELOOP , "Network loop"}, /* not sure */
7398 {WSAENAMETOOLONG , "Name is too long"},
7399 {WSAEHOSTDOWN , "Host is down"},
7400 {WSAEHOSTUNREACH , "No route to host"},
7401 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7402 {WSAEPROCLIM , "Too many processes"},
7403 {WSAEUSERS , "Too many users"}, /* not sure */
7404 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7405 {WSAESTALE , "Data is stale"}, /* not sure */
7406 {WSAEREMOTE , "Remote error"}, /* not sure */
7408 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7409 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7410 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7411 {WSAEDISCON , "Graceful shutdown in progress"},
7412 #ifdef WSAENOMORE
7413 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7414 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7415 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7416 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7417 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7418 {WSASYSCALLFAILURE , "System call failure"},
7419 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7420 {WSATYPE_NOT_FOUND , "Class type not found"},
7421 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7422 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7423 {WSAEREFUSED , "Operation refused"}, /* not sure */
7424 #endif
7426 {WSAHOST_NOT_FOUND , "Host not found"},
7427 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7428 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7429 {WSANO_DATA , "Valid name, no data record of requested type"},
7431 {-1, NULL}
7434 char *
7435 sys_strerror (int error_no)
7437 int i;
7438 static char unknown_msg[40];
7440 if (error_no >= 0 && error_no < sys_nerr)
7441 return sys_errlist[error_no];
7443 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7444 if (_wsa_errlist[i].errnum == error_no)
7445 return _wsa_errlist[i].msg;
7447 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7448 return unknown_msg;
7451 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7452 but I believe the method of keeping the socket handle separate (and
7453 insuring it is not inheritable) is the correct one. */
7455 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7457 static int socket_to_fd (SOCKET s);
7460 sys_socket (int af, int type, int protocol)
7462 SOCKET s;
7464 if (winsock_lib == NULL)
7466 errno = ENETDOWN;
7467 return -1;
7470 check_errno ();
7472 /* call the real socket function */
7473 s = pfn_socket (af, type, protocol);
7475 if (s != INVALID_SOCKET)
7476 return socket_to_fd (s);
7478 set_errno ();
7479 return -1;
7482 /* Convert a SOCKET to a file descriptor. */
7483 static int
7484 socket_to_fd (SOCKET s)
7486 int fd;
7487 child_process * cp;
7489 /* Although under NT 3.5 _open_osfhandle will accept a socket
7490 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7491 that does not work under NT 3.1. However, we can get the same
7492 effect by using a backdoor function to replace an existing
7493 descriptor handle with the one we want. */
7495 /* allocate a file descriptor (with appropriate flags) */
7496 fd = _open ("NUL:", _O_RDWR);
7497 if (fd >= 0)
7499 /* Make a non-inheritable copy of the socket handle. Note
7500 that it is possible that sockets aren't actually kernel
7501 handles, which appears to be the case on Windows 9x when
7502 the MS Proxy winsock client is installed. */
7504 /* Apparently there is a bug in NT 3.51 with some service
7505 packs, which prevents using DuplicateHandle to make a
7506 socket handle non-inheritable (causes WSACleanup to
7507 hang). The work-around is to use SetHandleInformation
7508 instead if it is available and implemented. */
7509 if (pfn_SetHandleInformation)
7511 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7513 else
7515 HANDLE parent = GetCurrentProcess ();
7516 HANDLE new_s = INVALID_HANDLE_VALUE;
7518 if (DuplicateHandle (parent,
7519 (HANDLE) s,
7520 parent,
7521 &new_s,
7523 FALSE,
7524 DUPLICATE_SAME_ACCESS))
7526 /* It is possible that DuplicateHandle succeeds even
7527 though the socket wasn't really a kernel handle,
7528 because a real handle has the same value. So
7529 test whether the new handle really is a socket. */
7530 unsigned long nonblocking = 0;
7531 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7533 pfn_closesocket (s);
7534 s = (SOCKET) new_s;
7536 else
7538 CloseHandle (new_s);
7543 eassert (fd < MAXDESC);
7544 fd_info[fd].hnd = (HANDLE) s;
7546 /* set our own internal flags */
7547 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7549 cp = new_child ();
7550 if (cp)
7552 cp->fd = fd;
7553 cp->status = STATUS_READ_ACKNOWLEDGED;
7555 /* attach child_process to fd_info */
7556 if (fd_info[ fd ].cp != NULL)
7558 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7559 emacs_abort ();
7562 fd_info[ fd ].cp = cp;
7564 /* success! */
7565 winsock_inuse++; /* count open sockets */
7566 return fd;
7569 /* clean up */
7570 _close (fd);
7572 else
7573 pfn_closesocket (s);
7574 errno = EMFILE;
7575 return -1;
7579 sys_bind (int s, const struct sockaddr * addr, int namelen)
7581 if (winsock_lib == NULL)
7583 errno = ENOTSOCK;
7584 return SOCKET_ERROR;
7587 check_errno ();
7588 if (fd_info[s].flags & FILE_SOCKET)
7590 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7591 if (rc == SOCKET_ERROR)
7592 set_errno ();
7593 return rc;
7595 errno = ENOTSOCK;
7596 return SOCKET_ERROR;
7600 sys_connect (int s, const struct sockaddr * name, int namelen)
7602 if (winsock_lib == NULL)
7604 errno = ENOTSOCK;
7605 return SOCKET_ERROR;
7608 check_errno ();
7609 if (fd_info[s].flags & FILE_SOCKET)
7611 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7612 if (rc == SOCKET_ERROR)
7614 set_errno ();
7615 /* If this is a non-blocking 'connect', set the bit in flags
7616 that will tell reader_thread to wait for connection
7617 before trying to read. */
7618 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7620 errno = EINPROGRESS; /* that's what process.c expects */
7621 fd_info[s].flags |= FILE_CONNECT;
7624 return rc;
7626 errno = ENOTSOCK;
7627 return SOCKET_ERROR;
7630 u_short
7631 sys_htons (u_short hostshort)
7633 return (winsock_lib != NULL) ?
7634 pfn_htons (hostshort) : hostshort;
7637 u_short
7638 sys_ntohs (u_short netshort)
7640 return (winsock_lib != NULL) ?
7641 pfn_ntohs (netshort) : netshort;
7644 unsigned long
7645 sys_inet_addr (const char * cp)
7647 return (winsock_lib != NULL) ?
7648 pfn_inet_addr (cp) : INADDR_NONE;
7652 sys_gethostname (char * name, int namelen)
7654 if (winsock_lib != NULL)
7656 int retval;
7658 check_errno ();
7659 retval = pfn_gethostname (name, namelen);
7660 if (retval == SOCKET_ERROR)
7661 set_errno ();
7662 return retval;
7665 if (namelen > MAX_COMPUTERNAME_LENGTH)
7666 return !GetComputerName (name, (DWORD *)&namelen);
7668 errno = EFAULT;
7669 return SOCKET_ERROR;
7672 struct hostent *
7673 sys_gethostbyname (const char * name)
7675 struct hostent * host;
7676 int h_err = h_errno;
7678 if (winsock_lib == NULL)
7680 h_errno = NO_RECOVERY;
7681 errno = ENETDOWN;
7682 return NULL;
7685 check_errno ();
7686 host = pfn_gethostbyname (name);
7687 if (!host)
7689 set_errno ();
7690 h_errno = errno;
7692 else
7693 h_errno = h_err;
7694 return host;
7697 struct servent *
7698 sys_getservbyname (const char * name, const char * proto)
7700 struct servent * serv;
7702 if (winsock_lib == NULL)
7704 errno = ENETDOWN;
7705 return NULL;
7708 check_errno ();
7709 serv = pfn_getservbyname (name, proto);
7710 if (!serv)
7711 set_errno ();
7712 return serv;
7716 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7718 if (winsock_lib == NULL)
7720 errno = ENETDOWN;
7721 return SOCKET_ERROR;
7724 check_errno ();
7725 if (fd_info[s].flags & FILE_SOCKET)
7727 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7728 if (rc == SOCKET_ERROR)
7729 set_errno ();
7730 return rc;
7732 errno = ENOTSOCK;
7733 return SOCKET_ERROR;
7737 sys_shutdown (int s, int how)
7739 if (winsock_lib == NULL)
7741 errno = ENETDOWN;
7742 return SOCKET_ERROR;
7745 check_errno ();
7746 if (fd_info[s].flags & FILE_SOCKET)
7748 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7749 if (rc == SOCKET_ERROR)
7750 set_errno ();
7751 return rc;
7753 errno = ENOTSOCK;
7754 return SOCKET_ERROR;
7758 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7760 if (winsock_lib == NULL)
7762 errno = ENETDOWN;
7763 return SOCKET_ERROR;
7766 check_errno ();
7767 if (fd_info[s].flags & FILE_SOCKET)
7769 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7770 (const char *)optval, optlen);
7771 if (rc == SOCKET_ERROR)
7772 set_errno ();
7773 return rc;
7775 errno = ENOTSOCK;
7776 return SOCKET_ERROR;
7780 sys_listen (int s, int backlog)
7782 if (winsock_lib == NULL)
7784 errno = ENETDOWN;
7785 return SOCKET_ERROR;
7788 check_errno ();
7789 if (fd_info[s].flags & FILE_SOCKET)
7791 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7792 if (rc == SOCKET_ERROR)
7793 set_errno ();
7794 else
7795 fd_info[s].flags |= FILE_LISTEN;
7796 return rc;
7798 errno = ENOTSOCK;
7799 return SOCKET_ERROR;
7803 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7805 if (winsock_lib == NULL)
7807 errno = ENETDOWN;
7808 return SOCKET_ERROR;
7811 check_errno ();
7812 if (fd_info[s].flags & FILE_SOCKET)
7814 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7815 if (rc == SOCKET_ERROR)
7816 set_errno ();
7817 return rc;
7819 errno = ENOTSOCK;
7820 return SOCKET_ERROR;
7824 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7826 if (winsock_lib == NULL)
7828 errno = ENETDOWN;
7829 return -1;
7832 check_errno ();
7833 if (fd_info[s].flags & FILE_LISTEN)
7835 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7836 int fd = -1;
7837 if (t == INVALID_SOCKET)
7838 set_errno ();
7839 else
7840 fd = socket_to_fd (t);
7842 if (fd >= 0)
7844 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7845 ResetEvent (fd_info[s].cp->char_avail);
7847 return fd;
7849 errno = ENOTSOCK;
7850 return -1;
7854 sys_recvfrom (int s, char * buf, int len, int flags,
7855 struct sockaddr * from, int * fromlen)
7857 if (winsock_lib == NULL)
7859 errno = ENETDOWN;
7860 return SOCKET_ERROR;
7863 check_errno ();
7864 if (fd_info[s].flags & FILE_SOCKET)
7866 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7867 if (rc == SOCKET_ERROR)
7868 set_errno ();
7869 return rc;
7871 errno = ENOTSOCK;
7872 return SOCKET_ERROR;
7876 sys_sendto (int s, const char * buf, int len, int flags,
7877 const struct sockaddr * to, int tolen)
7879 if (winsock_lib == NULL)
7881 errno = ENETDOWN;
7882 return SOCKET_ERROR;
7885 check_errno ();
7886 if (fd_info[s].flags & FILE_SOCKET)
7888 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7889 if (rc == SOCKET_ERROR)
7890 set_errno ();
7891 return rc;
7893 errno = ENOTSOCK;
7894 return SOCKET_ERROR;
7897 /* Windows does not have an fcntl function. Provide an implementation
7898 good enough for Emacs. */
7900 fcntl (int s, int cmd, int options)
7902 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7903 invoked in a context where fd1 is closed and all descriptors less
7904 than fd1 are open, so sys_dup is an adequate implementation. */
7905 if (cmd == F_DUPFD_CLOEXEC)
7906 return sys_dup (s);
7908 check_errno ();
7909 if (fd_info[s].flags & FILE_SOCKET)
7911 if (winsock_lib == NULL)
7913 errno = ENETDOWN;
7914 return -1;
7917 if (cmd == F_SETFL && options == O_NONBLOCK)
7919 unsigned long nblock = 1;
7920 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7921 if (rc == SOCKET_ERROR)
7922 set_errno ();
7923 /* Keep track of the fact that we set this to non-blocking. */
7924 fd_info[s].flags |= FILE_NDELAY;
7925 return rc;
7927 else
7929 errno = EINVAL;
7930 return SOCKET_ERROR;
7933 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7934 == (FILE_PIPE | FILE_WRITE))
7936 /* Force our writes to pipes be non-blocking. */
7937 if (cmd == F_SETFL && options == O_NONBLOCK)
7939 HANDLE h = (HANDLE)_get_osfhandle (s);
7940 DWORD pipe_mode = PIPE_NOWAIT;
7942 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7944 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7945 return SOCKET_ERROR;
7947 fd_info[s].flags |= FILE_NDELAY;
7948 return 0;
7950 else
7952 errno = EINVAL;
7953 return SOCKET_ERROR;
7956 errno = ENOTSOCK;
7957 return SOCKET_ERROR;
7961 /* Shadow main io functions: we need to handle pipes and sockets more
7962 intelligently. */
7965 sys_close (int fd)
7967 int rc;
7969 if (fd < 0)
7971 errno = EBADF;
7972 return -1;
7975 if (fd < MAXDESC && fd_info[fd].cp)
7977 child_process * cp = fd_info[fd].cp;
7979 fd_info[fd].cp = NULL;
7981 if (CHILD_ACTIVE (cp))
7983 /* if last descriptor to active child_process then cleanup */
7984 int i;
7985 for (i = 0; i < MAXDESC; i++)
7987 if (i == fd)
7988 continue;
7989 if (fd_info[i].cp == cp)
7990 break;
7992 if (i == MAXDESC)
7994 if (fd_info[fd].flags & FILE_SOCKET)
7996 if (winsock_lib == NULL) emacs_abort ();
7998 pfn_shutdown (SOCK_HANDLE (fd), 2);
7999 rc = pfn_closesocket (SOCK_HANDLE (fd));
8001 winsock_inuse--; /* count open sockets */
8003 /* If the process handle is NULL, it's either a socket
8004 or serial connection, or a subprocess that was
8005 already reaped by reap_subprocess, but whose
8006 resources were not yet freed, because its output was
8007 not fully read yet by the time it was reaped. (This
8008 usually happens with async subprocesses whose output
8009 is being read by Emacs.) Otherwise, this process was
8010 not reaped yet, so we set its FD to a negative value
8011 to make sure sys_select will eventually get to
8012 calling the SIGCHLD handler for it, which will then
8013 invoke waitpid and reap_subprocess. */
8014 if (cp->procinfo.hProcess == NULL)
8015 delete_child (cp);
8016 else
8017 cp->fd = -1;
8022 if (fd >= 0 && fd < MAXDESC)
8023 fd_info[fd].flags = 0;
8025 /* Note that sockets do not need special treatment here (at least on
8026 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8027 closesocket is equivalent to CloseHandle, which is to be expected
8028 because socket handles are fully fledged kernel handles. */
8029 rc = _close (fd);
8031 return rc;
8035 sys_dup (int fd)
8037 int new_fd;
8039 new_fd = _dup (fd);
8040 if (new_fd >= 0 && new_fd < MAXDESC)
8042 /* duplicate our internal info as well */
8043 fd_info[new_fd] = fd_info[fd];
8045 return new_fd;
8049 sys_dup2 (int src, int dst)
8051 int rc;
8053 if (dst < 0 || dst >= MAXDESC)
8055 errno = EBADF;
8056 return -1;
8059 /* make sure we close the destination first if it's a pipe or socket */
8060 if (src != dst && fd_info[dst].flags != 0)
8061 sys_close (dst);
8063 rc = _dup2 (src, dst);
8064 if (rc == 0)
8066 /* duplicate our internal info as well */
8067 fd_info[dst] = fd_info[src];
8069 return rc;
8073 pipe2 (int * phandles, int pipe2_flags)
8075 int rc;
8076 unsigned flags;
8077 unsigned pipe_size = 0;
8079 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8081 /* Allow Lisp to override the default buffer size of the pipe. */
8082 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8083 pipe_size = w32_pipe_buffer_size;
8085 /* make pipe handles non-inheritable; when we spawn a child, we
8086 replace the relevant handle with an inheritable one. Also put
8087 pipes into binary mode; we will do text mode translation ourselves
8088 if required. */
8089 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8091 if (rc == 0)
8093 /* Protect against overflow, since Windows can open more handles than
8094 our fd_info array has room for. */
8095 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8097 _close (phandles[0]);
8098 _close (phandles[1]);
8099 errno = EMFILE;
8100 rc = -1;
8102 else
8104 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8105 fd_info[phandles[0]].flags = flags;
8107 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8108 fd_info[phandles[1]].flags = flags;
8112 return rc;
8115 /* Function to do blocking read of one byte, needed to implement
8116 select. It is only allowed on communication ports, sockets, or
8117 pipes. */
8119 _sys_read_ahead (int fd)
8121 child_process * cp;
8122 int rc;
8124 if (fd < 0 || fd >= MAXDESC)
8125 return STATUS_READ_ERROR;
8127 cp = fd_info[fd].cp;
8129 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8130 return STATUS_READ_ERROR;
8132 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8133 || (fd_info[fd].flags & FILE_READ) == 0)
8135 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8136 emacs_abort ();
8139 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8140 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8141 cp->status = STATUS_READ_IN_PROGRESS;
8143 if (fd_info[fd].flags & FILE_PIPE)
8145 rc = _read (fd, &cp->chr, sizeof (char));
8147 /* Give subprocess time to buffer some more output for us before
8148 reporting that input is available; we need this because Windows 95
8149 connects DOS programs to pipes by making the pipe appear to be
8150 the normal console stdout - as a result most DOS programs will
8151 write to stdout without buffering, ie. one character at a
8152 time. Even some W32 programs do this - "dir" in a command
8153 shell on NT is very slow if we don't do this. */
8154 if (rc > 0)
8156 int wait = w32_pipe_read_delay;
8158 if (wait > 0)
8159 Sleep (wait);
8160 else if (wait < 0)
8161 while (++wait <= 0)
8162 /* Yield remainder of our time slice, effectively giving a
8163 temporary priority boost to the child process. */
8164 Sleep (0);
8167 else if (fd_info[fd].flags & FILE_SERIAL)
8169 HANDLE hnd = fd_info[fd].hnd;
8170 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8171 COMMTIMEOUTS ct;
8173 /* Configure timeouts for blocking read. */
8174 if (!GetCommTimeouts (hnd, &ct))
8176 cp->status = STATUS_READ_ERROR;
8177 return STATUS_READ_ERROR;
8179 ct.ReadIntervalTimeout = 0;
8180 ct.ReadTotalTimeoutMultiplier = 0;
8181 ct.ReadTotalTimeoutConstant = 0;
8182 if (!SetCommTimeouts (hnd, &ct))
8184 cp->status = STATUS_READ_ERROR;
8185 return STATUS_READ_ERROR;
8188 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8190 if (GetLastError () != ERROR_IO_PENDING)
8192 cp->status = STATUS_READ_ERROR;
8193 return STATUS_READ_ERROR;
8195 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8197 cp->status = STATUS_READ_ERROR;
8198 return STATUS_READ_ERROR;
8202 else if (fd_info[fd].flags & FILE_SOCKET)
8204 unsigned long nblock = 0;
8205 /* We always want this to block, so temporarily disable NDELAY. */
8206 if (fd_info[fd].flags & FILE_NDELAY)
8207 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8209 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8211 if (fd_info[fd].flags & FILE_NDELAY)
8213 nblock = 1;
8214 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8218 if (rc == sizeof (char))
8219 cp->status = STATUS_READ_SUCCEEDED;
8220 else
8221 cp->status = STATUS_READ_FAILED;
8223 return cp->status;
8227 _sys_wait_accept (int fd)
8229 HANDLE hEv;
8230 child_process * cp;
8231 int rc;
8233 if (fd < 0 || fd >= MAXDESC)
8234 return STATUS_READ_ERROR;
8236 cp = fd_info[fd].cp;
8238 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8239 return STATUS_READ_ERROR;
8241 cp->status = STATUS_READ_FAILED;
8243 hEv = pfn_WSACreateEvent ();
8244 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8245 if (rc != SOCKET_ERROR)
8247 do {
8248 rc = WaitForSingleObject (hEv, 500);
8249 Sleep (5);
8250 } while (rc == WAIT_TIMEOUT
8251 && cp->status != STATUS_READ_ERROR
8252 && cp->char_avail);
8253 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8254 if (rc == WAIT_OBJECT_0)
8255 cp->status = STATUS_READ_SUCCEEDED;
8257 pfn_WSACloseEvent (hEv);
8259 return cp->status;
8263 _sys_wait_connect (int fd)
8265 HANDLE hEv;
8266 child_process * cp;
8267 int rc;
8269 if (fd < 0 || fd >= MAXDESC)
8270 return STATUS_READ_ERROR;
8272 cp = fd_info[fd].cp;
8273 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8274 return STATUS_READ_ERROR;
8276 cp->status = STATUS_READ_FAILED;
8278 hEv = pfn_WSACreateEvent ();
8279 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8280 if (rc != SOCKET_ERROR)
8282 do {
8283 rc = WaitForSingleObject (hEv, 500);
8284 Sleep (5);
8285 } while (rc == WAIT_TIMEOUT
8286 && cp->status != STATUS_READ_ERROR
8287 && cp->char_avail);
8288 if (rc == WAIT_OBJECT_0)
8290 /* We've got an event, but it could be a successful
8291 connection, or it could be a failure. Find out
8292 which one is it. */
8293 WSANETWORKEVENTS events;
8295 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8296 if ((events.lNetworkEvents & FD_CONNECT) != 0
8297 && events.iErrorCode[FD_CONNECT_BIT])
8299 cp->status = STATUS_CONNECT_FAILED;
8300 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8302 else
8304 cp->status = STATUS_READ_SUCCEEDED;
8305 cp->errcode = 0;
8308 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8310 else
8311 pfn_WSACloseEvent (hEv);
8313 return cp->status;
8317 sys_read (int fd, char * buffer, unsigned int count)
8319 int nchars;
8320 int to_read;
8321 DWORD waiting;
8322 char * orig_buffer = buffer;
8324 if (fd < 0)
8326 errno = EBADF;
8327 return -1;
8330 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8332 child_process *cp = fd_info[fd].cp;
8334 if ((fd_info[fd].flags & FILE_READ) == 0)
8336 errno = EBADF;
8337 return -1;
8340 nchars = 0;
8342 /* re-read CR carried over from last read */
8343 if (fd_info[fd].flags & FILE_LAST_CR)
8345 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8346 *buffer++ = 0x0d;
8347 count--;
8348 nchars++;
8349 fd_info[fd].flags &= ~FILE_LAST_CR;
8352 /* presence of a child_process structure means we are operating in
8353 non-blocking mode - otherwise we just call _read directly.
8354 Note that the child_process structure might be missing because
8355 reap_subprocess has been called; in this case the pipe is
8356 already broken, so calling _read on it is okay. */
8357 if (cp)
8359 int current_status = cp->status;
8361 switch (current_status)
8363 case STATUS_READ_FAILED:
8364 case STATUS_READ_ERROR:
8365 /* report normal EOF if nothing in buffer */
8366 if (nchars <= 0)
8367 fd_info[fd].flags |= FILE_AT_EOF;
8368 return nchars;
8370 case STATUS_READ_READY:
8371 case STATUS_READ_IN_PROGRESS:
8372 #if 0
8373 /* This happens all the time during GnuTLS handshake
8374 with the remote, evidently because GnuTLS waits for
8375 the read to complete by retrying the read operation
8376 upon EAGAIN. So I'm disabling the DebPrint to avoid
8377 wasting cycles on something that is not a real
8378 problem. Enable if you need to debug something that
8379 bumps into this. */
8380 DebPrint (("sys_read called when read is in progress %d\n",
8381 current_status));
8382 #endif
8383 errno = EWOULDBLOCK;
8384 return -1;
8386 case STATUS_READ_SUCCEEDED:
8387 /* consume read-ahead char */
8388 *buffer++ = cp->chr;
8389 count--;
8390 nchars++;
8391 cp->status = STATUS_READ_ACKNOWLEDGED;
8392 ResetEvent (cp->char_avail);
8394 case STATUS_READ_ACKNOWLEDGED:
8395 case STATUS_CONNECT_FAILED:
8396 break;
8398 default:
8399 DebPrint (("sys_read: bad status %d\n", current_status));
8400 errno = EBADF;
8401 return -1;
8404 if (fd_info[fd].flags & FILE_PIPE)
8406 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8407 to_read = min (waiting, (DWORD) count);
8409 if (to_read > 0)
8410 nchars += _read (fd, buffer, to_read);
8412 else if (fd_info[fd].flags & FILE_SERIAL)
8414 HANDLE hnd = fd_info[fd].hnd;
8415 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8416 int rc = 0;
8417 COMMTIMEOUTS ct;
8419 if (count > 0)
8421 /* Configure timeouts for non-blocking read. */
8422 if (!GetCommTimeouts (hnd, &ct))
8424 errno = EIO;
8425 return -1;
8427 ct.ReadIntervalTimeout = MAXDWORD;
8428 ct.ReadTotalTimeoutMultiplier = 0;
8429 ct.ReadTotalTimeoutConstant = 0;
8430 if (!SetCommTimeouts (hnd, &ct))
8432 errno = EIO;
8433 return -1;
8436 if (!ResetEvent (ovl->hEvent))
8438 errno = EIO;
8439 return -1;
8441 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8443 if (GetLastError () != ERROR_IO_PENDING)
8445 errno = EIO;
8446 return -1;
8448 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8450 errno = EIO;
8451 return -1;
8454 nchars += rc;
8457 else /* FILE_SOCKET */
8459 if (winsock_lib == NULL) emacs_abort ();
8461 /* When a non-blocking 'connect' call fails,
8462 wait_reading_process_output detects this by calling
8463 'getpeername', and then attempts to obtain the connection
8464 error code by trying to read 1 byte from the socket. If
8465 we try to serve that read by calling 'recv' below, the
8466 error we get is a generic WSAENOTCONN, not the actual
8467 connection error. So instead, we use the actual error
8468 code stashed by '_sys_wait_connect' in cp->errcode.
8469 Alternatively, we could have used 'getsockopt', like on
8470 GNU/Linux, but: (a) I have no idea whether the winsock
8471 version could hang, as it does "on some systems" (see the
8472 comment in process.c); and (b) 'getsockopt' on Windows is
8473 documented to clear the socket error for the entire
8474 process, which I'm not sure is TRT; FIXME. */
8475 if (current_status == STATUS_CONNECT_FAILED
8476 && (fd_info[fd].flags & FILE_CONNECT) != 0
8477 && cp->errcode != 0)
8479 pfn_WSASetLastError (cp->errcode);
8480 set_errno ();
8481 return -1;
8483 /* Do the equivalent of a non-blocking read. */
8484 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8485 if (waiting == 0 && nchars == 0)
8487 errno = EWOULDBLOCK;
8488 return -1;
8491 if (waiting)
8493 /* always use binary mode for sockets */
8494 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8495 if (res == SOCKET_ERROR)
8497 set_errno ();
8498 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8499 errno, SOCK_HANDLE (fd)));
8500 return -1;
8502 nchars += res;
8506 else
8508 int nread = _read (fd, buffer, count);
8509 if (nread >= 0)
8510 nchars += nread;
8511 else if (nchars == 0)
8512 nchars = nread;
8515 if (nchars <= 0)
8516 fd_info[fd].flags |= FILE_AT_EOF;
8517 /* Perform text mode translation if required. */
8518 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8520 nchars = crlf_to_lf (nchars, orig_buffer);
8521 /* If buffer contains only CR, return that. To be absolutely
8522 sure we should attempt to read the next char, but in
8523 practice a CR to be followed by LF would not appear by
8524 itself in the buffer. */
8525 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8527 fd_info[fd].flags |= FILE_LAST_CR;
8528 nchars--;
8532 else
8533 nchars = _read (fd, buffer, count);
8535 return nchars;
8538 /* From w32xfns.c */
8539 extern HANDLE interrupt_handle;
8542 sys_write (int fd, const void * buffer, unsigned int count)
8544 int nchars;
8545 USE_SAFE_ALLOCA;
8547 if (fd < 0)
8549 errno = EBADF;
8550 return -1;
8553 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8555 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8557 errno = EBADF;
8558 return -1;
8561 /* Perform text mode translation if required. */
8562 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8564 char * tmpbuf;
8565 const unsigned char * src = buffer;
8566 unsigned char * dst;
8567 int nbytes = count;
8569 SAFE_NALLOCA (tmpbuf, 2, count);
8570 dst = (unsigned char *)tmpbuf;
8572 while (1)
8574 unsigned char *next;
8575 /* Copy next line or remaining bytes. */
8576 next = _memccpy (dst, src, '\n', nbytes);
8577 if (next)
8579 /* Copied one line ending with '\n'. */
8580 int copied = next - dst;
8581 nbytes -= copied;
8582 src += copied;
8583 /* Insert '\r' before '\n'. */
8584 next[-1] = '\r';
8585 next[0] = '\n';
8586 dst = next + 1;
8587 count++;
8589 else
8590 /* Copied remaining partial line -> now finished. */
8591 break;
8593 buffer = tmpbuf;
8597 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8599 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8600 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8601 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8602 DWORD active = 0;
8604 /* This is async (a.k.a. "overlapped") I/O, so the return value
8605 of FALSE from WriteFile means either an error or the output
8606 will be completed asynchronously (ERROR_IO_PENDING). */
8607 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8609 if (GetLastError () != ERROR_IO_PENDING)
8611 errno = EIO;
8612 nchars = -1;
8614 else
8616 /* Wait for the write to complete, and watch C-g while
8617 at that. */
8618 if (detect_input_pending ())
8619 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8620 INFINITE, QS_ALLINPUT);
8621 else
8622 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8623 switch (active)
8625 case WAIT_OBJECT_0:
8626 /* User pressed C-g, cancel write, then leave.
8627 Don't bother cleaning up as we may only get stuck
8628 in buggy drivers. */
8629 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8630 CancelIo (hnd);
8631 errno = EIO; /* Why not EINTR? */
8632 nchars = -1;
8633 break;
8634 case WAIT_OBJECT_0 + 1:
8635 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8637 errno = EIO;
8638 nchars = -1;
8640 break;
8645 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8647 unsigned long nblock = 0;
8648 if (winsock_lib == NULL) emacs_abort ();
8650 /* TODO: implement select() properly so non-blocking I/O works. */
8651 /* For now, make sure the write blocks. */
8652 if (fd_info[fd].flags & FILE_NDELAY)
8653 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8655 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8657 /* Set the socket back to non-blocking if it was before,
8658 for other operations that support it. */
8659 if (fd_info[fd].flags & FILE_NDELAY)
8661 nblock = 1;
8662 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8665 if (nchars == SOCKET_ERROR)
8667 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8668 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8669 set_errno ();
8672 else
8674 /* Some networked filesystems don't like too large writes, so
8675 break them into smaller chunks. See the Comments section of
8676 the MSDN documentation of WriteFile for details behind the
8677 choice of the value of CHUNK below. See also the thread
8678 http://thread.gmane.org/gmane.comp.version-control.git/145294
8679 in the git mailing list. */
8680 const unsigned char *p = buffer;
8681 const bool is_pipe = (fd < MAXDESC
8682 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8683 == (FILE_PIPE | FILE_NDELAY)));
8684 /* Some programs, notably Node.js's node.exe, seem to never
8685 completely empty the pipe, so writing more than the size of
8686 the pipe's buffer always returns ENOSPC, and we loop forever
8687 between send_process and here. As a workaround, write no
8688 more than the pipe's buffer can hold. */
8689 DWORD pipe_buffer_size;
8690 if (is_pipe)
8692 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8693 NULL, &pipe_buffer_size, NULL, NULL))
8695 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8696 pipe_buffer_size = 4096;
8699 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8701 nchars = 0;
8702 errno = 0;
8703 while (count > 0)
8705 unsigned this_chunk = count < chunk ? count : chunk;
8706 int n = _write (fd, p, this_chunk);
8708 if (n > 0)
8709 nchars += n;
8710 if (n < 0)
8712 /* When there's no buffer space in a pipe that is in the
8713 non-blocking mode, _write returns ENOSPC. We return
8714 EAGAIN instead, which should trigger the logic in
8715 send_process that enters waiting loop and calls
8716 wait_reading_process_output to allow process input to
8717 be accepted during the wait. Those calls to
8718 wait_reading_process_output allow sys_select to
8719 notice when process input becomes available, thus
8720 avoiding deadlock whereby each side of the pipe is
8721 blocked on write, waiting for the other party to read
8722 its end of the pipe. */
8723 if (errno == ENOSPC && is_pipe)
8724 errno = EAGAIN;
8725 if (nchars == 0)
8726 nchars = -1;
8727 break;
8729 else if (n < this_chunk)
8730 break;
8731 count -= n;
8732 p += n;
8736 SAFE_FREE ();
8737 return nchars;
8741 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8743 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8745 /* Return information about network interface IFNAME, or about all
8746 interfaces (if IFNAME is nil). */
8747 static Lisp_Object
8748 network_interface_get_info (Lisp_Object ifname)
8750 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8751 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8752 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8753 Lisp_Object res = Qnil;
8755 if (retval == ERROR_BUFFER_OVERFLOW)
8757 ainfo = xrealloc (ainfo, ainfo_len);
8758 retval = get_adapters_info (ainfo, &ainfo_len);
8761 if (retval == ERROR_SUCCESS)
8763 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8764 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8765 int if_num;
8766 struct sockaddr_in sa;
8768 /* For the below, we need some winsock functions, so make sure
8769 the winsock DLL is loaded. If we cannot successfully load
8770 it, they will have no use of the information we provide,
8771 anyway, so punt. */
8772 if (!winsock_lib && !init_winsock (1))
8773 goto done;
8775 for (adapter = ainfo; adapter; adapter = adapter->Next)
8777 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8778 u_long ip_addr;
8779 /* Present Unix-compatible interface names, instead of the
8780 Windows names, which are really GUIDs not readable by
8781 humans. */
8782 static const char *ifmt[] = {
8783 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8784 "lo", "ifx%d"
8786 enum {
8787 NONE = -1,
8788 ETHERNET = 0,
8789 TOKENRING = 1,
8790 FDDI = 2,
8791 PPP = 3,
8792 SLIP = 4,
8793 WLAN = 5,
8794 LOOPBACK = 6,
8795 OTHER_IF = 7
8796 } ifmt_idx;
8798 switch (adapter->Type)
8800 case MIB_IF_TYPE_ETHERNET:
8801 /* Windows before Vista reports wireless adapters as
8802 Ethernet. Work around by looking at the Description
8803 string. */
8804 if (strstr (adapter->Description, "Wireless "))
8806 ifmt_idx = WLAN;
8807 if_num = wlan_count++;
8809 else
8811 ifmt_idx = ETHERNET;
8812 if_num = eth_count++;
8814 break;
8815 case MIB_IF_TYPE_TOKENRING:
8816 ifmt_idx = TOKENRING;
8817 if_num = tr_count++;
8818 break;
8819 case MIB_IF_TYPE_FDDI:
8820 ifmt_idx = FDDI;
8821 if_num = fddi_count++;
8822 break;
8823 case MIB_IF_TYPE_PPP:
8824 ifmt_idx = PPP;
8825 if_num = ppp_count++;
8826 break;
8827 case MIB_IF_TYPE_SLIP:
8828 ifmt_idx = SLIP;
8829 if_num = sl_count++;
8830 break;
8831 case IF_TYPE_IEEE80211:
8832 ifmt_idx = WLAN;
8833 if_num = wlan_count++;
8834 break;
8835 case MIB_IF_TYPE_LOOPBACK:
8836 if (lo_count < 0)
8838 ifmt_idx = LOOPBACK;
8839 if_num = lo_count++;
8841 else
8842 ifmt_idx = NONE;
8843 break;
8844 default:
8845 ifmt_idx = OTHER_IF;
8846 if_num = ifx_count++;
8847 break;
8849 if (ifmt_idx == NONE)
8850 continue;
8851 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8853 sa.sin_family = AF_INET;
8854 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8855 if (ip_addr == INADDR_NONE)
8857 /* Bogus address, skip this interface. */
8858 continue;
8860 sa.sin_addr.s_addr = ip_addr;
8861 sa.sin_port = 0;
8862 if (NILP (ifname))
8863 res = Fcons (Fcons (build_string (namebuf),
8864 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8865 sizeof (struct sockaddr))),
8866 res);
8867 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8869 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8870 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8871 Lisp_Object flags = Qnil;
8872 int n;
8873 u_long net_mask;
8875 /* Flags. We guess most of them by type, since the
8876 Windows flags are different and hard to get by. */
8877 flags = Fcons (intern ("up"), flags);
8878 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8880 flags = Fcons (intern ("broadcast"), flags);
8881 flags = Fcons (intern ("multicast"), flags);
8883 flags = Fcons (intern ("running"), flags);
8884 if (ifmt_idx == PPP)
8886 flags = Fcons (intern ("pointopoint"), flags);
8887 flags = Fcons (intern ("noarp"), flags);
8889 if (adapter->HaveWins)
8890 flags = Fcons (intern ("WINS"), flags);
8891 if (adapter->DhcpEnabled)
8892 flags = Fcons (intern ("dynamic"), flags);
8894 res = Fcons (flags, res);
8896 /* Hardware address and its family. */
8897 for (n = 0; n < adapter->AddressLength; n++)
8898 p->contents[n] = make_number ((int) adapter->Address[n]);
8899 /* Windows does not support AF_LINK or AF_PACKET family
8900 of addresses. Use an arbitrary family number that is
8901 identical to what GNU/Linux returns. */
8902 res = Fcons (Fcons (make_number (1), hwaddr), res);
8904 /* Network mask. */
8905 sa.sin_family = AF_INET;
8906 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8907 if (net_mask != INADDR_NONE)
8909 sa.sin_addr.s_addr = net_mask;
8910 sa.sin_port = 0;
8911 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8912 sizeof (struct sockaddr)),
8913 res);
8915 else
8916 res = Fcons (Qnil, res);
8918 sa.sin_family = AF_INET;
8919 if (ip_addr != INADDR_NONE)
8921 /* Broadcast address is only reported by
8922 GetAdaptersAddresses, which is of limited
8923 availability. Generate it on our own. */
8924 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8926 sa.sin_addr.s_addr = bcast_addr;
8927 sa.sin_port = 0;
8928 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8929 sizeof (struct sockaddr)),
8930 res);
8932 /* IP address. */
8933 sa.sin_addr.s_addr = ip_addr;
8934 sa.sin_port = 0;
8935 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8936 sizeof (struct sockaddr)),
8937 res);
8939 else
8940 res = Fcons (Qnil, Fcons (Qnil, res));
8943 /* GetAdaptersInfo is documented to not report loopback
8944 interfaces, so we generate one out of thin air. */
8945 if (!lo_count)
8947 sa.sin_family = AF_INET;
8948 sa.sin_port = 0;
8949 if (NILP (ifname))
8951 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8952 res = Fcons (Fcons (build_string ("lo"),
8953 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8954 sizeof (struct sockaddr))),
8955 res);
8957 else if (strcmp (SSDATA (ifname), "lo") == 0)
8959 res = Fcons (Fcons (intern ("running"),
8960 Fcons (intern ("loopback"),
8961 Fcons (intern ("up"), Qnil))), Qnil);
8962 /* 772 is what 3 different GNU/Linux systems report for
8963 the loopback interface. */
8964 res = Fcons (Fcons (make_number (772),
8965 Fmake_vector (make_number (6),
8966 make_number (0))),
8967 res);
8968 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8969 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8970 sizeof (struct sockaddr)),
8971 res);
8972 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8973 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8974 sizeof (struct sockaddr)),
8975 res);
8976 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8977 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8978 sizeof (struct sockaddr)),
8979 res);
8985 done:
8986 xfree (ainfo);
8987 return res;
8990 Lisp_Object
8991 network_interface_list (void)
8993 return network_interface_get_info (Qnil);
8996 Lisp_Object
8997 network_interface_info (Lisp_Object ifname)
8999 CHECK_STRING (ifname);
9000 return network_interface_get_info (ifname);
9004 /* The Windows CRT functions are "optimized for speed", so they don't
9005 check for timezone and DST changes if they were last called less
9006 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9007 all Emacs features that repeatedly call time functions (e.g.,
9008 display-time) are in real danger of missing timezone and DST
9009 changes. Calling tzset before each localtime call fixes that. */
9010 struct tm *
9011 sys_localtime (const time_t *t)
9013 tzset ();
9014 return localtime (t);
9019 /* Try loading LIBRARY_ID from the file(s) specified in
9020 Vdynamic_library_alist. If the library is loaded successfully,
9021 return the handle of the DLL, and record the filename in the
9022 property :loaded-from of LIBRARY_ID. If the library could not be
9023 found, or when it was already loaded (because the handle is not
9024 recorded anywhere, and so is lost after use), return NULL.
9026 We could also save the handle in :loaded-from, but currently
9027 there's no use case for it. */
9028 HMODULE
9029 w32_delayed_load (Lisp_Object library_id)
9031 HMODULE dll_handle = NULL;
9033 CHECK_SYMBOL (library_id);
9035 if (CONSP (Vdynamic_library_alist)
9036 && NILP (Fassq (library_id, Vlibrary_cache)))
9038 Lisp_Object found = Qnil;
9039 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9041 if (CONSP (dlls))
9042 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9044 Lisp_Object dll = XCAR (dlls);
9045 char name[MAX_UTF8_PATH];
9046 DWORD res = -1;
9048 CHECK_STRING (dll);
9049 dll = ENCODE_FILE (dll);
9050 if (w32_unicode_filenames)
9052 wchar_t name_w[MAX_PATH];
9054 filename_to_utf16 (SSDATA (dll), name_w);
9055 dll_handle = LoadLibraryW (name_w);
9056 if (dll_handle)
9058 res = GetModuleFileNameW (dll_handle, name_w,
9059 sizeof (name_w));
9060 if (res > 0)
9061 filename_from_utf16 (name_w, name);
9064 else
9066 char name_a[MAX_PATH];
9068 filename_to_ansi (SSDATA (dll), name_a);
9069 dll_handle = LoadLibraryA (name_a);
9070 if (dll_handle)
9072 res = GetModuleFileNameA (dll_handle, name_a,
9073 sizeof (name_a));
9074 if (res > 0)
9075 filename_from_ansi (name_a, name);
9078 if (dll_handle)
9080 ptrdiff_t len = strlen (name);
9081 found = Fcons (dll,
9082 (res > 0)
9083 /* Possibly truncated */
9084 ? make_specified_string (name, -1, len, 1)
9085 : Qnil);
9086 /* This prevents thread start and end notifications
9087 from being sent to the DLL, for every thread we
9088 start. We don't need those notifications because
9089 threads we create never use any of these DLLs, only
9090 the main thread uses them. This is supposed to
9091 speed up thread creation. */
9092 DisableThreadLibraryCalls (dll_handle);
9093 break;
9097 Fput (library_id, QCloaded_from, found);
9100 return dll_handle;
9104 void
9105 check_windows_init_file (void)
9107 /* A common indication that Emacs is not installed properly is when
9108 it cannot find the Windows installation file. If this file does
9109 not exist in the expected place, tell the user. */
9111 if (!noninteractive && !inhibit_window_system
9112 /* Vload_path is not yet initialized when we are loading
9113 loadup.el. */
9114 && NILP (Vpurify_flag))
9116 Lisp_Object init_file;
9117 int fd;
9119 /* Implementation note: this function runs early during Emacs
9120 startup, before startup.el is run. So Vload_path is still in
9121 its initial unibyte form, but it holds UTF-8 encoded file
9122 names, since init_callproc was already called. So we do not
9123 need to ENCODE_FILE here, but we do need to convert the file
9124 names from UTF-8 to ANSI. */
9125 init_file = build_string ("term/w32-win");
9126 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9127 if (fd < 0)
9129 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9130 char *init_file_name = SSDATA (init_file);
9131 char *load_path = SSDATA (load_path_print);
9132 char *buffer = alloca (1024
9133 + strlen (init_file_name)
9134 + strlen (load_path));
9135 char *msg = buffer;
9136 int needed;
9138 sprintf (buffer,
9139 "The Emacs Windows initialization file \"%s.el\" "
9140 "could not be found in your Emacs installation. "
9141 "Emacs checked the following directories for this file:\n"
9142 "\n%s\n\n"
9143 "When Emacs cannot find this file, it usually means that it "
9144 "was not installed properly, or its distribution file was "
9145 "not unpacked properly.\nSee the README.W32 file in the "
9146 "top-level Emacs directory for more information.",
9147 init_file_name, load_path);
9148 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9149 buffer, -1, NULL, 0);
9150 if (needed > 0)
9152 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9154 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9155 -1, msg_w, needed);
9156 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9157 NULL, 0, NULL, NULL);
9158 if (needed > 0)
9160 char *msg_a = alloca (needed + 1);
9162 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9163 NULL, NULL);
9164 msg = msg_a;
9167 MessageBox (NULL,
9168 msg,
9169 "Emacs Abort Dialog",
9170 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9171 /* Use the low-level system abort. */
9172 abort ();
9174 else
9176 _close (fd);
9181 void
9182 term_ntproc (int ignored)
9184 (void)ignored;
9186 term_timers ();
9188 /* shutdown the socket interface if necessary */
9189 term_winsock ();
9191 term_w32select ();
9194 void
9195 init_ntproc (int dumping)
9197 sigset_t initial_mask = 0;
9199 /* Initialize the socket interface now if available and requested by
9200 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9201 delayed until open-network-stream is called (w32-has-winsock can
9202 also be used to dynamically load or reload winsock).
9204 Conveniently, init_environment is called before us, so
9205 PRELOAD_WINSOCK can be set in the registry. */
9207 /* Always initialize this correctly. */
9208 winsock_lib = NULL;
9210 if (getenv ("PRELOAD_WINSOCK") != NULL)
9211 init_winsock (TRUE);
9213 /* Initial preparation for subprocess support: replace our standard
9214 handles with non-inheritable versions. */
9216 HANDLE parent;
9217 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9218 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9219 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9221 parent = GetCurrentProcess ();
9223 /* ignore errors when duplicating and closing; typically the
9224 handles will be invalid when running as a gui program. */
9225 DuplicateHandle (parent,
9226 GetStdHandle (STD_INPUT_HANDLE),
9227 parent,
9228 &stdin_save,
9230 FALSE,
9231 DUPLICATE_SAME_ACCESS);
9233 DuplicateHandle (parent,
9234 GetStdHandle (STD_OUTPUT_HANDLE),
9235 parent,
9236 &stdout_save,
9238 FALSE,
9239 DUPLICATE_SAME_ACCESS);
9241 DuplicateHandle (parent,
9242 GetStdHandle (STD_ERROR_HANDLE),
9243 parent,
9244 &stderr_save,
9246 FALSE,
9247 DUPLICATE_SAME_ACCESS);
9249 fclose (stdin);
9250 fclose (stdout);
9251 fclose (stderr);
9253 if (stdin_save != INVALID_HANDLE_VALUE)
9254 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9255 else
9256 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9257 _fdopen (0, "r");
9259 if (stdout_save != INVALID_HANDLE_VALUE)
9260 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9261 else
9262 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9263 _fdopen (1, "w");
9265 if (stderr_save != INVALID_HANDLE_VALUE)
9266 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9267 else
9268 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9269 _fdopen (2, "w");
9272 /* unfortunately, atexit depends on implementation of malloc */
9273 /* atexit (term_ntproc); */
9274 if (!dumping)
9276 /* Make sure we start with all signals unblocked. */
9277 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9278 signal (SIGABRT, term_ntproc);
9280 init_timers ();
9282 /* determine which drives are fixed, for GetCachedVolumeInformation */
9284 /* GetDriveType must have trailing backslash. */
9285 char drive[] = "A:\\";
9287 /* Loop over all possible drive letters */
9288 while (*drive <= 'Z')
9290 /* Record if this drive letter refers to a fixed drive. */
9291 fixed_drives[DRIVE_INDEX (*drive)] =
9292 (GetDriveType (drive) == DRIVE_FIXED);
9294 (*drive)++;
9297 /* Reset the volume info cache. */
9298 volume_cache = NULL;
9303 shutdown_handler ensures that buffers' autosave files are
9304 up to date when the user logs off, or the system shuts down.
9306 static BOOL WINAPI
9307 shutdown_handler (DWORD type)
9309 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9310 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9311 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9312 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9314 /* Shut down cleanly, making sure autosave files are up to date. */
9315 shut_down_emacs (0, Qnil);
9318 /* Allow other handlers to handle this signal. */
9319 return FALSE;
9322 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9323 NT, return a handle to GDI32.DLL. */
9324 HANDLE
9325 maybe_load_unicows_dll (void)
9327 if (os_subtype == OS_9X)
9329 HANDLE ret = LoadLibrary ("Unicows.dll");
9330 if (ret)
9332 /* These two functions are present on Windows 9X as stubs
9333 that always fail. We need the real implementations from
9334 UNICOWS.DLL, so we must call these functions through
9335 pointers, and assign the correct addresses to these
9336 pointers at program startup (see emacs.c, which calls
9337 this function early on). */
9338 pMultiByteToWideChar =
9339 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9340 pWideCharToMultiByte =
9341 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9342 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9343 return ret;
9345 else
9347 int button;
9349 button = MessageBox (NULL,
9350 "Emacs cannot load the UNICOWS.DLL library.\n"
9351 "This library is essential for using Emacs\n"
9352 "on this system. You need to install it.\n\n"
9353 "Emacs will exit when you click OK.",
9354 "Emacs cannot load UNICOWS.DLL",
9355 MB_ICONERROR | MB_TASKMODAL
9356 | MB_SETFOREGROUND | MB_OK);
9357 switch (button)
9359 case IDOK:
9360 default:
9361 exit (1);
9365 else
9367 /* On NT family of Windows, these two functions are always
9368 linked in, so we just assign their addresses to the 2
9369 pointers; no need for the LoadLibrary dance. */
9370 pMultiByteToWideChar = MultiByteToWideChar;
9371 pWideCharToMultiByte = WideCharToMultiByte;
9372 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9373 if (w32_major_version < 5)
9374 multiByteToWideCharFlags = 0;
9375 else
9376 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9377 return LoadLibrary ("Gdi32.dll");
9382 globals_of_w32 is used to initialize those global variables that
9383 must always be initialized on startup even when the global variable
9384 initialized is non zero (see the function main in emacs.c).
9386 void
9387 globals_of_w32 (void)
9389 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9391 get_process_times_fn = (GetProcessTimes_Proc)
9392 GetProcAddress (kernel32, "GetProcessTimes");
9394 DEFSYM (QCloaded_from, ":loaded-from");
9396 g_b_init_is_windows_9x = 0;
9397 g_b_init_open_process_token = 0;
9398 g_b_init_get_token_information = 0;
9399 g_b_init_lookup_account_sid = 0;
9400 g_b_init_get_sid_sub_authority = 0;
9401 g_b_init_get_sid_sub_authority_count = 0;
9402 g_b_init_get_security_info = 0;
9403 g_b_init_get_file_security_w = 0;
9404 g_b_init_get_file_security_a = 0;
9405 g_b_init_get_security_descriptor_owner = 0;
9406 g_b_init_get_security_descriptor_group = 0;
9407 g_b_init_is_valid_sid = 0;
9408 g_b_init_create_toolhelp32_snapshot = 0;
9409 g_b_init_process32_first = 0;
9410 g_b_init_process32_next = 0;
9411 g_b_init_open_thread_token = 0;
9412 g_b_init_impersonate_self = 0;
9413 g_b_init_revert_to_self = 0;
9414 g_b_init_get_process_memory_info = 0;
9415 g_b_init_get_process_working_set_size = 0;
9416 g_b_init_global_memory_status = 0;
9417 g_b_init_global_memory_status_ex = 0;
9418 g_b_init_equal_sid = 0;
9419 g_b_init_copy_sid = 0;
9420 g_b_init_get_length_sid = 0;
9421 g_b_init_get_native_system_info = 0;
9422 g_b_init_get_system_times = 0;
9423 g_b_init_create_symbolic_link_w = 0;
9424 g_b_init_create_symbolic_link_a = 0;
9425 g_b_init_get_security_descriptor_dacl = 0;
9426 g_b_init_convert_sd_to_sddl = 0;
9427 g_b_init_convert_sddl_to_sd = 0;
9428 g_b_init_is_valid_security_descriptor = 0;
9429 g_b_init_set_file_security_w = 0;
9430 g_b_init_set_file_security_a = 0;
9431 g_b_init_set_named_security_info_w = 0;
9432 g_b_init_set_named_security_info_a = 0;
9433 g_b_init_get_adapters_info = 0;
9434 g_b_init_compare_string_w = 0;
9435 num_of_processors = 0;
9436 /* The following sets a handler for shutdown notifications for
9437 console apps. This actually applies to Emacs in both console and
9438 GUI modes, since we had to fool windows into thinking emacs is a
9439 console application to get console mode to work. */
9440 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9442 /* "None" is the default group name on standalone workstations. */
9443 strcpy (dflt_group_name, "None");
9445 /* Reset, in case it has some value inherited from dump time. */
9446 w32_stat_get_owner_group = 0;
9448 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9449 (a.k.a. "wide") APIs to invoke functions that accept file
9450 names. */
9451 if (is_windows_9x ())
9452 w32_unicode_filenames = 0;
9453 else
9454 w32_unicode_filenames = 1;
9456 #ifdef HAVE_MODULES
9457 extern void dynlib_reset_last_error (void);
9458 dynlib_reset_last_error ();
9459 #endif
9461 w32_crypto_hprov = (HCRYPTPROV)0;
9464 /* For make-serial-process */
9466 serial_open (Lisp_Object port_obj)
9468 char *port = SSDATA (port_obj);
9469 HANDLE hnd;
9470 child_process *cp;
9471 int fd = -1;
9473 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9474 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9475 if (hnd == INVALID_HANDLE_VALUE)
9476 error ("Could not open %s", port);
9477 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9478 if (fd == -1)
9479 error ("Could not open %s", port);
9481 cp = new_child ();
9482 if (!cp)
9483 error ("Could not create child process");
9484 cp->fd = fd;
9485 cp->status = STATUS_READ_ACKNOWLEDGED;
9486 fd_info[ fd ].hnd = hnd;
9487 fd_info[ fd ].flags |=
9488 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9489 if (fd_info[ fd ].cp != NULL)
9491 error ("fd_info[fd = %d] is already in use", fd);
9493 fd_info[ fd ].cp = cp;
9494 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9495 if (cp->ovl_read.hEvent == NULL)
9496 error ("Could not create read event");
9497 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9498 if (cp->ovl_write.hEvent == NULL)
9499 error ("Could not create write event");
9501 return fd;
9504 /* For serial-process-configure */
9505 void
9506 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9508 Lisp_Object childp2 = Qnil;
9509 Lisp_Object tem = Qnil;
9510 HANDLE hnd;
9511 DCB dcb;
9512 COMMTIMEOUTS ct;
9513 char summary[4] = "???"; /* This usually becomes "8N1". */
9515 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9516 error ("Not a serial process");
9517 hnd = fd_info[ p->outfd ].hnd;
9519 childp2 = Fcopy_sequence (p->childp);
9521 /* Initialize timeouts for blocking read and blocking write. */
9522 if (!GetCommTimeouts (hnd, &ct))
9523 error ("GetCommTimeouts() failed");
9524 ct.ReadIntervalTimeout = 0;
9525 ct.ReadTotalTimeoutMultiplier = 0;
9526 ct.ReadTotalTimeoutConstant = 0;
9527 ct.WriteTotalTimeoutMultiplier = 0;
9528 ct.WriteTotalTimeoutConstant = 0;
9529 if (!SetCommTimeouts (hnd, &ct))
9530 error ("SetCommTimeouts() failed");
9531 /* Read port attributes and prepare default configuration. */
9532 memset (&dcb, 0, sizeof (dcb));
9533 dcb.DCBlength = sizeof (DCB);
9534 if (!GetCommState (hnd, &dcb))
9535 error ("GetCommState() failed");
9536 dcb.fBinary = TRUE;
9537 dcb.fNull = FALSE;
9538 dcb.fAbortOnError = FALSE;
9539 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9540 dcb.ErrorChar = 0;
9541 dcb.EofChar = 0;
9542 dcb.EvtChar = 0;
9544 /* Configure speed. */
9545 if (!NILP (Fplist_member (contact, QCspeed)))
9546 tem = Fplist_get (contact, QCspeed);
9547 else
9548 tem = Fplist_get (p->childp, QCspeed);
9549 CHECK_NUMBER (tem);
9550 dcb.BaudRate = XINT (tem);
9551 childp2 = Fplist_put (childp2, QCspeed, tem);
9553 /* Configure bytesize. */
9554 if (!NILP (Fplist_member (contact, QCbytesize)))
9555 tem = Fplist_get (contact, QCbytesize);
9556 else
9557 tem = Fplist_get (p->childp, QCbytesize);
9558 if (NILP (tem))
9559 tem = make_number (8);
9560 CHECK_NUMBER (tem);
9561 if (XINT (tem) != 7 && XINT (tem) != 8)
9562 error (":bytesize must be nil (8), 7, or 8");
9563 dcb.ByteSize = XINT (tem);
9564 summary[0] = XINT (tem) + '0';
9565 childp2 = Fplist_put (childp2, QCbytesize, tem);
9567 /* Configure parity. */
9568 if (!NILP (Fplist_member (contact, QCparity)))
9569 tem = Fplist_get (contact, QCparity);
9570 else
9571 tem = Fplist_get (p->childp, QCparity);
9572 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9573 error (":parity must be nil (no parity), `even', or `odd'");
9574 dcb.fParity = FALSE;
9575 dcb.Parity = NOPARITY;
9576 dcb.fErrorChar = FALSE;
9577 if (NILP (tem))
9579 summary[1] = 'N';
9581 else if (EQ (tem, Qeven))
9583 summary[1] = 'E';
9584 dcb.fParity = TRUE;
9585 dcb.Parity = EVENPARITY;
9586 dcb.fErrorChar = TRUE;
9588 else if (EQ (tem, Qodd))
9590 summary[1] = 'O';
9591 dcb.fParity = TRUE;
9592 dcb.Parity = ODDPARITY;
9593 dcb.fErrorChar = TRUE;
9595 childp2 = Fplist_put (childp2, QCparity, tem);
9597 /* Configure stopbits. */
9598 if (!NILP (Fplist_member (contact, QCstopbits)))
9599 tem = Fplist_get (contact, QCstopbits);
9600 else
9601 tem = Fplist_get (p->childp, QCstopbits);
9602 if (NILP (tem))
9603 tem = make_number (1);
9604 CHECK_NUMBER (tem);
9605 if (XINT (tem) != 1 && XINT (tem) != 2)
9606 error (":stopbits must be nil (1 stopbit), 1, or 2");
9607 summary[2] = XINT (tem) + '0';
9608 if (XINT (tem) == 1)
9609 dcb.StopBits = ONESTOPBIT;
9610 else if (XINT (tem) == 2)
9611 dcb.StopBits = TWOSTOPBITS;
9612 childp2 = Fplist_put (childp2, QCstopbits, tem);
9614 /* Configure flowcontrol. */
9615 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9616 tem = Fplist_get (contact, QCflowcontrol);
9617 else
9618 tem = Fplist_get (p->childp, QCflowcontrol);
9619 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9620 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9621 dcb.fOutxCtsFlow = FALSE;
9622 dcb.fOutxDsrFlow = FALSE;
9623 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9624 dcb.fDsrSensitivity = FALSE;
9625 dcb.fTXContinueOnXoff = FALSE;
9626 dcb.fOutX = FALSE;
9627 dcb.fInX = FALSE;
9628 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9629 dcb.XonChar = 17; /* Control-Q */
9630 dcb.XoffChar = 19; /* Control-S */
9631 if (NILP (tem))
9633 /* Already configured. */
9635 else if (EQ (tem, Qhw))
9637 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9638 dcb.fOutxCtsFlow = TRUE;
9640 else if (EQ (tem, Qsw))
9642 dcb.fOutX = TRUE;
9643 dcb.fInX = TRUE;
9645 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9647 /* Activate configuration. */
9648 if (!SetCommState (hnd, &dcb))
9649 error ("SetCommState() failed");
9651 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9652 pset_childp (p, childp2);
9655 /* For make-pipe-process */
9656 void
9657 register_aux_fd (int infd)
9659 child_process *cp;
9661 cp = new_child ();
9662 if (!cp)
9663 error ("Could not create child process");
9664 cp->fd = infd;
9665 cp->status = STATUS_READ_ACKNOWLEDGED;
9667 if (fd_info[ infd ].cp != NULL)
9669 error ("fd_info[fd = %d] is already in use", infd);
9671 fd_info[ infd ].cp = cp;
9672 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9675 #ifdef HAVE_GNUTLS
9677 ssize_t
9678 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9680 int n, err;
9681 struct Lisp_Process *process = (struct Lisp_Process *)p;
9682 int fd = process->infd;
9684 n = sys_read (fd, (char*)buf, sz);
9686 if (n >= 0)
9687 return n;
9689 err = errno;
9691 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9692 if (err == EWOULDBLOCK)
9693 err = EAGAIN;
9695 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9697 return -1;
9700 ssize_t
9701 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9703 struct Lisp_Process *process = (struct Lisp_Process *)p;
9704 int fd = process->outfd;
9705 ssize_t n = sys_write (fd, buf, sz);
9707 /* 0 or more bytes written means everything went fine. */
9708 if (n >= 0)
9709 return n;
9711 /* Negative bytes written means we got an error in errno.
9712 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9713 emacs_gnutls_transport_set_errno (process->gnutls_state,
9714 errno == EWOULDBLOCK ? EAGAIN : errno);
9716 return -1;
9718 #endif /* HAVE_GNUTLS */
9720 /* end of w32.c */