; Update ChangeLog.2 and AUTHORS files
[emacs.git] / src / w32.c
blob7c57693cf3d3424ff7516e5a19415b7de8e8908d
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 /* Initialize the codepage used for decoding file names. This is
1497 needed to undo the value recorded during dumping, which might not
1498 be correct when we run the dumped Emacs. */
1499 void
1500 w32_init_file_name_codepage (void)
1502 file_name_codepage = CP_ACP;
1503 w32_ansi_code_page = CP_ACP;
1506 /* Produce a Windows ANSI codepage suitable for encoding file names.
1507 Return the information about that codepage in CP_INFO. */
1509 codepage_for_filenames (CPINFO *cp_info)
1511 /* A simple cache to avoid calling GetCPInfo every time we need to
1512 encode/decode a file name. The file-name encoding is not
1513 supposed to be changed too frequently, if ever. */
1514 static Lisp_Object last_file_name_encoding;
1515 static CPINFO cp;
1516 Lisp_Object current_encoding;
1518 current_encoding = Vfile_name_coding_system;
1519 if (NILP (current_encoding))
1520 current_encoding = Vdefault_file_name_coding_system;
1522 if (!EQ (last_file_name_encoding, current_encoding)
1523 || NILP (last_file_name_encoding))
1525 /* Default to the current ANSI codepage. */
1526 file_name_codepage = w32_ansi_code_page;
1528 if (!NILP (current_encoding))
1530 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1531 char *cp = NULL, *end;
1532 int cpnum;
1534 if (strncmp (cpname, "cp", 2) == 0)
1535 cp = cpname + 2;
1536 else if (strncmp (cpname, "windows-", 8) == 0)
1537 cp = cpname + 8;
1539 if (cp)
1541 end = cp;
1542 cpnum = strtol (cp, &end, 10);
1543 if (cpnum && *end == '\0' && end - cp >= 2)
1544 file_name_codepage = cpnum;
1548 if (!file_name_codepage)
1549 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1551 if (!GetCPInfo (file_name_codepage, &cp))
1553 file_name_codepage = CP_ACP;
1554 if (!GetCPInfo (file_name_codepage, &cp))
1555 emacs_abort ();
1558 /* Cache the new value. */
1559 last_file_name_encoding = current_encoding;
1561 if (cp_info)
1562 *cp_info = cp;
1564 return file_name_codepage;
1568 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1570 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1571 -1, fn_out, MAX_PATH);
1573 if (!result)
1575 DWORD err = GetLastError ();
1577 switch (err)
1579 case ERROR_INVALID_FLAGS:
1580 case ERROR_INVALID_PARAMETER:
1581 errno = EINVAL;
1582 break;
1583 case ERROR_INSUFFICIENT_BUFFER:
1584 case ERROR_NO_UNICODE_TRANSLATION:
1585 default:
1586 errno = ENOENT;
1587 break;
1589 return -1;
1591 return 0;
1595 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1597 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1598 fn_out, MAX_UTF8_PATH, NULL, NULL);
1600 if (!result)
1602 DWORD err = GetLastError ();
1604 switch (err)
1606 case ERROR_INVALID_FLAGS:
1607 case ERROR_INVALID_PARAMETER:
1608 errno = EINVAL;
1609 break;
1610 case ERROR_INSUFFICIENT_BUFFER:
1611 case ERROR_NO_UNICODE_TRANSLATION:
1612 default:
1613 errno = ENOENT;
1614 break;
1616 return -1;
1618 return 0;
1622 filename_to_ansi (const char *fn_in, char *fn_out)
1624 wchar_t fn_utf16[MAX_PATH];
1626 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1628 int result;
1629 int codepage = codepage_for_filenames (NULL);
1631 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1632 fn_out, MAX_PATH, NULL, NULL);
1633 if (!result)
1635 DWORD err = GetLastError ();
1637 switch (err)
1639 case ERROR_INVALID_FLAGS:
1640 case ERROR_INVALID_PARAMETER:
1641 errno = EINVAL;
1642 break;
1643 case ERROR_INSUFFICIENT_BUFFER:
1644 case ERROR_NO_UNICODE_TRANSLATION:
1645 default:
1646 errno = ENOENT;
1647 break;
1649 return -1;
1651 return 0;
1653 return -1;
1657 filename_from_ansi (const char *fn_in, char *fn_out)
1659 wchar_t fn_utf16[MAX_PATH];
1660 int codepage = codepage_for_filenames (NULL);
1661 int result = pMultiByteToWideChar (codepage, multiByteToWideCharFlags, fn_in,
1662 -1, fn_utf16, MAX_PATH);
1664 if (!result)
1666 DWORD err = GetLastError ();
1668 switch (err)
1670 case ERROR_INVALID_FLAGS:
1671 case ERROR_INVALID_PARAMETER:
1672 errno = EINVAL;
1673 break;
1674 case ERROR_INSUFFICIENT_BUFFER:
1675 case ERROR_NO_UNICODE_TRANSLATION:
1676 default:
1677 errno = ENOENT;
1678 break;
1680 return -1;
1682 return filename_from_utf16 (fn_utf16, fn_out);
1687 /* The directory where we started, in UTF-8. */
1688 static char startup_dir[MAX_UTF8_PATH];
1690 /* Get the current working directory. */
1691 char *
1692 getcwd (char *dir, int dirsize)
1694 if (!dirsize)
1696 errno = EINVAL;
1697 return NULL;
1699 if (dirsize <= strlen (startup_dir))
1701 errno = ERANGE;
1702 return NULL;
1704 #if 0
1705 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1706 return dir;
1707 return NULL;
1708 #else
1709 /* Emacs doesn't actually change directory itself, it stays in the
1710 same directory where it was started. */
1711 strcpy (dir, startup_dir);
1712 return dir;
1713 #endif
1716 /* Emulate getloadavg. */
1718 struct load_sample {
1719 time_t sample_time;
1720 ULONGLONG idle;
1721 ULONGLONG kernel;
1722 ULONGLONG user;
1725 /* Number of processors on this machine. */
1726 static unsigned num_of_processors;
1728 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1729 static struct load_sample samples[16*60];
1730 static int first_idx = -1, last_idx = -1;
1731 static int max_idx = ARRAYELTS (samples);
1733 static int
1734 buf_next (int from)
1736 int next_idx = from + 1;
1738 if (next_idx >= max_idx)
1739 next_idx = 0;
1741 return next_idx;
1744 static int
1745 buf_prev (int from)
1747 int prev_idx = from - 1;
1749 if (prev_idx < 0)
1750 prev_idx = max_idx - 1;
1752 return prev_idx;
1755 static void
1756 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1758 SYSTEM_INFO sysinfo;
1759 FILETIME ft_idle, ft_user, ft_kernel;
1761 /* Initialize the number of processors on this machine. */
1762 if (num_of_processors <= 0)
1764 get_native_system_info (&sysinfo);
1765 num_of_processors = sysinfo.dwNumberOfProcessors;
1766 if (num_of_processors <= 0)
1768 GetSystemInfo (&sysinfo);
1769 num_of_processors = sysinfo.dwNumberOfProcessors;
1771 if (num_of_processors <= 0)
1772 num_of_processors = 1;
1775 /* TODO: Take into account threads that are ready to run, by
1776 sampling the "\System\Processor Queue Length" performance
1777 counter. The code below accounts only for threads that are
1778 actually running. */
1780 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1782 ULARGE_INTEGER uidle, ukernel, uuser;
1784 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1785 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1786 memcpy (&uuser, &ft_user, sizeof (ft_user));
1787 *idle = uidle.QuadPart;
1788 *kernel = ukernel.QuadPart;
1789 *user = uuser.QuadPart;
1791 else
1793 *idle = 0;
1794 *kernel = 0;
1795 *user = 0;
1799 /* Produce the load average for a given time interval, using the
1800 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1801 1-minute, 5-minute, or 15-minute average, respectively. */
1802 static double
1803 getavg (int which)
1805 double retval = -1.0;
1806 double tdiff;
1807 int idx;
1808 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1809 time_t now = samples[last_idx].sample_time;
1811 if (first_idx != last_idx)
1813 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1815 tdiff = difftime (now, samples[idx].sample_time);
1816 if (tdiff >= span - 2*DBL_EPSILON*now)
1818 long double sys =
1819 samples[last_idx].kernel + samples[last_idx].user
1820 - (samples[idx].kernel + samples[idx].user);
1821 long double idl = samples[last_idx].idle - samples[idx].idle;
1823 retval = (1.0 - idl / sys) * num_of_processors;
1824 break;
1826 if (idx == first_idx)
1827 break;
1831 return retval;
1835 getloadavg (double loadavg[], int nelem)
1837 int elem;
1838 ULONGLONG idle, kernel, user;
1839 time_t now = time (NULL);
1841 /* If system time jumped back for some reason, delete all samples
1842 whose time is later than the current wall-clock time. This
1843 prevents load average figures from becoming frozen for prolonged
1844 periods of time, when system time is reset backwards. */
1845 if (last_idx >= 0)
1847 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1849 if (last_idx == first_idx)
1851 first_idx = last_idx = -1;
1852 break;
1854 last_idx = buf_prev (last_idx);
1858 /* Store another sample. We ignore samples that are less than 1 sec
1859 apart. */
1860 if (last_idx < 0
1861 || (difftime (now, samples[last_idx].sample_time)
1862 >= 1.0 - 2*DBL_EPSILON*now))
1864 sample_system_load (&idle, &kernel, &user);
1865 last_idx = buf_next (last_idx);
1866 samples[last_idx].sample_time = now;
1867 samples[last_idx].idle = idle;
1868 samples[last_idx].kernel = kernel;
1869 samples[last_idx].user = user;
1870 /* If the buffer has more that 15 min worth of samples, discard
1871 the old ones. */
1872 if (first_idx == -1)
1873 first_idx = last_idx;
1874 while (first_idx != last_idx
1875 && (difftime (now, samples[first_idx].sample_time)
1876 >= 15.0*60 + 2*DBL_EPSILON*now))
1877 first_idx = buf_next (first_idx);
1880 for (elem = 0; elem < nelem; elem++)
1882 double avg = getavg (elem);
1884 if (avg < 0)
1885 break;
1886 loadavg[elem] = avg;
1889 return elem;
1892 /* Emulate getpwuid, getpwnam and others. */
1894 #define PASSWD_FIELD_SIZE 256
1896 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1897 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1898 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1899 static char dflt_passwd_dir[MAX_UTF8_PATH];
1900 static char dflt_passwd_shell[MAX_UTF8_PATH];
1902 static struct passwd dflt_passwd =
1904 dflt_passwd_name,
1905 dflt_passwd_passwd,
1909 dflt_passwd_gecos,
1910 dflt_passwd_dir,
1911 dflt_passwd_shell,
1914 static char dflt_group_name[GNLEN+1];
1916 static struct group dflt_group =
1918 /* When group information is not available, we return this as the
1919 group for all files. */
1920 dflt_group_name,
1924 unsigned
1925 getuid (void)
1927 return dflt_passwd.pw_uid;
1930 unsigned
1931 geteuid (void)
1933 /* I could imagine arguing for checking to see whether the user is
1934 in the Administrators group and returning a UID of 0 for that
1935 case, but I don't know how wise that would be in the long run. */
1936 return getuid ();
1939 unsigned
1940 getgid (void)
1942 return dflt_passwd.pw_gid;
1945 unsigned
1946 getegid (void)
1948 return getgid ();
1951 struct passwd *
1952 getpwuid (unsigned uid)
1954 if (uid == dflt_passwd.pw_uid)
1955 return &dflt_passwd;
1956 return NULL;
1959 struct group *
1960 getgrgid (gid_t gid)
1962 return &dflt_group;
1965 struct passwd *
1966 getpwnam (char *name)
1968 struct passwd *pw;
1970 pw = getpwuid (getuid ());
1971 if (!pw)
1972 return pw;
1974 if (xstrcasecmp (name, pw->pw_name))
1975 return NULL;
1977 return pw;
1980 static void
1981 init_user_info (void)
1983 /* Find the user's real name by opening the process token and
1984 looking up the name associated with the user-sid in that token.
1986 Use the relative portion of the identifier authority value from
1987 the user-sid as the user id value (same for group id using the
1988 primary group sid from the process token). */
1990 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1991 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1992 DWORD glength = sizeof (gname);
1993 HANDLE token = NULL;
1994 SID_NAME_USE user_type;
1995 unsigned char *buf = NULL;
1996 DWORD blen = 0;
1997 TOKEN_USER user_token;
1998 TOKEN_PRIMARY_GROUP group_token;
1999 BOOL result;
2001 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
2002 if (result)
2004 result = get_token_information (token, TokenUser, NULL, 0, &blen);
2005 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2007 buf = xmalloc (blen);
2008 result = get_token_information (token, TokenUser,
2009 (LPVOID)buf, blen, &needed);
2010 if (result)
2012 memcpy (&user_token, buf, sizeof (user_token));
2013 result = lookup_account_sid (NULL, user_token.User.Sid,
2014 uname, &ulength,
2015 domain, &dlength, &user_type);
2018 else
2019 result = FALSE;
2021 if (result)
2023 strcpy (dflt_passwd.pw_name, uname);
2024 /* Determine a reasonable uid value. */
2025 if (xstrcasecmp ("administrator", uname) == 0)
2027 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2028 dflt_passwd.pw_gid = 513; /* well-known None gid */
2030 else
2032 /* Use the last sub-authority value of the RID, the relative
2033 portion of the SID, as user/group ID. */
2034 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2036 /* Get group id and name. */
2037 result = get_token_information (token, TokenPrimaryGroup,
2038 (LPVOID)buf, blen, &needed);
2039 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2041 buf = xrealloc (buf, blen = needed);
2042 result = get_token_information (token, TokenPrimaryGroup,
2043 (LPVOID)buf, blen, &needed);
2045 if (result)
2047 memcpy (&group_token, buf, sizeof (group_token));
2048 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2049 dlength = sizeof (domain);
2050 /* If we can get at the real Primary Group name, use that.
2051 Otherwise, the default group name was already set to
2052 "None" in globals_of_w32. */
2053 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2054 gname, &glength, NULL, &dlength,
2055 &user_type))
2056 strcpy (dflt_group_name, gname);
2058 else
2059 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2062 /* If security calls are not supported (presumably because we
2063 are running under Windows 9X), fallback to this: */
2064 else if (GetUserName (uname, &ulength))
2066 strcpy (dflt_passwd.pw_name, uname);
2067 if (xstrcasecmp ("administrator", uname) == 0)
2068 dflt_passwd.pw_uid = 0;
2069 else
2070 dflt_passwd.pw_uid = 123;
2071 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2073 else
2075 strcpy (dflt_passwd.pw_name, "unknown");
2076 dflt_passwd.pw_uid = 123;
2077 dflt_passwd.pw_gid = 123;
2079 dflt_group.gr_gid = dflt_passwd.pw_gid;
2081 /* Set dir and shell from environment variables. */
2082 if (w32_unicode_filenames)
2084 wchar_t *home = _wgetenv (L"HOME");
2085 wchar_t *shell = _wgetenv (L"SHELL");
2087 /* Ensure HOME and SHELL are defined. */
2088 if (home == NULL)
2089 emacs_abort ();
2090 if (shell == NULL)
2091 emacs_abort ();
2092 filename_from_utf16 (home, dflt_passwd.pw_dir);
2093 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2095 else
2097 char *home = getenv ("HOME");
2098 char *shell = getenv ("SHELL");
2100 if (home == NULL)
2101 emacs_abort ();
2102 if (shell == NULL)
2103 emacs_abort ();
2104 filename_from_ansi (home, dflt_passwd.pw_dir);
2105 filename_from_ansi (shell, dflt_passwd.pw_shell);
2108 xfree (buf);
2109 if (token)
2110 CloseHandle (token);
2113 static HCRYPTPROV w32_crypto_hprov;
2114 static int
2115 w32_init_crypt_random (void)
2117 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2118 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2120 DebPrint (("CryptAcquireContext failed with error %x\n",
2121 GetLastError ()));
2122 w32_crypto_hprov = 0;
2123 return -1;
2125 return 0;
2129 w32_init_random (void *buf, ptrdiff_t buflen)
2131 if (!w32_crypto_hprov)
2132 w32_init_crypt_random ();
2133 if (w32_crypto_hprov)
2135 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2136 return 0;
2138 return -1;
2142 random (void)
2144 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2145 return ((rand () << 15) | rand ());
2148 void
2149 srandom (int seed)
2151 srand (seed);
2154 /* Return the maximum length in bytes of a multibyte character
2155 sequence encoded in the current ANSI codepage. This is required to
2156 correctly walk the encoded file names one character at a time. */
2157 static int
2158 max_filename_mbslen (void)
2160 CPINFO cp_info;
2162 codepage_for_filenames (&cp_info);
2163 return cp_info.MaxCharSize;
2166 /* Normalize filename by converting in-place all of its path
2167 separators to the separator specified by PATH_SEP. */
2169 static void
2170 normalize_filename (register char *fp, char path_sep)
2172 char *p2;
2174 /* Always lower-case drive letters a-z, even if the filesystem
2175 preserves case in filenames.
2176 This is so filenames can be compared by string comparison
2177 functions that are case-sensitive. Even case-preserving filesystems
2178 do not distinguish case in drive letters. */
2179 p2 = fp + 1;
2181 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2183 *fp += 'a' - 'A';
2184 fp += 2;
2187 while (*fp)
2189 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2190 *fp = path_sep;
2191 fp++;
2195 /* Destructively turn backslashes into slashes. */
2196 void
2197 dostounix_filename (register char *p)
2199 normalize_filename (p, '/');
2202 /* Destructively turn slashes into backslashes. */
2203 void
2204 unixtodos_filename (register char *p)
2206 normalize_filename (p, '\\');
2209 /* Remove all CR's that are followed by a LF.
2210 (From msdos.c...probably should figure out a way to share it,
2211 although this code isn't going to ever change.) */
2212 static int
2213 crlf_to_lf (register int n, register char *buf)
2215 unsigned char *np = (unsigned char *)buf;
2216 unsigned char *startp = np;
2217 char *endp = buf + n;
2219 if (n == 0)
2220 return n;
2221 while (buf < endp - 1)
2223 if (*buf == 0x0d)
2225 if (*(++buf) != 0x0a)
2226 *np++ = 0x0d;
2228 else
2229 *np++ = *buf++;
2231 if (buf < endp)
2232 *np++ = *buf++;
2233 return np - startp;
2236 /* Parse the root part of file name, if present. Return length and
2237 optionally store pointer to char after root. */
2238 static int
2239 parse_root (const char * name, const char ** pPath)
2241 const char * start = name;
2243 if (name == NULL)
2244 return 0;
2246 /* find the root name of the volume if given */
2247 if (isalpha (name[0]) && name[1] == ':')
2249 /* skip past drive specifier */
2250 name += 2;
2251 if (IS_DIRECTORY_SEP (name[0]))
2252 name++;
2254 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2256 int slashes = 2;
2258 name += 2;
2261 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2262 break;
2263 name++;
2265 while ( *name );
2266 if (IS_DIRECTORY_SEP (name[0]))
2267 name++;
2270 if (pPath)
2271 *pPath = name;
2273 return name - start;
2276 /* Get long base name for name; name is assumed to be absolute. */
2277 static int
2278 get_long_basename (char * name, char * buf, int size)
2280 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2281 char fname_utf8[MAX_UTF8_PATH];
2282 int len = 0;
2283 int cstatus = -1;
2285 /* Must be valid filename, no wild cards or other invalid characters. */
2286 if (strpbrk (name, "*?|<>\""))
2287 return 0;
2289 if (w32_unicode_filenames)
2291 wchar_t fname_utf16[MAX_PATH];
2292 WIN32_FIND_DATAW find_data_wide;
2294 filename_to_utf16 (name, fname_utf16);
2295 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2296 if (dir_handle != INVALID_HANDLE_VALUE)
2297 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2299 else
2301 char fname_ansi[MAX_PATH];
2302 WIN32_FIND_DATAA find_data_ansi;
2304 filename_to_ansi (name, fname_ansi);
2305 /* If the ANSI name includes ? characters, it is not encodable
2306 in the ANSI codepage. In that case, we deliver the question
2307 marks to the caller; calling FindFirstFileA in this case
2308 could return some unrelated file name in the same
2309 directory. */
2310 if (_mbspbrk (fname_ansi, "?"))
2312 /* Find the basename of fname_ansi. */
2313 char *p = strrchr (fname_ansi, '\\');
2315 if (!p)
2316 p = fname_ansi;
2317 else
2318 p++;
2319 cstatus = filename_from_ansi (p, fname_utf8);
2321 else
2323 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2324 if (dir_handle != INVALID_HANDLE_VALUE)
2325 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2329 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2330 memcpy (buf, fname_utf8, len + 1);
2331 else
2332 len = 0;
2334 if (dir_handle != INVALID_HANDLE_VALUE)
2335 FindClose (dir_handle);
2337 return len;
2340 /* Get long name for file, if possible (assumed to be absolute). */
2341 BOOL
2342 w32_get_long_filename (const char * name, char * buf, int size)
2344 char * o = buf;
2345 char * p;
2346 const char * q;
2347 char full[ MAX_UTF8_PATH ];
2348 int len;
2350 len = strlen (name);
2351 if (len >= MAX_UTF8_PATH)
2352 return FALSE;
2354 /* Use local copy for destructive modification. */
2355 memcpy (full, name, len+1);
2356 unixtodos_filename (full);
2358 /* Copy root part verbatim. */
2359 len = parse_root (full, (const char **)&p);
2360 memcpy (o, full, len);
2361 o += len;
2362 *o = '\0';
2363 size -= len;
2365 while (p != NULL && *p)
2367 q = p;
2368 p = strchr (q, '\\');
2369 if (p) *p = '\0';
2370 len = get_long_basename (full, o, size);
2371 if (len > 0)
2373 o += len;
2374 size -= len;
2375 if (p != NULL)
2377 *p++ = '\\';
2378 if (size < 2)
2379 return FALSE;
2380 *o++ = '\\';
2381 size--;
2382 *o = '\0';
2385 else
2386 return FALSE;
2389 return TRUE;
2392 unsigned int
2393 w32_get_short_filename (const char * name, char * buf, int size)
2395 if (w32_unicode_filenames)
2397 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2398 unsigned int retval;
2400 filename_to_utf16 (name, name_utf16);
2401 retval = GetShortPathNameW (name_utf16, short_name, size);
2402 if (retval && retval < size)
2403 filename_from_utf16 (short_name, buf);
2404 return retval;
2406 else
2408 char name_ansi[MAX_PATH];
2410 filename_to_ansi (name, name_ansi);
2411 return GetShortPathNameA (name_ansi, buf, size);
2415 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2416 MS-Windows ANSI codepage. If FILENAME includes characters not
2417 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2418 if it exists. This is needed because the w32 build wants to
2419 support file names outside of the system locale, but image
2420 libraries typically don't support wide (a.k.a. "Unicode") APIs
2421 required for that. */
2423 Lisp_Object
2424 ansi_encode_filename (Lisp_Object filename)
2426 Lisp_Object encoded_filename;
2427 char fname[MAX_PATH];
2429 filename_to_ansi (SSDATA (filename), fname);
2430 if (_mbspbrk (fname, "?"))
2432 char shortname[MAX_PATH];
2434 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2436 dostounix_filename (shortname);
2437 encoded_filename = build_string (shortname);
2439 else
2440 encoded_filename = build_unibyte_string (fname);
2442 else
2443 encoded_filename = build_unibyte_string (fname);
2444 return encoded_filename;
2447 static int
2448 is_unc_volume (const char *filename)
2450 const char *ptr = filename;
2452 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2453 return 0;
2455 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2456 return 0;
2458 return 1;
2461 /* Emulate the Posix unsetenv. */
2463 unsetenv (const char *name)
2465 char *var;
2466 size_t name_len;
2468 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2470 errno = EINVAL;
2471 return -1;
2473 name_len = strlen (name);
2474 /* MS docs says an environment variable cannot be longer than 32K. */
2475 if (name_len > 32767)
2477 errno = ENOMEM;
2478 return 0;
2480 /* It is safe to use 'alloca' with 32K size, since the stack is at
2481 least 2MB, and we set it to 8MB in the link command line. */
2482 var = alloca (name_len + 2);
2483 strncpy (var, name, name_len);
2484 var[name_len++] = '=';
2485 var[name_len] = '\0';
2486 return _putenv (var);
2489 /* MS _putenv doesn't support removing a variable when the argument
2490 does not include the '=' character, so we fix that here. */
2492 sys_putenv (char *str)
2494 const char *const name_end = strchr (str, '=');
2496 if (name_end == NULL)
2498 /* Remove the variable from the environment. */
2499 return unsetenv (str);
2502 return _putenv (str);
2505 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2507 LPBYTE
2508 w32_get_resource (char *key, LPDWORD lpdwtype)
2510 LPBYTE lpvalue;
2511 HKEY hrootkey = NULL;
2512 DWORD cbData;
2514 /* Check both the current user and the local machine to see if
2515 we have any resources. */
2517 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2519 lpvalue = NULL;
2521 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2522 && (lpvalue = xmalloc (cbData)) != NULL
2523 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2525 RegCloseKey (hrootkey);
2526 return (lpvalue);
2529 xfree (lpvalue);
2531 RegCloseKey (hrootkey);
2534 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2536 lpvalue = NULL;
2538 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2539 && (lpvalue = xmalloc (cbData)) != NULL
2540 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2542 RegCloseKey (hrootkey);
2543 return (lpvalue);
2546 xfree (lpvalue);
2548 RegCloseKey (hrootkey);
2551 return (NULL);
2554 /* The argv[] array holds ANSI-encoded strings, and so this function
2555 works with ANS_encoded strings. */
2556 void
2557 init_environment (char ** argv)
2559 static const char * const tempdirs[] = {
2560 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2563 int i;
2565 const int imax = ARRAYELTS (tempdirs);
2567 /* Implementation note: This function explicitly works with ANSI
2568 file names, not with UTF-8 encoded file names. This is because
2569 this function pushes variables into the Emacs's environment, and
2570 the environment variables are always assumed to be in the
2571 locale-specific encoding. Do NOT call any functions that accept
2572 UTF-8 file names from this function! */
2574 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2575 temporary files and assume "/tmp" if $TMPDIR is unset, which
2576 will break on DOS/Windows. Refuse to work if we cannot find
2577 a directory, not even "c:/", usable for that purpose. */
2578 for (i = 0; i < imax ; i++)
2580 const char *tmp = tempdirs[i];
2582 if (*tmp == '$')
2583 tmp = getenv (tmp + 1);
2584 /* Note that `access' can lie to us if the directory resides on a
2585 read-only filesystem, like CD-ROM or a write-protected floppy.
2586 The only way to be really sure is to actually create a file and
2587 see if it succeeds. But I think that's too much to ask. */
2589 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2590 if (tmp && sys_access (tmp, D_OK) == 0)
2592 char * var = alloca (strlen (tmp) + 8);
2593 sprintf (var, "TMPDIR=%s", tmp);
2594 _putenv (strdup (var));
2595 break;
2598 if (i >= imax)
2599 cmd_error_internal
2600 (Fcons (Qerror,
2601 Fcons (build_string ("no usable temporary directories found!!"),
2602 Qnil)),
2603 "While setting TMPDIR: ");
2605 /* Check for environment variables and use registry settings if they
2606 don't exist. Fallback on default values where applicable. */
2608 int i;
2609 LPBYTE lpval;
2610 DWORD dwType;
2611 char locale_name[32];
2612 char default_home[MAX_PATH];
2613 int appdata = 0;
2615 static const struct env_entry
2617 char * name;
2618 char * def_value;
2619 } dflt_envvars[] =
2621 /* If the default value is NULL, we will use the value from the
2622 outside environment or the Registry, but will not push the
2623 variable into the Emacs environment if it is defined neither
2624 in the Registry nor in the outside environment. */
2625 {"HOME", "C:/"},
2626 {"PRELOAD_WINSOCK", NULL},
2627 {"emacs_dir", "C:/emacs"},
2628 {"EMACSLOADPATH", NULL},
2629 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2630 {"EMACSDATA", NULL},
2631 {"EMACSPATH", NULL},
2632 {"INFOPATH", NULL},
2633 {"EMACSDOC", NULL},
2634 {"TERM", "cmd"},
2635 {"LANG", NULL},
2638 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2640 /* We need to copy dflt_envvars[] and work on the copy because we
2641 don't want the dumped Emacs to inherit the values of
2642 environment variables we saw during dumping (which could be on
2643 a different system). The defaults above must be left intact. */
2644 struct env_entry env_vars[N_ENV_VARS];
2646 for (i = 0; i < N_ENV_VARS; i++)
2647 env_vars[i] = dflt_envvars[i];
2649 /* For backwards compatibility, check if a .emacs file exists in C:/
2650 If not, then we can try to default to the appdata directory under the
2651 user's profile, which is more likely to be writable. */
2652 if (sys_access ("C:/.emacs", F_OK) != 0)
2654 HRESULT profile_result;
2655 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2656 of Windows 95 and NT4 that have not been updated to include
2657 MSIE 5. */
2658 ShGetFolderPath_fn get_folder_path;
2659 get_folder_path = (ShGetFolderPath_fn)
2660 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2662 if (get_folder_path != NULL)
2664 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2665 0, default_home);
2667 /* If we can't get the appdata dir, revert to old behavior. */
2668 if (profile_result == S_OK)
2670 env_vars[0].def_value = default_home;
2671 appdata = 1;
2676 /* Get default locale info and use it for LANG. */
2677 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2678 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2679 locale_name, sizeof (locale_name)))
2681 for (i = 0; i < N_ENV_VARS; i++)
2683 if (strcmp (env_vars[i].name, "LANG") == 0)
2685 env_vars[i].def_value = locale_name;
2686 break;
2691 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2693 /* Treat emacs_dir specially: set it unconditionally based on our
2694 location. */
2696 char *p;
2697 char modname[MAX_PATH];
2699 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2700 emacs_abort ();
2701 if ((p = _mbsrchr (modname, '\\')) == NULL)
2702 emacs_abort ();
2703 *p = 0;
2705 if ((p = _mbsrchr (modname, '\\'))
2706 /* From bin means installed Emacs, from src means uninstalled. */
2707 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2709 char buf[SET_ENV_BUF_SIZE];
2710 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2712 *p = 0;
2713 for (p = modname; *p; p = CharNext (p))
2714 if (*p == '\\') *p = '/';
2716 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2717 _putenv (strdup (buf));
2718 /* If we are running from the Posix-like build tree, define
2719 SHELL to point to our own cmdproxy. The loop below will
2720 then disregard PATH_EXEC and the default value. */
2721 if (within_build_tree)
2723 _snprintf (buf, sizeof (buf) - 1,
2724 "SHELL=%s/nt/cmdproxy.exe", modname);
2725 _putenv (strdup (buf));
2730 for (i = 0; i < N_ENV_VARS; i++)
2732 if (!getenv (env_vars[i].name))
2734 int dont_free = 0;
2735 char bufc[SET_ENV_BUF_SIZE];
2737 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2738 /* Also ignore empty environment variables. */
2739 || *lpval == 0)
2741 xfree (lpval);
2742 dont_free = 1;
2743 if (strcmp (env_vars[i].name, "SHELL") == 0)
2745 /* Look for cmdproxy.exe in every directory in
2746 PATH_EXEC. FIXME: This does not find cmdproxy
2747 in nt/ when we run uninstalled. */
2748 char fname[MAX_PATH];
2749 const char *pstart = PATH_EXEC, *pend;
2751 do {
2752 pend = _mbschr (pstart, ';');
2753 if (!pend)
2754 pend = pstart + strlen (pstart);
2755 /* Be defensive against series of ;;; characters. */
2756 if (pend > pstart)
2758 strncpy (fname, pstart, pend - pstart);
2759 fname[pend - pstart] = '/';
2760 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2761 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2762 sizeof (bufc));
2763 if (sys_access (bufc, F_OK) == 0)
2765 lpval = bufc;
2766 dwType = REG_SZ;
2767 break;
2770 if (*pend)
2771 pstart = pend + 1;
2772 else
2773 pstart = pend;
2774 if (!*pstart)
2776 /* If not found in any directory, use the
2777 default as the last resort. */
2778 lpval = env_vars[i].def_value;
2779 dwType = REG_EXPAND_SZ;
2781 } while (*pstart);
2783 else
2785 lpval = env_vars[i].def_value;
2786 dwType = REG_EXPAND_SZ;
2788 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2789 Vdelayed_warnings_list
2790 = Fcons
2791 (listn (CONSTYPE_HEAP, 2,
2792 intern ("initialization"), build_string
2793 ("Use of `C:\\.emacs' without defining `HOME'\n"
2794 "in the environment is deprecated, "
2795 "see `Windows HOME' in the Emacs manual.")),
2796 Vdelayed_warnings_list);
2799 if (lpval)
2801 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2803 if (dwType == REG_EXPAND_SZ)
2804 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2805 else if (dwType == REG_SZ)
2806 strcpy (buf1, lpval);
2807 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2809 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2810 buf1);
2811 _putenv (strdup (buf2));
2814 if (!dont_free)
2815 xfree (lpval);
2821 /* Rebuild system configuration to reflect invoking system. */
2822 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2824 /* Another special case: on NT, the PATH variable is actually named
2825 "Path" although cmd.exe (perhaps NT itself) arranges for
2826 environment variable lookup and setting to be case insensitive.
2827 However, Emacs assumes a fully case sensitive environment, so we
2828 need to change "Path" to "PATH" to match the expectations of
2829 various elisp packages. We do this by the sneaky method of
2830 modifying the string in the C runtime environ entry.
2832 The same applies to COMSPEC. */
2834 char ** envp;
2836 for (envp = environ; *envp; envp++)
2837 if (_strnicmp (*envp, "PATH=", 5) == 0)
2838 memcpy (*envp, "PATH=", 5);
2839 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2840 memcpy (*envp, "COMSPEC=", 8);
2843 /* Remember the initial working directory for getcwd. */
2844 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2845 Does it matter anywhere in Emacs? */
2846 if (w32_unicode_filenames)
2848 wchar_t wstartup_dir[MAX_PATH];
2850 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2851 emacs_abort ();
2852 filename_from_utf16 (wstartup_dir, startup_dir);
2854 else
2856 char astartup_dir[MAX_PATH];
2858 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2859 emacs_abort ();
2860 filename_from_ansi (astartup_dir, startup_dir);
2864 static char modname[MAX_PATH];
2866 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2867 emacs_abort ();
2868 argv[0] = modname;
2871 /* Determine if there is a middle mouse button, to allow parse_button
2872 to decide whether right mouse events should be mouse-2 or
2873 mouse-3. */
2874 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2876 init_user_info ();
2879 /* Called from expand-file-name when default-directory is not a string. */
2881 char *
2882 emacs_root_dir (void)
2884 static char root_dir[MAX_UTF8_PATH];
2885 const char *p;
2887 p = getenv ("emacs_dir");
2888 if (p == NULL)
2889 emacs_abort ();
2890 filename_from_ansi (p, root_dir);
2891 root_dir[parse_root (root_dir, NULL)] = '\0';
2892 dostounix_filename (root_dir);
2893 return root_dir;
2896 #include <sys/timeb.h>
2898 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2900 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2902 struct _timeb tb;
2903 _ftime (&tb);
2905 tv->tv_sec = tb.time;
2906 tv->tv_usec = tb.millitm * 1000L;
2907 /* Implementation note: _ftime sometimes doesn't update the dstflag
2908 according to the new timezone when the system timezone is
2909 changed. We could fix that by using GetSystemTime and
2910 GetTimeZoneInformation, but that doesn't seem necessary, since
2911 Emacs always calls gettimeofday with the 2nd argument NULL (see
2912 current_emacs_time). */
2913 if (tz)
2915 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2916 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2918 return 0;
2921 /* Emulate fdutimens. */
2923 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2924 TIMESPEC[0] and TIMESPEC[1], respectively.
2925 FD must be either negative -- in which case it is ignored --
2926 or a file descriptor that is open on FILE.
2927 If FD is nonnegative, then FILE can be NULL, which means
2928 use just futimes instead of utimes.
2929 If TIMESPEC is null, FAIL.
2930 Return 0 on success, -1 (setting errno) on failure. */
2933 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2935 if (!timespec)
2937 errno = ENOSYS;
2938 return -1;
2940 if (fd < 0 && !file)
2942 errno = EBADF;
2943 return -1;
2945 /* _futime's prototype defines 2nd arg as having the type 'struct
2946 _utimbuf', while utime needs to accept 'struct utimbuf' for
2947 compatibility with Posix. So we need to use 2 different (but
2948 equivalent) types to avoid compiler warnings, sigh. */
2949 if (fd >= 0)
2951 struct _utimbuf _ut;
2953 _ut.actime = timespec[0].tv_sec;
2954 _ut.modtime = timespec[1].tv_sec;
2955 return _futime (fd, &_ut);
2957 else
2959 struct utimbuf ut;
2961 ut.actime = timespec[0].tv_sec;
2962 ut.modtime = timespec[1].tv_sec;
2963 /* Call 'utime', which is implemented below, not the MS library
2964 function, which fails on directories. */
2965 return utime (file, &ut);
2970 /* ------------------------------------------------------------------------- */
2971 /* IO support and wrapper functions for the Windows API. */
2972 /* ------------------------------------------------------------------------- */
2974 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2975 on network directories, so we handle that case here.
2976 (Ulrich Leodolter, 1/11/95). */
2977 char *
2978 sys_ctime (const time_t *t)
2980 char *str = (char *) ctime (t);
2981 return (str ? str : "Sun Jan 01 00:00:00 1970");
2984 /* Emulate sleep...we could have done this with a define, but that
2985 would necessitate including windows.h in the files that used it.
2986 This is much easier. */
2987 void
2988 sys_sleep (int seconds)
2990 Sleep (seconds * 1000);
2993 /* Internal MSVC functions for low-level descriptor munging */
2994 extern int __cdecl _set_osfhnd (int fd, long h);
2995 extern int __cdecl _free_osfhnd (int fd);
2997 /* parallel array of private info on file handles */
2998 filedesc fd_info [ MAXDESC ];
3000 typedef struct volume_info_data {
3001 struct volume_info_data * next;
3003 /* time when info was obtained */
3004 DWORD timestamp;
3006 /* actual volume info */
3007 char * root_dir;
3008 DWORD serialnum;
3009 DWORD maxcomp;
3010 DWORD flags;
3011 char * name;
3012 char * type;
3013 } volume_info_data;
3015 /* Global referenced by various functions. */
3016 static volume_info_data volume_info;
3018 /* Vector to indicate which drives are local and fixed (for which cached
3019 data never expires). */
3020 static BOOL fixed_drives[26];
3022 /* Consider cached volume information to be stale if older than 10s,
3023 at least for non-local drives. Info for fixed drives is never stale. */
3024 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3025 #define VOLINFO_STILL_VALID( root_dir, info ) \
3026 ( ( isalpha (root_dir[0]) && \
3027 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3028 || GetTickCount () - info->timestamp < 10000 )
3030 /* Cache support functions. */
3032 /* Simple linked list with linear search is sufficient. */
3033 static volume_info_data *volume_cache = NULL;
3035 static volume_info_data *
3036 lookup_volume_info (char * root_dir)
3038 volume_info_data * info;
3040 for (info = volume_cache; info; info = info->next)
3041 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3042 break;
3043 return info;
3046 static void
3047 add_volume_info (char * root_dir, volume_info_data * info)
3049 info->root_dir = xstrdup (root_dir);
3050 unixtodos_filename (info->root_dir);
3051 info->next = volume_cache;
3052 volume_cache = info;
3056 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3057 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3058 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3059 static volume_info_data *
3060 GetCachedVolumeInformation (char * root_dir)
3062 volume_info_data * info;
3063 char default_root[ MAX_UTF8_PATH ];
3064 char name[MAX_PATH+1];
3065 char type[MAX_PATH+1];
3067 /* NULL for root_dir means use root from current directory. */
3068 if (root_dir == NULL)
3070 if (w32_unicode_filenames)
3072 wchar_t curdirw[MAX_PATH];
3074 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3075 return NULL;
3076 filename_from_utf16 (curdirw, default_root);
3078 else
3080 char curdira[MAX_PATH];
3082 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3083 return NULL;
3084 filename_from_ansi (curdira, default_root);
3086 parse_root (default_root, (const char **)&root_dir);
3087 *root_dir = 0;
3088 root_dir = default_root;
3091 /* Local fixed drives can be cached permanently. Removable drives
3092 cannot be cached permanently, since the volume name and serial
3093 number (if nothing else) can change. Remote drives should be
3094 treated as if they are removable, since there is no sure way to
3095 tell whether they are or not. Also, the UNC association of drive
3096 letters mapped to remote volumes can be changed at any time (even
3097 by other processes) without notice.
3099 As a compromise, so we can benefit from caching info for remote
3100 volumes, we use a simple expiry mechanism to invalidate cache
3101 entries that are more than ten seconds old. */
3103 #if 0
3104 /* No point doing this, because WNetGetConnection is even slower than
3105 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3106 GetDriveType is about the only call of this type which does not
3107 involve network access, and so is extremely quick). */
3109 /* Map drive letter to UNC if remote. */
3110 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3112 char remote_name[ 256 ];
3113 char drive[3] = { root_dir[0], ':' };
3115 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3116 == NO_ERROR)
3117 /* do something */ ;
3119 #endif
3121 info = lookup_volume_info (root_dir);
3123 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3125 DWORD serialnum;
3126 DWORD maxcomp;
3127 DWORD flags;
3129 /* Info is not cached, or is stale. */
3130 if (w32_unicode_filenames)
3132 wchar_t root_w[MAX_PATH];
3133 wchar_t name_w[MAX_PATH+1];
3134 wchar_t type_w[MAX_PATH+1];
3136 filename_to_utf16 (root_dir, root_w);
3137 if (!GetVolumeInformationW (root_w,
3138 name_w, sizeof (name_w),
3139 &serialnum,
3140 &maxcomp,
3141 &flags,
3142 type_w, sizeof (type_w)))
3143 return NULL;
3144 /* Hmm... not really 100% correct, as these 2 are not file
3145 names... */
3146 filename_from_utf16 (name_w, name);
3147 filename_from_utf16 (type_w, type);
3149 else
3151 char root_a[MAX_PATH];
3152 char name_a[MAX_PATH+1];
3153 char type_a[MAX_PATH+1];
3155 filename_to_ansi (root_dir, root_a);
3156 if (!GetVolumeInformationA (root_a,
3157 name_a, sizeof (name_a),
3158 &serialnum,
3159 &maxcomp,
3160 &flags,
3161 type_a, sizeof (type_a)))
3162 return NULL;
3163 filename_from_ansi (name_a, name);
3164 filename_from_ansi (type_a, type);
3167 /* Cache the volume information for future use, overwriting existing
3168 entry if present. */
3169 if (info == NULL)
3171 info = xmalloc (sizeof (volume_info_data));
3172 add_volume_info (root_dir, info);
3174 else
3176 xfree (info->name);
3177 xfree (info->type);
3180 info->name = xstrdup (name);
3181 unixtodos_filename (info->name);
3182 info->serialnum = serialnum;
3183 info->maxcomp = maxcomp;
3184 info->flags = flags;
3185 info->type = xstrdup (type);
3186 info->timestamp = GetTickCount ();
3189 return info;
3192 /* Get information on the volume where NAME is held; set path pointer to
3193 start of pathname in NAME (past UNC header\volume header if present),
3194 if pPath is non-NULL.
3196 Note: if NAME includes symlinks, the information is for the volume
3197 of the symlink, not of its target. That's because, even though
3198 GetVolumeInformation returns information about the symlink target
3199 of its argument, we only pass the root directory to
3200 GetVolumeInformation, not the full NAME. */
3201 static int
3202 get_volume_info (const char * name, const char ** pPath)
3204 char temp[MAX_UTF8_PATH];
3205 char *rootname = NULL; /* default to current volume */
3206 volume_info_data * info;
3207 int root_len = parse_root (name, pPath);
3209 if (name == NULL)
3210 return FALSE;
3212 /* Copy the root name of the volume, if given. */
3213 if (root_len)
3215 strncpy (temp, name, root_len);
3216 temp[root_len] = '\0';
3217 unixtodos_filename (temp);
3218 rootname = temp;
3221 info = GetCachedVolumeInformation (rootname);
3222 if (info != NULL)
3224 /* Set global referenced by other functions. */
3225 volume_info = *info;
3226 return TRUE;
3228 return FALSE;
3231 /* Determine if volume is FAT format (ie. only supports short 8.3
3232 names); also set path pointer to start of pathname in name, if
3233 pPath is non-NULL. */
3234 static int
3235 is_fat_volume (const char * name, const char ** pPath)
3237 if (get_volume_info (name, pPath))
3238 return (volume_info.maxcomp == 12);
3239 return FALSE;
3242 /* Convert all slashes in a filename to backslashes, and map filename
3243 to a valid 8.3 name if necessary. The result is a pointer to a
3244 static buffer, so CAVEAT EMPTOR! */
3245 const char *
3246 map_w32_filename (const char * name, const char ** pPath)
3248 static char shortname[MAX_UTF8_PATH];
3249 char * str = shortname;
3250 char c;
3251 char * path;
3252 const char * save_name = name;
3254 if (strlen (name) >= sizeof (shortname))
3256 /* Return a filename which will cause callers to fail. */
3257 strcpy (shortname, "?");
3258 return shortname;
3261 if (!fatal_error_in_progress /* disable fancy processing during crash */
3262 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3264 register int left = 8; /* maximum number of chars in part */
3265 register int extn = 0; /* extension added? */
3266 register int dots = 2; /* maximum number of dots allowed */
3268 while (name < path)
3269 *str++ = *name++; /* skip past UNC header */
3271 while ((c = *name++))
3273 switch ( c )
3275 case ':':
3276 case '\\':
3277 case '/':
3278 *str++ = (c == ':' ? ':' : '\\');
3279 extn = 0; /* reset extension flags */
3280 dots = 2; /* max 2 dots */
3281 left = 8; /* max length 8 for main part */
3282 break;
3283 case '.':
3284 if ( dots )
3286 /* Convert path components of the form .xxx to _xxx,
3287 but leave . and .. as they are. This allows .emacs
3288 to be read as _emacs, for example. */
3290 if (! *name ||
3291 *name == '.' ||
3292 IS_DIRECTORY_SEP (*name))
3294 *str++ = '.';
3295 dots--;
3297 else
3299 *str++ = '_';
3300 left--;
3301 dots = 0;
3304 else if ( !extn )
3306 *str++ = '.';
3307 extn = 1; /* we've got an extension */
3308 left = 3; /* 3 chars in extension */
3310 else
3312 /* any embedded dots after the first are converted to _ */
3313 *str++ = '_';
3315 break;
3316 case '~':
3317 case '#': /* don't lose these, they're important */
3318 if ( ! left )
3319 str[-1] = c; /* replace last character of part */
3320 /* FALLTHRU */
3321 default:
3322 if ( left && 'A' <= c && c <= 'Z' )
3324 *str++ = tolower (c); /* map to lower case (looks nicer) */
3325 left--;
3326 dots = 0; /* started a path component */
3328 break;
3331 *str = '\0';
3333 else
3335 strcpy (shortname, name);
3336 unixtodos_filename (shortname);
3339 if (pPath)
3340 *pPath = shortname + (path - save_name);
3342 return shortname;
3345 static int
3346 is_exec (const char * name)
3348 char * p = strrchr (name, '.');
3349 return
3350 (p != NULL
3351 && (xstrcasecmp (p, ".exe") == 0 ||
3352 xstrcasecmp (p, ".com") == 0 ||
3353 xstrcasecmp (p, ".bat") == 0 ||
3354 xstrcasecmp (p, ".cmd") == 0));
3357 /* Emulate the Unix directory procedures opendir, closedir, and
3358 readdir. We rename them to sys_* names because some versions of
3359 MinGW startup code call opendir and readdir to glob wildcards, and
3360 the code that calls them doesn't grok UTF-8 encoded file names we
3361 produce in dirent->d_name[]. */
3363 struct dirent dir_static; /* simulated directory contents */
3364 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3365 static int dir_is_fat;
3366 static char dir_pathname[MAX_UTF8_PATH];
3367 static WIN32_FIND_DATAW dir_find_data_w;
3368 static WIN32_FIND_DATAA dir_find_data_a;
3369 #define DIR_FIND_DATA_W 1
3370 #define DIR_FIND_DATA_A 2
3371 static int last_dir_find_data = -1;
3373 /* Support shares on a network resource as subdirectories of a read-only
3374 root directory. */
3375 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3376 static HANDLE open_unc_volume (const char *);
3377 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3378 static void close_unc_volume (HANDLE);
3380 DIR *
3381 sys_opendir (const char *filename)
3383 DIR *dirp;
3385 /* Opening is done by FindFirstFile. However, a read is inherent to
3386 this operation, so we defer the open until read time. */
3388 if (dir_find_handle != INVALID_HANDLE_VALUE)
3389 return NULL;
3390 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3391 return NULL;
3393 /* Note: We don't support traversal of UNC volumes via symlinks.
3394 Doing so would mean punishing 99.99% of use cases by resolving
3395 all the possible symlinks in FILENAME, recursively. */
3396 if (is_unc_volume (filename))
3398 wnet_enum_handle = open_unc_volume (filename);
3399 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3400 return NULL;
3403 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3404 return NULL;
3406 dirp->dd_fd = 0;
3407 dirp->dd_loc = 0;
3408 dirp->dd_size = 0;
3410 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3411 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3412 /* Note: We don't support symlinks to file names on FAT volumes.
3413 Doing so would mean punishing 99.99% of use cases by resolving
3414 all the possible symlinks in FILENAME, recursively. */
3415 dir_is_fat = is_fat_volume (filename, NULL);
3417 return dirp;
3420 void
3421 sys_closedir (DIR *dirp)
3423 /* If we have a find-handle open, close it. */
3424 if (dir_find_handle != INVALID_HANDLE_VALUE)
3426 FindClose (dir_find_handle);
3427 dir_find_handle = INVALID_HANDLE_VALUE;
3429 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3431 close_unc_volume (wnet_enum_handle);
3432 wnet_enum_handle = INVALID_HANDLE_VALUE;
3434 xfree ((char *) dirp);
3437 struct dirent *
3438 sys_readdir (DIR *dirp)
3440 int downcase = !NILP (Vw32_downcase_file_names);
3442 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3444 if (!read_unc_volume (wnet_enum_handle,
3445 dir_find_data_w.cFileName,
3446 dir_find_data_a.cFileName,
3447 MAX_PATH))
3448 return NULL;
3450 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3451 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3453 char filename[MAX_UTF8_PATH];
3454 int ln;
3455 bool last_slash = true;
3457 /* Note: We don't need to worry about dir_pathname being longer
3458 than MAX_UTF8_PATH, as sys_opendir already took care of that
3459 when it called map_w32_filename: that function will put a "?"
3460 in its return value in that case, thus failing all the calls
3461 below. */
3462 strcpy (filename, dir_pathname);
3463 ln = strlen (filename);
3464 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3465 last_slash = false;
3467 /* Note: No need to resolve symlinks in FILENAME, because
3468 FindFirst opens the directory that is the target of a
3469 symlink. */
3470 if (w32_unicode_filenames)
3472 wchar_t fnw[MAX_PATH + 2];
3474 filename_to_utf16 (filename, fnw);
3475 if (!last_slash)
3476 wcscat (fnw, L"\\");
3477 wcscat (fnw, L"*");
3478 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3480 else
3482 char fna[MAX_PATH + 2];
3484 filename_to_ansi (filename, fna);
3485 if (!last_slash)
3486 strcat (fna, "\\");
3487 strcat (fna, "*");
3488 /* If FILENAME is not representable by the current ANSI
3489 codepage, we don't want FindFirstFileA to interpret the
3490 '?' characters as a wildcard. */
3491 if (_mbspbrk (fna, "?"))
3492 dir_find_handle = INVALID_HANDLE_VALUE;
3493 else
3494 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3497 if (dir_find_handle == INVALID_HANDLE_VALUE)
3499 /* Any changes in the value of errno here should be in sync
3500 with what directory_files_internal does when it calls
3501 readdir. */
3502 switch (GetLastError ())
3504 /* Windows uses this value when FindFirstFile finds no
3505 files that match the wildcard. This is not supposed
3506 to happen, since our wildcard is "*", but just in
3507 case, if there's some weird empty directory with not
3508 even "." and ".." entries... */
3509 case ERROR_FILE_NOT_FOUND:
3510 errno = 0;
3511 /* FALLTHRU */
3512 default:
3513 break;
3514 case ERROR_ACCESS_DENIED:
3515 case ERROR_NETWORK_ACCESS_DENIED:
3516 errno = EACCES;
3517 break;
3518 case ERROR_PATH_NOT_FOUND:
3519 case ERROR_INVALID_DRIVE:
3520 case ERROR_NOT_READY:
3521 case ERROR_BAD_NETPATH:
3522 case ERROR_BAD_NET_NAME:
3523 errno = ENOENT;
3524 break;
3526 return NULL;
3529 else if (w32_unicode_filenames)
3531 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3533 errno = 0;
3534 return NULL;
3537 else
3539 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3541 errno = 0;
3542 return NULL;
3546 /* Emacs never uses this value, so don't bother making it match
3547 value returned by stat(). */
3548 dir_static.d_ino = 1;
3550 if (w32_unicode_filenames)
3552 if (downcase || dir_is_fat)
3554 wchar_t tem[MAX_PATH];
3556 wcscpy (tem, dir_find_data_w.cFileName);
3557 CharLowerW (tem);
3558 filename_from_utf16 (tem, dir_static.d_name);
3560 else
3561 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3562 last_dir_find_data = DIR_FIND_DATA_W;
3564 else
3566 char tem[MAX_PATH];
3568 /* If the file name in cFileName[] includes `?' characters, it
3569 means the original file name used characters that cannot be
3570 represented by the current ANSI codepage. To avoid total
3571 lossage, retrieve the short 8+3 alias of the long file
3572 name. */
3573 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3575 strcpy (tem, dir_find_data_a.cAlternateFileName);
3576 /* 8+3 aliases are returned in all caps, which could break
3577 various alists that look at filenames' extensions. */
3578 downcase = 1;
3580 else if (downcase || dir_is_fat)
3581 strcpy (tem, dir_find_data_a.cFileName);
3582 else
3583 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3584 if (downcase || dir_is_fat)
3586 _mbslwr (tem);
3587 filename_from_ansi (tem, dir_static.d_name);
3589 last_dir_find_data = DIR_FIND_DATA_A;
3592 dir_static.d_namlen = strlen (dir_static.d_name);
3593 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3594 dir_static.d_namlen - dir_static.d_namlen % 4;
3596 return &dir_static;
3599 static HANDLE
3600 open_unc_volume (const char *path)
3602 const char *fn = map_w32_filename (path, NULL);
3603 DWORD result;
3604 HANDLE henum;
3606 if (w32_unicode_filenames)
3608 NETRESOURCEW nrw;
3609 wchar_t fnw[MAX_PATH];
3611 nrw.dwScope = RESOURCE_GLOBALNET;
3612 nrw.dwType = RESOURCETYPE_DISK;
3613 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3614 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3615 nrw.lpLocalName = NULL;
3616 filename_to_utf16 (fn, fnw);
3617 nrw.lpRemoteName = fnw;
3618 nrw.lpComment = NULL;
3619 nrw.lpProvider = NULL;
3621 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3622 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3624 else
3626 NETRESOURCEA nra;
3627 char fna[MAX_PATH];
3629 nra.dwScope = RESOURCE_GLOBALNET;
3630 nra.dwType = RESOURCETYPE_DISK;
3631 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3632 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3633 nra.lpLocalName = NULL;
3634 filename_to_ansi (fn, fna);
3635 nra.lpRemoteName = fna;
3636 nra.lpComment = NULL;
3637 nra.lpProvider = NULL;
3639 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3640 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3642 if (result == NO_ERROR)
3643 return henum;
3644 else
3646 /* Make sure directory_files_internal reports a sensible error. */
3647 errno = ENOENT;
3648 return INVALID_HANDLE_VALUE;
3652 static void *
3653 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3655 DWORD count;
3656 int result;
3657 char *buffer;
3658 DWORD bufsize = 512;
3659 void *retval;
3661 count = 1;
3662 if (w32_unicode_filenames)
3664 wchar_t *ptrw;
3666 bufsize *= 2;
3667 buffer = alloca (bufsize);
3668 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3669 if (result != NO_ERROR)
3670 return NULL;
3671 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3672 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3673 ptrw += 2;
3674 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3675 ptrw++;
3676 wcsncpy (fname_w, ptrw, size);
3677 retval = fname_w;
3679 else
3681 int dbcs_p = max_filename_mbslen () > 1;
3682 char *ptra;
3684 buffer = alloca (bufsize);
3685 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3686 if (result != NO_ERROR)
3687 return NULL;
3688 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3689 ptra += 2;
3690 if (!dbcs_p)
3691 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3692 else
3694 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3695 ptra = CharNextExA (file_name_codepage, ptra, 0);
3697 ptra++;
3698 strncpy (fname_a, ptra, size);
3699 retval = fname_a;
3702 return retval;
3705 static void
3706 close_unc_volume (HANDLE henum)
3708 if (henum != INVALID_HANDLE_VALUE)
3709 WNetCloseEnum (henum);
3712 static DWORD
3713 unc_volume_file_attributes (const char *path)
3715 HANDLE henum;
3716 DWORD attrs;
3718 henum = open_unc_volume (path);
3719 if (henum == INVALID_HANDLE_VALUE)
3720 return -1;
3722 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3724 close_unc_volume (henum);
3726 return attrs;
3729 /* Ensure a network connection is authenticated. */
3730 static void
3731 logon_network_drive (const char *path)
3733 char share[MAX_UTF8_PATH];
3734 int n_slashes;
3735 char drive[4];
3736 UINT drvtype;
3737 char *p;
3738 DWORD val;
3740 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3741 drvtype = DRIVE_REMOTE;
3742 else if (path[0] == '\0' || path[1] != ':')
3743 drvtype = GetDriveType (NULL);
3744 else
3746 drive[0] = path[0];
3747 drive[1] = ':';
3748 drive[2] = '\\';
3749 drive[3] = '\0';
3750 drvtype = GetDriveType (drive);
3753 /* Only logon to networked drives. */
3754 if (drvtype != DRIVE_REMOTE)
3755 return;
3757 n_slashes = 2;
3758 strncpy (share, path, MAX_UTF8_PATH);
3759 /* Truncate to just server and share name. */
3760 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3762 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3764 *p = '\0';
3765 break;
3769 if (w32_unicode_filenames)
3771 NETRESOURCEW resourcew;
3772 wchar_t share_w[MAX_PATH];
3774 resourcew.dwScope = RESOURCE_GLOBALNET;
3775 resourcew.dwType = RESOURCETYPE_DISK;
3776 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3777 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3778 resourcew.lpLocalName = NULL;
3779 filename_to_utf16 (share, share_w);
3780 resourcew.lpRemoteName = share_w;
3781 resourcew.lpProvider = NULL;
3783 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3785 else
3787 NETRESOURCEA resourcea;
3788 char share_a[MAX_PATH];
3790 resourcea.dwScope = RESOURCE_GLOBALNET;
3791 resourcea.dwType = RESOURCETYPE_DISK;
3792 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3793 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3794 resourcea.lpLocalName = NULL;
3795 filename_to_ansi (share, share_a);
3796 resourcea.lpRemoteName = share_a;
3797 resourcea.lpProvider = NULL;
3799 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3802 switch (val)
3804 case NO_ERROR:
3805 case ERROR_ALREADY_ASSIGNED:
3806 break;
3807 case ERROR_ACCESS_DENIED:
3808 case ERROR_LOGON_FAILURE:
3809 errno = EACCES;
3810 break;
3811 case ERROR_BUSY:
3812 errno = EAGAIN;
3813 break;
3814 case ERROR_BAD_NET_NAME:
3815 case ERROR_NO_NET_OR_BAD_PATH:
3816 case ERROR_NO_NETWORK:
3817 case ERROR_CANCELLED:
3818 default:
3819 errno = ENOENT;
3820 break;
3824 /* Emulate faccessat(2). */
3826 faccessat (int dirfd, const char * path, int mode, int flags)
3828 DWORD attributes;
3830 if (dirfd != AT_FDCWD
3831 && !(IS_DIRECTORY_SEP (path[0])
3832 || IS_DEVICE_SEP (path[1])))
3834 errno = EBADF;
3835 return -1;
3838 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3839 newer versions blow up when passed D_OK. */
3840 path = map_w32_filename (path, NULL);
3841 /* If the last element of PATH is a symlink, we need to resolve it
3842 to get the attributes of its target file. Note: any symlinks in
3843 PATH elements other than the last one are transparently resolved
3844 by GetFileAttributes below. */
3845 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3846 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3847 path = chase_symlinks (path);
3849 if (w32_unicode_filenames)
3851 wchar_t path_w[MAX_PATH];
3853 filename_to_utf16 (path, path_w);
3854 attributes = GetFileAttributesW (path_w);
3856 else
3858 char path_a[MAX_PATH];
3860 filename_to_ansi (path, path_a);
3861 attributes = GetFileAttributesA (path_a);
3864 if (attributes == -1)
3866 DWORD w32err = GetLastError ();
3868 switch (w32err)
3870 case ERROR_INVALID_NAME:
3871 case ERROR_BAD_PATHNAME:
3872 if (is_unc_volume (path))
3874 attributes = unc_volume_file_attributes (path);
3875 if (attributes == -1)
3877 errno = EACCES;
3878 return -1;
3880 goto check_attrs;
3882 /* FALLTHROUGH */
3883 case ERROR_FILE_NOT_FOUND:
3884 case ERROR_BAD_NETPATH:
3885 errno = ENOENT;
3886 break;
3887 default:
3888 errno = EACCES;
3889 break;
3891 return -1;
3894 check_attrs:
3895 if ((mode & X_OK) != 0
3896 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3898 errno = EACCES;
3899 return -1;
3901 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3903 errno = EACCES;
3904 return -1;
3906 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3908 errno = EACCES;
3909 return -1;
3911 return 0;
3914 /* A special test for DIRNAME being a directory accessible by the
3915 current user. This is needed because the security permissions in
3916 directory's ACLs are not visible in the Posix-style mode bits
3917 returned by 'stat' and in attributes returned by GetFileAttributes.
3918 So a directory would seem like it's readable by the current user,
3919 but will in fact error out with EACCES when they actually try. */
3921 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3923 char pattern[MAX_UTF8_PATH];
3924 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3925 HANDLE dh;
3927 /* Network volumes need a different reading method. */
3928 if (is_unc_volume (dirname))
3930 void *read_result = NULL;
3931 wchar_t fnw[MAX_PATH];
3932 char fna[MAX_PATH];
3934 dh = open_unc_volume (dirname);
3935 if (dh != INVALID_HANDLE_VALUE)
3937 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
3938 close_unc_volume (dh);
3940 /* Treat empty volumes as accessible. */
3941 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
3944 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3945 MAX_UTF8_PATH. */
3946 strcpy (pattern, map_w32_filename (dirname, NULL));
3948 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3949 opens the directory that is the target of a symlink. */
3950 if (w32_unicode_filenames)
3952 wchar_t pat_w[MAX_PATH + 2];
3953 WIN32_FIND_DATAW dfd_w;
3955 filename_to_utf16 (pattern, pat_w);
3956 if (!last_slash)
3957 wcscat (pat_w, L"\\");
3958 wcscat (pat_w, L"*");
3959 dh = FindFirstFileW (pat_w, &dfd_w);
3961 else
3963 char pat_a[MAX_PATH + 2];
3964 WIN32_FIND_DATAA dfd_a;
3966 filename_to_ansi (pattern, pat_a);
3967 if (!last_slash)
3968 strcpy (pat_a, "\\");
3969 strcat (pat_a, "*");
3970 /* In case DIRNAME cannot be expressed in characters from the
3971 current ANSI codepage. */
3972 if (_mbspbrk (pat_a, "?"))
3973 dh = INVALID_HANDLE_VALUE;
3974 else
3975 dh = FindFirstFileA (pat_a, &dfd_a);
3978 if (dh == INVALID_HANDLE_VALUE)
3979 return 0;
3980 FindClose (dh);
3981 return 1;
3984 /* A version of 'access' to be used locally with file names in
3985 locale-specific encoding. Does not resolve symlinks and does not
3986 support file names on FAT12 and FAT16 volumes, but that's OK, since
3987 we only invoke this function for files inside the Emacs source or
3988 installation tree, on directories (so any symlinks should have the
3989 directory bit set), and on short file names such as "C:/.emacs". */
3990 static int
3991 sys_access (const char *fname, int mode)
3993 char fname_copy[MAX_PATH], *p;
3994 DWORD attributes;
3996 strcpy (fname_copy, fname);
3997 /* Do the equivalent of unixtodos_filename. */
3998 for (p = fname_copy; *p; p = CharNext (p))
3999 if (*p == '/')
4000 *p = '\\';
4002 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4004 DWORD w32err = GetLastError ();
4006 switch (w32err)
4008 case ERROR_INVALID_NAME:
4009 case ERROR_BAD_PATHNAME:
4010 case ERROR_FILE_NOT_FOUND:
4011 case ERROR_BAD_NETPATH:
4012 errno = ENOENT;
4013 break;
4014 default:
4015 errno = EACCES;
4016 break;
4018 return -1;
4020 if ((mode & X_OK) != 0
4021 && !(is_exec (fname_copy)
4022 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4024 errno = EACCES;
4025 return -1;
4027 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4029 errno = EACCES;
4030 return -1;
4032 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4034 errno = EACCES;
4035 return -1;
4037 return 0;
4040 /* Shadow some MSVC runtime functions to map requests for long filenames
4041 to reasonable short names if necessary. This was originally added to
4042 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4043 long file names. */
4046 sys_chdir (const char * path)
4048 path = map_w32_filename (path, NULL);
4049 if (w32_unicode_filenames)
4051 wchar_t newdir_w[MAX_PATH];
4053 if (filename_to_utf16 (path, newdir_w) == 0)
4054 return _wchdir (newdir_w);
4055 return -1;
4057 else
4059 char newdir_a[MAX_PATH];
4061 if (filename_to_ansi (path, newdir_a) == 0)
4062 return _chdir (newdir_a);
4063 return -1;
4068 sys_chmod (const char * path, int mode)
4070 path = chase_symlinks (map_w32_filename (path, NULL));
4071 if (w32_unicode_filenames)
4073 wchar_t path_w[MAX_PATH];
4075 filename_to_utf16 (path, path_w);
4076 return _wchmod (path_w, mode);
4078 else
4080 char path_a[MAX_PATH];
4082 filename_to_ansi (path, path_a);
4083 return _chmod (path_a, mode);
4088 sys_creat (const char * path, int mode)
4090 path = map_w32_filename (path, NULL);
4091 if (w32_unicode_filenames)
4093 wchar_t path_w[MAX_PATH];
4095 filename_to_utf16 (path, path_w);
4096 return _wcreat (path_w, mode);
4098 else
4100 char path_a[MAX_PATH];
4102 filename_to_ansi (path, path_a);
4103 return _creat (path_a, mode);
4107 FILE *
4108 sys_fopen (const char * path, const char * mode)
4110 int fd;
4111 int oflag;
4112 const char * mode_save = mode;
4114 /* Force all file handles to be non-inheritable. This is necessary to
4115 ensure child processes don't unwittingly inherit handles that might
4116 prevent future file access. */
4118 if (mode[0] == 'r')
4119 oflag = O_RDONLY;
4120 else if (mode[0] == 'w' || mode[0] == 'a')
4121 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4122 else
4123 return NULL;
4125 /* Only do simplistic option parsing. */
4126 while (*++mode)
4127 if (mode[0] == '+')
4129 oflag &= ~(O_RDONLY | O_WRONLY);
4130 oflag |= O_RDWR;
4132 else if (mode[0] == 'b')
4134 oflag &= ~O_TEXT;
4135 oflag |= O_BINARY;
4137 else if (mode[0] == 't')
4139 oflag &= ~O_BINARY;
4140 oflag |= O_TEXT;
4142 else break;
4144 path = map_w32_filename (path, NULL);
4145 if (w32_unicode_filenames)
4147 wchar_t path_w[MAX_PATH];
4149 filename_to_utf16 (path, path_w);
4150 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4152 else
4154 char path_a[MAX_PATH];
4156 filename_to_ansi (path, path_a);
4157 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4159 if (fd < 0)
4160 return NULL;
4162 return _fdopen (fd, mode_save);
4165 /* This only works on NTFS volumes, but is useful to have. */
4167 sys_link (const char * old, const char * new)
4169 HANDLE fileh;
4170 int result = -1;
4171 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4172 wchar_t oldname_w[MAX_PATH];
4173 char oldname_a[MAX_PATH];
4175 if (old == NULL || new == NULL)
4177 errno = ENOENT;
4178 return -1;
4181 strcpy (oldname, map_w32_filename (old, NULL));
4182 strcpy (newname, map_w32_filename (new, NULL));
4184 if (w32_unicode_filenames)
4186 filename_to_utf16 (oldname, oldname_w);
4187 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4188 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4190 else
4192 filename_to_ansi (oldname, oldname_a);
4193 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4194 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4196 if (fileh != INVALID_HANDLE_VALUE)
4198 int wlen;
4200 /* Confusingly, the "alternate" stream name field does not apply
4201 when restoring a hard link, and instead contains the actual
4202 stream data for the link (ie. the name of the link to create).
4203 The WIN32_STREAM_ID structure before the cStreamName field is
4204 the stream header, which is then immediately followed by the
4205 stream data. */
4207 struct {
4208 WIN32_STREAM_ID wid;
4209 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4210 } data;
4212 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4213 indicates that flag is unsupported for CP_UTF8, and OTOH says
4214 it is the default anyway. */
4215 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4216 data.wid.cStreamName, MAX_PATH);
4217 if (wlen > 0)
4219 LPVOID context = NULL;
4220 DWORD wbytes = 0;
4222 data.wid.dwStreamId = BACKUP_LINK;
4223 data.wid.dwStreamAttributes = 0;
4224 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4225 data.wid.Size.HighPart = 0;
4226 data.wid.dwStreamNameSize = 0;
4228 if (BackupWrite (fileh, (LPBYTE)&data,
4229 offsetof (WIN32_STREAM_ID, cStreamName)
4230 + data.wid.Size.LowPart,
4231 &wbytes, FALSE, FALSE, &context)
4232 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4234 /* succeeded */
4235 result = 0;
4237 else
4239 DWORD err = GetLastError ();
4240 DWORD attributes;
4242 switch (err)
4244 case ERROR_ACCESS_DENIED:
4245 /* This is what happens when OLDNAME is a directory,
4246 since Windows doesn't support hard links to
4247 directories. Posix says to set errno to EPERM in
4248 that case. */
4249 if (w32_unicode_filenames)
4250 attributes = GetFileAttributesW (oldname_w);
4251 else
4252 attributes = GetFileAttributesA (oldname_a);
4253 if (attributes != -1
4254 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4255 errno = EPERM;
4256 else if (attributes == -1
4257 && is_unc_volume (oldname)
4258 && unc_volume_file_attributes (oldname) != -1)
4259 errno = EPERM;
4260 else
4261 errno = EACCES;
4262 break;
4263 case ERROR_TOO_MANY_LINKS:
4264 errno = EMLINK;
4265 break;
4266 case ERROR_NOT_SAME_DEVICE:
4267 errno = EXDEV;
4268 break;
4269 default:
4270 errno = EINVAL;
4271 break;
4276 CloseHandle (fileh);
4278 else
4279 errno = ENOENT;
4281 return result;
4285 sys_mkdir (const char * path)
4287 path = map_w32_filename (path, NULL);
4289 if (w32_unicode_filenames)
4291 wchar_t path_w[MAX_PATH];
4293 filename_to_utf16 (path, path_w);
4294 return _wmkdir (path_w);
4296 else
4298 char path_a[MAX_PATH];
4300 filename_to_ansi (path, path_a);
4301 return _mkdir (path_a);
4306 sys_open (const char * path, int oflag, int mode)
4308 const char* mpath = map_w32_filename (path, NULL);
4309 int res = -1;
4311 if (w32_unicode_filenames)
4313 wchar_t mpath_w[MAX_PATH];
4315 filename_to_utf16 (mpath, mpath_w);
4316 /* If possible, try to open file without _O_CREAT, to be able to
4317 write to existing hidden and system files. Force all file
4318 handles to be non-inheritable. */
4319 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4320 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4321 if (res < 0)
4322 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4324 else
4326 char mpath_a[MAX_PATH];
4328 filename_to_ansi (mpath, mpath_a);
4329 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4330 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4331 if (res < 0)
4332 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4335 return res;
4338 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4339 when using mktemp.
4341 Standard algorithm for generating a temporary file name seems to be
4342 use pid or tid with a letter on the front (in place of the 6 X's)
4343 and cycle through the letters to find a unique name. We extend
4344 that to allow any reasonable character as the first of the 6 X's,
4345 so that the number of simultaneously used temporary files will be
4346 greater. */
4349 mkostemp (char * template, int flags)
4351 char * p;
4352 int i, fd = -1;
4353 unsigned uid = GetCurrentThreadId ();
4354 int save_errno = errno;
4355 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4357 errno = EINVAL;
4358 if (template == NULL)
4359 return -1;
4361 p = template + strlen (template);
4362 i = 5;
4363 /* replace up to the last 5 X's with uid in decimal */
4364 while (--p >= template && p[0] == 'X' && --i >= 0)
4366 p[0] = '0' + uid % 10;
4367 uid /= 10;
4370 if (i < 0 && p[0] == 'X')
4372 i = 0;
4375 p[0] = first_char[i];
4376 if ((fd = sys_open (template,
4377 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4378 S_IRUSR | S_IWUSR)) >= 0
4379 || errno != EEXIST)
4381 if (fd >= 0)
4382 errno = save_errno;
4383 return fd;
4386 while (++i < sizeof (first_char));
4389 /* Template is badly formed or else we can't generate a unique name. */
4390 return -1;
4394 fchmod (int fd, mode_t mode)
4396 return 0;
4400 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4402 BOOL result;
4403 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4404 int newname_dev;
4405 int oldname_dev;
4406 bool have_temp_a = false;
4408 /* MoveFile on Windows 95 doesn't correctly change the short file name
4409 alias in a number of circumstances (it is not easy to predict when
4410 just by looking at oldname and newname, unfortunately). In these
4411 cases, renaming through a temporary name avoids the problem.
4413 A second problem on Windows 95 is that renaming through a temp name when
4414 newname is uppercase fails (the final long name ends up in
4415 lowercase, although the short alias might be uppercase) UNLESS the
4416 long temp name is not 8.3.
4418 So, on Windows 95 we always rename through a temp name, and we make sure
4419 the temp name has a long extension to ensure correct renaming. */
4421 strcpy (temp, map_w32_filename (oldname, NULL));
4423 /* volume_info is set indirectly by map_w32_filename. */
4424 oldname_dev = volume_info.serialnum;
4426 if (os_subtype == OS_9X)
4428 char * o;
4429 char * p;
4430 int i = 0;
4431 char oldname_a[MAX_PATH];
4433 oldname = map_w32_filename (oldname, NULL);
4434 filename_to_ansi (oldname, oldname_a);
4435 filename_to_ansi (temp, temp_a);
4436 if ((o = strrchr (oldname_a, '\\')))
4437 o++;
4438 else
4439 o = (char *) oldname_a;
4441 if ((p = strrchr (temp_a, '\\')))
4442 p++;
4443 else
4444 p = temp_a;
4448 /* Force temp name to require a manufactured 8.3 alias - this
4449 seems to make the second rename work properly. */
4450 sprintf (p, "_.%s.%u", o, i);
4451 i++;
4452 result = rename (oldname_a, temp_a);
4454 /* This loop must surely terminate! */
4455 while (result < 0 && errno == EEXIST);
4456 if (result < 0)
4457 return -1;
4458 have_temp_a = true;
4461 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4462 (at least if it is a file; don't do this for directories).
4464 Since we mustn't do this if we are just changing the case of the
4465 file name (we would end up deleting the file we are trying to
4466 rename!), we let rename detect if the destination file already
4467 exists - that way we avoid the possible pitfalls of trying to
4468 determine ourselves whether two names really refer to the same
4469 file, which is not always possible in the general case. (Consider
4470 all the permutations of shared or subst'd drives, etc.) */
4472 newname = map_w32_filename (newname, NULL);
4474 /* volume_info is set indirectly by map_w32_filename. */
4475 newname_dev = volume_info.serialnum;
4477 if (w32_unicode_filenames)
4479 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4481 filename_to_utf16 (temp, temp_w);
4482 filename_to_utf16 (newname, newname_w);
4483 result = _wrename (temp_w, newname_w);
4484 if (result < 0 && force)
4486 DWORD w32err = GetLastError ();
4488 if (errno == EACCES
4489 && newname_dev != oldname_dev)
4491 /* The implementation of `rename' on Windows does not return
4492 errno = EXDEV when you are moving a directory to a
4493 different storage device (ex. logical disk). It returns
4494 EACCES instead. So here we handle such situations and
4495 return EXDEV. */
4496 DWORD attributes;
4498 if ((attributes = GetFileAttributesW (temp_w)) != -1
4499 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4500 errno = EXDEV;
4502 else if (errno == EEXIST)
4504 if (_wchmod (newname_w, 0666) != 0)
4505 return result;
4506 if (_wunlink (newname_w) != 0)
4507 return result;
4508 result = _wrename (temp_w, newname_w);
4510 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4511 && is_symlink (temp))
4513 /* This is Windows prohibiting the user from creating a
4514 symlink in another place, since that requires
4515 privileges. */
4516 errno = EPERM;
4520 else
4522 char newname_a[MAX_PATH];
4524 if (!have_temp_a)
4525 filename_to_ansi (temp, temp_a);
4526 filename_to_ansi (newname, newname_a);
4527 result = rename (temp_a, newname_a);
4528 if (result < 0 && force)
4530 DWORD w32err = GetLastError ();
4532 if (errno == EACCES
4533 && newname_dev != oldname_dev)
4535 DWORD attributes;
4537 if ((attributes = GetFileAttributesA (temp_a)) != -1
4538 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4539 errno = EXDEV;
4541 else if (errno == EEXIST)
4543 if (_chmod (newname_a, 0666) != 0)
4544 return result;
4545 if (_unlink (newname_a) != 0)
4546 return result;
4547 result = rename (temp_a, newname_a);
4549 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4550 && is_symlink (temp))
4551 errno = EPERM;
4555 return result;
4559 sys_rename (char const *old, char const *new)
4561 return sys_rename_replace (old, new, TRUE);
4565 sys_rmdir (const char * path)
4567 path = map_w32_filename (path, NULL);
4569 if (w32_unicode_filenames)
4571 wchar_t path_w[MAX_PATH];
4573 filename_to_utf16 (path, path_w);
4574 return _wrmdir (path_w);
4576 else
4578 char path_a[MAX_PATH];
4580 filename_to_ansi (path, path_a);
4581 return _rmdir (path_a);
4586 sys_unlink (const char * path)
4588 int rmstatus, e;
4590 path = map_w32_filename (path, NULL);
4592 if (w32_unicode_filenames)
4594 wchar_t path_w[MAX_PATH];
4596 filename_to_utf16 (path, path_w);
4597 /* On Unix, unlink works without write permission. */
4598 _wchmod (path_w, 0666);
4599 rmstatus = _wunlink (path_w);
4600 e = errno;
4601 /* Symlinks to directories can only be deleted by _rmdir;
4602 _unlink returns EACCES. */
4603 if (rmstatus != 0
4604 && errno == EACCES
4605 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4606 rmstatus = _wrmdir (path_w);
4607 else
4608 errno = e;
4610 else
4612 char path_a[MAX_PATH];
4614 filename_to_ansi (path, path_a);
4615 _chmod (path_a, 0666);
4616 rmstatus = _unlink (path_a);
4617 e = errno;
4618 if (rmstatus != 0
4619 && errno == EACCES
4620 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4621 rmstatus = _rmdir (path_a);
4622 else
4623 errno = e;
4626 return rmstatus;
4629 static FILETIME utc_base_ft;
4630 static ULONGLONG utc_base; /* In 100ns units */
4631 static int init = 0;
4633 #define FILETIME_TO_U64(result, ft) \
4634 do { \
4635 ULARGE_INTEGER uiTemp; \
4636 uiTemp.LowPart = (ft).dwLowDateTime; \
4637 uiTemp.HighPart = (ft).dwHighDateTime; \
4638 result = uiTemp.QuadPart; \
4639 } while (0)
4641 static void
4642 initialize_utc_base (void)
4644 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4645 SYSTEMTIME st;
4647 st.wYear = 1970;
4648 st.wMonth = 1;
4649 st.wDay = 1;
4650 st.wHour = 0;
4651 st.wMinute = 0;
4652 st.wSecond = 0;
4653 st.wMilliseconds = 0;
4655 SystemTimeToFileTime (&st, &utc_base_ft);
4656 FILETIME_TO_U64 (utc_base, utc_base_ft);
4659 static time_t
4660 convert_time (FILETIME ft)
4662 ULONGLONG tmp;
4664 if (!init)
4666 initialize_utc_base ();
4667 init = 1;
4670 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4671 return 0;
4673 FILETIME_TO_U64 (tmp, ft);
4674 return (time_t) ((tmp - utc_base) / 10000000L);
4677 static void
4678 convert_from_time_t (time_t time, FILETIME * pft)
4680 ULARGE_INTEGER tmp;
4682 if (!init)
4684 initialize_utc_base ();
4685 init = 1;
4688 /* time in 100ns units since 1-Jan-1601 */
4689 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4690 pft->dwHighDateTime = tmp.HighPart;
4691 pft->dwLowDateTime = tmp.LowPart;
4694 static PSECURITY_DESCRIPTOR
4695 get_file_security_desc_by_handle (HANDLE h)
4697 PSECURITY_DESCRIPTOR psd = NULL;
4698 DWORD err;
4699 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4700 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4702 err = get_security_info (h, SE_FILE_OBJECT, si,
4703 NULL, NULL, NULL, NULL, &psd);
4704 if (err != ERROR_SUCCESS)
4705 return NULL;
4707 return psd;
4710 static PSECURITY_DESCRIPTOR
4711 get_file_security_desc_by_name (const char *fname)
4713 PSECURITY_DESCRIPTOR psd = NULL;
4714 DWORD sd_len, err;
4715 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4716 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4718 if (!get_file_security (fname, si, psd, 0, &sd_len))
4720 err = GetLastError ();
4721 if (err != ERROR_INSUFFICIENT_BUFFER)
4722 return NULL;
4725 psd = xmalloc (sd_len);
4726 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4728 xfree (psd);
4729 return NULL;
4732 return psd;
4735 static DWORD
4736 get_rid (PSID sid)
4738 unsigned n_subauthorities;
4740 /* Use the last sub-authority value of the RID, the relative
4741 portion of the SID, as user/group ID. */
4742 n_subauthorities = *get_sid_sub_authority_count (sid);
4743 if (n_subauthorities < 1)
4744 return 0; /* the "World" RID */
4745 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4748 /* Caching SID and account values for faster lokup. */
4750 struct w32_id {
4751 unsigned rid;
4752 struct w32_id *next;
4753 char name[GNLEN+1];
4754 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4757 static struct w32_id *w32_idlist;
4759 static int
4760 w32_cached_id (PSID sid, unsigned *id, char *name)
4762 struct w32_id *tail, *found;
4764 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4766 if (equal_sid ((PSID)tail->sid, sid))
4768 found = tail;
4769 break;
4772 if (found)
4774 *id = found->rid;
4775 strcpy (name, found->name);
4776 return 1;
4778 else
4779 return 0;
4782 static void
4783 w32_add_to_cache (PSID sid, unsigned id, char *name)
4785 DWORD sid_len;
4786 struct w32_id *new_entry;
4788 /* We don't want to leave behind stale cache from when Emacs was
4789 dumped. */
4790 if (initialized)
4792 sid_len = get_length_sid (sid);
4793 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4794 if (new_entry)
4796 new_entry->rid = id;
4797 strcpy (new_entry->name, name);
4798 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4799 new_entry->next = w32_idlist;
4800 w32_idlist = new_entry;
4805 #define UID 1
4806 #define GID 2
4808 static int
4809 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4811 PSID sid = NULL;
4812 BOOL dflt;
4813 SID_NAME_USE ignore;
4814 char name[UNLEN+1];
4815 DWORD name_len = sizeof (name);
4816 char domain[1024];
4817 DWORD domain_len = sizeof (domain);
4818 int use_dflt = 0;
4819 int result;
4821 if (what == UID)
4822 result = get_security_descriptor_owner (psd, &sid, &dflt);
4823 else if (what == GID)
4824 result = get_security_descriptor_group (psd, &sid, &dflt);
4825 else
4826 result = 0;
4828 if (!result || !is_valid_sid (sid))
4829 use_dflt = 1;
4830 else if (!w32_cached_id (sid, id, nm))
4832 if (!lookup_account_sid (NULL, sid, name, &name_len,
4833 domain, &domain_len, &ignore)
4834 || name_len > UNLEN+1)
4835 use_dflt = 1;
4836 else
4838 *id = get_rid (sid);
4839 strcpy (nm, name);
4840 w32_add_to_cache (sid, *id, name);
4843 return use_dflt;
4846 static void
4847 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4849 int dflt_usr = 0, dflt_grp = 0;
4851 if (!psd)
4853 dflt_usr = 1;
4854 dflt_grp = 1;
4856 else
4858 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4859 dflt_usr = 1;
4860 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4861 dflt_grp = 1;
4863 /* Consider files to belong to current user/group, if we cannot get
4864 more accurate information. */
4865 if (dflt_usr)
4867 st->st_uid = dflt_passwd.pw_uid;
4868 strcpy (st->st_uname, dflt_passwd.pw_name);
4870 if (dflt_grp)
4872 st->st_gid = dflt_passwd.pw_gid;
4873 strcpy (st->st_gname, dflt_group.gr_name);
4877 /* Return non-zero if NAME is a potentially slow filesystem. */
4879 is_slow_fs (const char *name)
4881 char drive_root[4];
4882 UINT devtype;
4884 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4885 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4886 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4887 devtype = GetDriveType (NULL); /* use root of current drive */
4888 else
4890 /* GetDriveType needs the root directory of the drive. */
4891 strncpy (drive_root, name, 2);
4892 drive_root[2] = '\\';
4893 drive_root[3] = '\0';
4894 devtype = GetDriveType (drive_root);
4896 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4899 /* If this is non-zero, the caller wants accurate information about
4900 file's owner and group, which could be expensive to get. dired.c
4901 uses this flag when needed for the job at hand. */
4902 int w32_stat_get_owner_group;
4904 /* MSVC stat function can't cope with UNC names and has other bugs, so
4905 replace it with our own. This also allows us to calculate consistent
4906 inode values and owner/group without hacks in the main Emacs code,
4907 and support file names encoded in UTF-8. */
4909 static int
4910 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4912 char *name, *save_name, *r;
4913 WIN32_FIND_DATAW wfd_w;
4914 WIN32_FIND_DATAA wfd_a;
4915 HANDLE fh;
4916 unsigned __int64 fake_inode = 0;
4917 int permission;
4918 int len;
4919 int rootdir = FALSE;
4920 PSECURITY_DESCRIPTOR psd = NULL;
4921 int is_a_symlink = 0;
4922 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4923 DWORD access_rights = 0;
4924 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4925 FILETIME ctime, atime, wtime;
4926 wchar_t name_w[MAX_PATH];
4927 char name_a[MAX_PATH];
4929 if (path == NULL || buf == NULL)
4931 errno = EFAULT;
4932 return -1;
4935 save_name = name = (char *) map_w32_filename (path, &path);
4936 /* Must be valid filename, no wild cards or other invalid
4937 characters. */
4938 if (strpbrk (name, "*?|<>\""))
4940 errno = ENOENT;
4941 return -1;
4944 len = strlen (name);
4945 /* Allocate 1 extra byte so that we could append a slash to a root
4946 directory, down below. */
4947 name = strcpy (alloca (len + 2), name);
4949 /* Avoid a somewhat costly call to is_symlink if the filesystem
4950 doesn't support symlinks. */
4951 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4952 is_a_symlink = is_symlink (name);
4954 /* Plan A: Open the file and get all the necessary information via
4955 the resulting handle. This solves several issues in one blow:
4957 . retrieves attributes for the target of a symlink, if needed
4958 . gets attributes of root directories and symlinks pointing to
4959 root directories, thus avoiding the need for special-casing
4960 these and detecting them by examining the file-name format
4961 . retrieves more accurate attributes (e.g., non-zero size for
4962 some directories, esp. directories that are junction points)
4963 . correctly resolves "c:/..", "/.." and similar file names
4964 . avoids run-time penalties for 99% of use cases
4966 Plan A is always tried first, unless the user asked not to (but
4967 if the file is a symlink and we need to follow links, we try Plan
4968 A even if the user asked not to).
4970 If Plan A fails, we go to Plan B (below), where various
4971 potentially expensive techniques must be used to handle "special"
4972 files such as UNC volumes etc. */
4973 if (!(NILP (Vw32_get_true_file_attributes)
4974 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4975 /* Following symlinks requires getting the info by handle. */
4976 || (is_a_symlink && follow_symlinks))
4978 BY_HANDLE_FILE_INFORMATION info;
4980 if (is_a_symlink && !follow_symlinks)
4981 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4982 /* READ_CONTROL access rights are required to get security info
4983 by handle. But if the OS doesn't support security in the
4984 first place, we don't need to try. */
4985 if (is_windows_9x () != TRUE)
4986 access_rights |= READ_CONTROL;
4988 if (w32_unicode_filenames)
4990 filename_to_utf16 (name, name_w);
4991 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4992 file_flags, NULL);
4993 /* If CreateFile fails with READ_CONTROL, try again with
4994 zero as access rights. */
4995 if (fh == INVALID_HANDLE_VALUE && access_rights)
4996 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
4997 file_flags, NULL);
4999 else
5001 filename_to_ansi (name, name_a);
5002 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5003 file_flags, NULL);
5004 if (fh == INVALID_HANDLE_VALUE && access_rights)
5005 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5006 file_flags, NULL);
5008 if (fh == INVALID_HANDLE_VALUE)
5009 goto no_true_file_attributes;
5011 /* This is more accurate in terms of getting the correct number
5012 of links, but is quite slow (it is noticeable when Emacs is
5013 making a list of file name completions). */
5014 if (GetFileInformationByHandle (fh, &info))
5016 nlinks = info.nNumberOfLinks;
5017 /* Might as well use file index to fake inode values, but this
5018 is not guaranteed to be unique unless we keep a handle open
5019 all the time (even then there are situations where it is
5020 not unique). Reputedly, there are at most 48 bits of info
5021 (on NTFS, presumably less on FAT). */
5022 fake_inode = info.nFileIndexHigh;
5023 fake_inode <<= 32;
5024 fake_inode += info.nFileIndexLow;
5025 serialnum = info.dwVolumeSerialNumber;
5026 fs_high = info.nFileSizeHigh;
5027 fs_low = info.nFileSizeLow;
5028 ctime = info.ftCreationTime;
5029 atime = info.ftLastAccessTime;
5030 wtime = info.ftLastWriteTime;
5031 fattrs = info.dwFileAttributes;
5033 else
5035 /* We don't go to Plan B here, because it's not clear that
5036 it's a good idea. The only known use case where
5037 CreateFile succeeds, but GetFileInformationByHandle fails
5038 (with ERROR_INVALID_FUNCTION) is for character devices
5039 such as NUL, PRN, etc. For these, switching to Plan B is
5040 a net loss, because we lose the character device
5041 attribute returned by GetFileType below (FindFirstFile
5042 doesn't set that bit in the attributes), and the other
5043 fields don't make sense for character devices anyway.
5044 Emacs doesn't really care for non-file entities in the
5045 context of l?stat, so neither do we. */
5047 /* w32err is assigned so one could put a breakpoint here and
5048 examine its value, when GetFileInformationByHandle
5049 fails. */
5050 DWORD w32err = GetLastError ();
5052 switch (w32err)
5054 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5055 errno = ENOENT;
5056 return -1;
5060 /* Test for a symlink before testing for a directory, since
5061 symlinks to directories have the directory bit set, but we
5062 don't want them to appear as directories. */
5063 if (is_a_symlink && !follow_symlinks)
5064 buf->st_mode = S_IFLNK;
5065 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5066 buf->st_mode = S_IFDIR;
5067 else
5069 DWORD ftype = GetFileType (fh);
5071 switch (ftype)
5073 case FILE_TYPE_DISK:
5074 buf->st_mode = S_IFREG;
5075 break;
5076 case FILE_TYPE_PIPE:
5077 buf->st_mode = S_IFIFO;
5078 break;
5079 case FILE_TYPE_CHAR:
5080 case FILE_TYPE_UNKNOWN:
5081 default:
5082 buf->st_mode = S_IFCHR;
5085 /* We produce the fallback owner and group data, based on the
5086 current user that runs Emacs, in the following cases:
5088 . caller didn't request owner and group info
5089 . this is Windows 9X
5090 . getting security by handle failed, and we need to produce
5091 information for the target of a symlink (this is better
5092 than producing a potentially misleading info about the
5093 symlink itself)
5095 If getting security by handle fails, and we don't need to
5096 resolve symlinks, we try getting security by name. */
5097 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5098 get_file_owner_and_group (NULL, buf);
5099 else
5101 psd = get_file_security_desc_by_handle (fh);
5102 if (psd)
5104 get_file_owner_and_group (psd, buf);
5105 LocalFree (psd);
5107 else if (!(is_a_symlink && follow_symlinks))
5109 psd = get_file_security_desc_by_name (name);
5110 get_file_owner_and_group (psd, buf);
5111 xfree (psd);
5113 else
5114 get_file_owner_and_group (NULL, buf);
5116 CloseHandle (fh);
5118 else
5120 no_true_file_attributes:
5121 /* Plan B: Either getting a handle on the file failed, or the
5122 caller explicitly asked us to not bother making this
5123 information more accurate.
5125 Implementation note: In Plan B, we never bother to resolve
5126 symlinks, even if we got here because we tried Plan A and
5127 failed. That's because, even if the caller asked for extra
5128 precision by setting Vw32_get_true_file_attributes to t,
5129 resolving symlinks requires acquiring a file handle to the
5130 symlink, which we already know will fail. And if the user
5131 did not ask for extra precision, resolving symlinks will fly
5132 in the face of that request, since the user then wants the
5133 lightweight version of the code. */
5134 rootdir = (path >= save_name + len - 1
5135 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5137 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5138 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5139 if (IS_DIRECTORY_SEP (r[0])
5140 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5141 r[1] = r[2] = '\0';
5143 /* Note: If NAME is a symlink to the root of a UNC volume
5144 (i.e. "\\SERVER"), we will not detect that here, and we will
5145 return data about the symlink as result of FindFirst below.
5146 This is unfortunate, but that marginal use case does not
5147 justify a call to chase_symlinks which would impose a penalty
5148 on all the other use cases. (We get here for symlinks to
5149 roots of UNC volumes because CreateFile above fails for them,
5150 unlike with symlinks to root directories X:\ of drives.) */
5151 if (is_unc_volume (name))
5153 fattrs = unc_volume_file_attributes (name);
5154 if (fattrs == -1)
5155 return -1;
5157 ctime = atime = wtime = utc_base_ft;
5159 else if (rootdir)
5161 /* Make sure root directories end in a slash. */
5162 if (!IS_DIRECTORY_SEP (name[len-1]))
5163 strcpy (name + len, "\\");
5164 if (GetDriveType (name) < 2)
5166 errno = ENOENT;
5167 return -1;
5170 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5171 ctime = atime = wtime = utc_base_ft;
5173 else
5175 int have_wfd = -1;
5177 /* Make sure non-root directories do NOT end in a slash,
5178 otherwise FindFirstFile might fail. */
5179 if (IS_DIRECTORY_SEP (name[len-1]))
5180 name[len - 1] = 0;
5182 /* (This is hacky, but helps when doing file completions on
5183 network drives.) Optimize by using information available from
5184 active readdir if possible. */
5185 len = strlen (dir_pathname);
5186 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5187 len--;
5188 if (dir_find_handle != INVALID_HANDLE_VALUE
5189 && last_dir_find_data != -1
5190 && !(is_a_symlink && follow_symlinks)
5191 /* The 2 file-name comparisons below support only ASCII
5192 characters, and will lose (compare not equal) when
5193 the file names include non-ASCII characters that are
5194 the same but for the case. However, doing this
5195 properly involves: (a) converting both file names to
5196 UTF-16, (b) lower-casing both names using CharLowerW,
5197 and (c) comparing the results; this would be quite a
5198 bit slower, whereas Plan B is for users who want
5199 lightweight albeit inaccurate version of 'stat'. */
5200 && c_strncasecmp (save_name, dir_pathname, len) == 0
5201 && IS_DIRECTORY_SEP (name[len])
5202 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5204 have_wfd = last_dir_find_data;
5205 /* This was the last entry returned by readdir. */
5206 if (last_dir_find_data == DIR_FIND_DATA_W)
5207 wfd_w = dir_find_data_w;
5208 else
5209 wfd_a = dir_find_data_a;
5211 else
5213 logon_network_drive (name);
5215 if (w32_unicode_filenames)
5217 filename_to_utf16 (name, name_w);
5218 fh = FindFirstFileW (name_w, &wfd_w);
5219 have_wfd = DIR_FIND_DATA_W;
5221 else
5223 filename_to_ansi (name, name_a);
5224 /* If NAME includes characters not representable by
5225 the current ANSI codepage, filename_to_ansi
5226 usually replaces them with a '?'. We don't want
5227 to let FindFirstFileA interpret those as wildcards,
5228 and "succeed", returning us data from some random
5229 file in the same directory. */
5230 if (_mbspbrk (name_a, "?"))
5231 fh = INVALID_HANDLE_VALUE;
5232 else
5233 fh = FindFirstFileA (name_a, &wfd_a);
5234 have_wfd = DIR_FIND_DATA_A;
5236 if (fh == INVALID_HANDLE_VALUE)
5238 errno = ENOENT;
5239 return -1;
5241 FindClose (fh);
5243 /* Note: if NAME is a symlink, the information we get from
5244 FindFirstFile is for the symlink, not its target. */
5245 if (have_wfd == DIR_FIND_DATA_W)
5247 fattrs = wfd_w.dwFileAttributes;
5248 ctime = wfd_w.ftCreationTime;
5249 atime = wfd_w.ftLastAccessTime;
5250 wtime = wfd_w.ftLastWriteTime;
5251 fs_high = wfd_w.nFileSizeHigh;
5252 fs_low = wfd_w.nFileSizeLow;
5254 else
5256 fattrs = wfd_a.dwFileAttributes;
5257 ctime = wfd_a.ftCreationTime;
5258 atime = wfd_a.ftLastAccessTime;
5259 wtime = wfd_a.ftLastWriteTime;
5260 fs_high = wfd_a.nFileSizeHigh;
5261 fs_low = wfd_a.nFileSizeLow;
5263 fake_inode = 0;
5264 nlinks = 1;
5265 serialnum = volume_info.serialnum;
5267 if (is_a_symlink && !follow_symlinks)
5268 buf->st_mode = S_IFLNK;
5269 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5270 buf->st_mode = S_IFDIR;
5271 else
5272 buf->st_mode = S_IFREG;
5274 get_file_owner_and_group (NULL, buf);
5277 buf->st_ino = fake_inode;
5279 buf->st_dev = serialnum;
5280 buf->st_rdev = serialnum;
5282 buf->st_size = fs_high;
5283 buf->st_size <<= 32;
5284 buf->st_size += fs_low;
5285 buf->st_nlink = nlinks;
5287 /* Convert timestamps to Unix format. */
5288 buf->st_mtime = convert_time (wtime);
5289 buf->st_atime = convert_time (atime);
5290 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5291 buf->st_ctime = convert_time (ctime);
5292 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5294 /* determine rwx permissions */
5295 if (is_a_symlink && !follow_symlinks)
5296 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5297 else
5299 if (fattrs & FILE_ATTRIBUTE_READONLY)
5300 permission = S_IREAD;
5301 else
5302 permission = S_IREAD | S_IWRITE;
5304 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5305 permission |= S_IEXEC;
5306 else if (is_exec (name))
5307 permission |= S_IEXEC;
5310 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5312 return 0;
5316 stat (const char * path, struct stat * buf)
5318 return stat_worker (path, buf, 1);
5322 lstat (const char * path, struct stat * buf)
5324 return stat_worker (path, buf, 0);
5328 fstatat (int fd, char const *name, struct stat *st, int flags)
5330 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5331 This is good enough for the current usage in Emacs, but is fragile.
5333 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5334 Gnulib does this and can serve as a model. */
5335 char fullname[MAX_UTF8_PATH];
5337 if (fd != AT_FDCWD)
5339 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5341 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5342 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5343 < 0)
5345 errno = ENAMETOOLONG;
5346 return -1;
5348 name = fullname;
5351 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5354 /* Provide fstat and utime as well as stat for consistent handling of
5355 file timestamps. */
5357 fstat (int desc, struct stat * buf)
5359 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5360 BY_HANDLE_FILE_INFORMATION info;
5361 unsigned __int64 fake_inode;
5362 int permission;
5364 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5366 case FILE_TYPE_DISK:
5367 buf->st_mode = S_IFREG;
5368 if (!GetFileInformationByHandle (fh, &info))
5370 errno = EACCES;
5371 return -1;
5373 break;
5374 case FILE_TYPE_PIPE:
5375 buf->st_mode = S_IFIFO;
5376 goto non_disk;
5377 case FILE_TYPE_CHAR:
5378 case FILE_TYPE_UNKNOWN:
5379 default:
5380 buf->st_mode = S_IFCHR;
5381 non_disk:
5382 memset (&info, 0, sizeof (info));
5383 info.dwFileAttributes = 0;
5384 info.ftCreationTime = utc_base_ft;
5385 info.ftLastAccessTime = utc_base_ft;
5386 info.ftLastWriteTime = utc_base_ft;
5389 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5390 buf->st_mode = S_IFDIR;
5392 buf->st_nlink = info.nNumberOfLinks;
5393 /* Might as well use file index to fake inode values, but this
5394 is not guaranteed to be unique unless we keep a handle open
5395 all the time (even then there are situations where it is
5396 not unique). Reputedly, there are at most 48 bits of info
5397 (on NTFS, presumably less on FAT). */
5398 fake_inode = info.nFileIndexHigh;
5399 fake_inode <<= 32;
5400 fake_inode += info.nFileIndexLow;
5402 /* MSVC defines _ino_t to be short; other libc's might not. */
5403 if (sizeof (buf->st_ino) == 2)
5404 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5405 else
5406 buf->st_ino = fake_inode;
5408 /* If the caller so requested, get the true file owner and group.
5409 Otherwise, consider the file to belong to the current user. */
5410 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5411 get_file_owner_and_group (NULL, buf);
5412 else
5414 PSECURITY_DESCRIPTOR psd = NULL;
5416 psd = get_file_security_desc_by_handle (fh);
5417 if (psd)
5419 get_file_owner_and_group (psd, buf);
5420 LocalFree (psd);
5422 else
5423 get_file_owner_and_group (NULL, buf);
5426 buf->st_dev = info.dwVolumeSerialNumber;
5427 buf->st_rdev = info.dwVolumeSerialNumber;
5429 buf->st_size = info.nFileSizeHigh;
5430 buf->st_size <<= 32;
5431 buf->st_size += info.nFileSizeLow;
5433 /* Convert timestamps to Unix format. */
5434 buf->st_mtime = convert_time (info.ftLastWriteTime);
5435 buf->st_atime = convert_time (info.ftLastAccessTime);
5436 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5437 buf->st_ctime = convert_time (info.ftCreationTime);
5438 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5440 /* determine rwx permissions */
5441 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5442 permission = S_IREAD;
5443 else
5444 permission = S_IREAD | S_IWRITE;
5446 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5447 permission |= S_IEXEC;
5448 else
5450 #if 0 /* no way of knowing the filename */
5451 char * p = strrchr (name, '.');
5452 if (p != NULL &&
5453 (xstrcasecmp (p, ".exe") == 0 ||
5454 xstrcasecmp (p, ".com") == 0 ||
5455 xstrcasecmp (p, ".bat") == 0 ||
5456 xstrcasecmp (p, ".cmd") == 0))
5457 permission |= S_IEXEC;
5458 #endif
5461 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5463 return 0;
5466 /* A version of 'utime' which handles directories as well as
5467 files. */
5470 utime (const char *name, struct utimbuf *times)
5472 struct utimbuf deftime;
5473 HANDLE fh;
5474 FILETIME mtime;
5475 FILETIME atime;
5477 if (times == NULL)
5479 deftime.modtime = deftime.actime = time (NULL);
5480 times = &deftime;
5483 if (w32_unicode_filenames)
5485 wchar_t name_utf16[MAX_PATH];
5487 if (filename_to_utf16 (name, name_utf16) != 0)
5488 return -1; /* errno set by filename_to_utf16 */
5490 /* Need write access to set times. */
5491 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5492 /* If NAME specifies a directory, FILE_SHARE_DELETE
5493 allows other processes to delete files inside it,
5494 while we have the directory open. */
5495 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5496 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5498 else
5500 char name_ansi[MAX_PATH];
5502 if (filename_to_ansi (name, name_ansi) != 0)
5503 return -1; /* errno set by filename_to_ansi */
5505 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5506 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5507 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5509 if (fh != INVALID_HANDLE_VALUE)
5511 convert_from_time_t (times->actime, &atime);
5512 convert_from_time_t (times->modtime, &mtime);
5513 if (!SetFileTime (fh, NULL, &atime, &mtime))
5515 CloseHandle (fh);
5516 errno = EACCES;
5517 return -1;
5519 CloseHandle (fh);
5521 else
5523 DWORD err = GetLastError ();
5525 switch (err)
5527 case ERROR_FILE_NOT_FOUND:
5528 case ERROR_PATH_NOT_FOUND:
5529 case ERROR_INVALID_DRIVE:
5530 case ERROR_BAD_NETPATH:
5531 case ERROR_DEV_NOT_EXIST:
5532 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5533 file name includes ?s, i.e. translation to ANSI failed. */
5534 case ERROR_INVALID_NAME:
5535 errno = ENOENT;
5536 break;
5537 case ERROR_TOO_MANY_OPEN_FILES:
5538 errno = ENFILE;
5539 break;
5540 case ERROR_ACCESS_DENIED:
5541 case ERROR_SHARING_VIOLATION:
5542 errno = EACCES;
5543 break;
5544 default:
5545 errno = EINVAL;
5546 break;
5548 return -1;
5550 return 0;
5554 sys_umask (int mode)
5556 static int current_mask;
5557 int retval, arg = 0;
5559 /* The only bit we really support is the write bit. Files are
5560 always readable on MS-Windows, and the execute bit does not exist
5561 at all. */
5562 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5563 to prevent access by other users on NTFS. */
5564 if ((mode & S_IWRITE) != 0)
5565 arg |= S_IWRITE;
5567 retval = _umask (arg);
5568 /* Merge into the return value the bits they've set the last time,
5569 which msvcrt.dll ignores and never returns. Emacs insists on its
5570 notion of mask being identical to what we return. */
5571 retval |= (current_mask & ~S_IWRITE);
5572 current_mask = mode;
5574 return retval;
5578 /* Symlink-related functions. */
5579 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5580 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5581 #endif
5584 symlink (char const *filename, char const *linkname)
5586 char linkfn[MAX_UTF8_PATH], *tgtfn;
5587 DWORD flags = 0;
5588 int dir_access, filename_ends_in_slash;
5590 /* Diagnostics follows Posix as much as possible. */
5591 if (filename == NULL || linkname == NULL)
5593 errno = EFAULT;
5594 return -1;
5596 if (!*filename)
5598 errno = ENOENT;
5599 return -1;
5601 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5603 errno = ENAMETOOLONG;
5604 return -1;
5607 strcpy (linkfn, map_w32_filename (linkname, NULL));
5608 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5610 errno = EPERM;
5611 return -1;
5614 /* Note: since empty FILENAME was already rejected, we can safely
5615 refer to FILENAME[1]. */
5616 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5618 /* Non-absolute FILENAME is understood as being relative to
5619 LINKNAME's directory. We need to prepend that directory to
5620 FILENAME to get correct results from faccessat below, since
5621 otherwise it will interpret FILENAME relative to the
5622 directory where the Emacs process runs. Note that
5623 make-symbolic-link always makes sure LINKNAME is a fully
5624 expanded file name. */
5625 char tem[MAX_UTF8_PATH];
5626 char *p = linkfn + strlen (linkfn);
5628 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5629 p--;
5630 if (p > linkfn)
5631 strncpy (tem, linkfn, p - linkfn);
5632 strcpy (tem + (p - linkfn), filename);
5633 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5635 else
5636 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5638 /* Since Windows distinguishes between symlinks to directories and
5639 to files, we provide a kludgy feature: if FILENAME doesn't
5640 exist, but ends in a slash, we create a symlink to directory. If
5641 FILENAME exists and is a directory, we always create a symlink to
5642 directory. */
5643 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5644 if (dir_access == 0 || filename_ends_in_slash)
5645 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5647 tgtfn = (char *)map_w32_filename (filename, NULL);
5648 if (filename_ends_in_slash)
5649 tgtfn[strlen (tgtfn) - 1] = '\0';
5651 errno = 0;
5652 if (!create_symbolic_link (linkfn, tgtfn, flags))
5654 /* ENOSYS is set by create_symbolic_link, when it detects that
5655 the OS doesn't support the CreateSymbolicLink API. */
5656 if (errno != ENOSYS)
5658 DWORD w32err = GetLastError ();
5660 switch (w32err)
5662 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5663 TGTFN point to the same file name, go figure. */
5664 case ERROR_SUCCESS:
5665 case ERROR_FILE_EXISTS:
5666 errno = EEXIST;
5667 break;
5668 case ERROR_ACCESS_DENIED:
5669 errno = EACCES;
5670 break;
5671 case ERROR_FILE_NOT_FOUND:
5672 case ERROR_PATH_NOT_FOUND:
5673 case ERROR_BAD_NETPATH:
5674 case ERROR_INVALID_REPARSE_DATA:
5675 errno = ENOENT;
5676 break;
5677 case ERROR_DIRECTORY:
5678 errno = EISDIR;
5679 break;
5680 case ERROR_PRIVILEGE_NOT_HELD:
5681 case ERROR_NOT_ALL_ASSIGNED:
5682 errno = EPERM;
5683 break;
5684 case ERROR_DISK_FULL:
5685 errno = ENOSPC;
5686 break;
5687 default:
5688 errno = EINVAL;
5689 break;
5692 return -1;
5694 return 0;
5697 /* A quick inexpensive test of whether FILENAME identifies a file that
5698 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5699 must already be in the normalized form returned by
5700 map_w32_filename. If the symlink is to a directory, the
5701 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5703 Note: for repeated operations on many files, it is best to test
5704 whether the underlying volume actually supports symlinks, by
5705 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5706 avoid the call to this function if it doesn't. That's because the
5707 call to GetFileAttributes takes a non-negligible time, especially
5708 on non-local or removable filesystems. See stat_worker for an
5709 example of how to do that. */
5710 static int
5711 is_symlink (const char *filename)
5713 DWORD attrs;
5714 wchar_t filename_w[MAX_PATH];
5715 char filename_a[MAX_PATH];
5716 WIN32_FIND_DATAW wfdw;
5717 WIN32_FIND_DATAA wfda;
5718 HANDLE fh;
5719 int attrs_mean_symlink;
5721 if (w32_unicode_filenames)
5723 filename_to_utf16 (filename, filename_w);
5724 attrs = GetFileAttributesW (filename_w);
5726 else
5728 filename_to_ansi (filename, filename_a);
5729 attrs = GetFileAttributesA (filename_a);
5731 if (attrs == -1)
5733 DWORD w32err = GetLastError ();
5735 switch (w32err)
5737 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5738 break;
5739 case ERROR_ACCESS_DENIED:
5740 errno = EACCES;
5741 break;
5742 case ERROR_FILE_NOT_FOUND:
5743 case ERROR_PATH_NOT_FOUND:
5744 default:
5745 errno = ENOENT;
5746 break;
5748 return 0;
5750 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5751 return 0;
5752 logon_network_drive (filename);
5753 if (w32_unicode_filenames)
5755 fh = FindFirstFileW (filename_w, &wfdw);
5756 attrs_mean_symlink =
5757 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5758 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5759 if (attrs_mean_symlink)
5760 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5762 else if (_mbspbrk (filename_a, "?"))
5764 /* filename_to_ansi failed to convert the file name. */
5765 errno = ENOENT;
5766 return 0;
5768 else
5770 fh = FindFirstFileA (filename_a, &wfda);
5771 attrs_mean_symlink =
5772 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5773 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5774 if (attrs_mean_symlink)
5775 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5777 if (fh == INVALID_HANDLE_VALUE)
5778 return 0;
5779 FindClose (fh);
5780 return attrs_mean_symlink;
5783 /* If NAME identifies a symbolic link, copy into BUF the file name of
5784 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5785 null-terminate the target name, even if it fits. Return the number
5786 of bytes copied, or -1 if NAME is not a symlink or any error was
5787 encountered while resolving it. The file name copied into BUF is
5788 encoded in the current ANSI codepage. */
5789 ssize_t
5790 readlink (const char *name, char *buf, size_t buf_size)
5792 const char *path;
5793 TOKEN_PRIVILEGES privs;
5794 int restore_privs = 0;
5795 HANDLE sh;
5796 ssize_t retval;
5797 char resolved[MAX_UTF8_PATH];
5799 if (name == NULL)
5801 errno = EFAULT;
5802 return -1;
5804 if (!*name)
5806 errno = ENOENT;
5807 return -1;
5810 path = map_w32_filename (name, NULL);
5812 if (strlen (path) > MAX_UTF8_PATH)
5814 errno = ENAMETOOLONG;
5815 return -1;
5818 errno = 0;
5819 if (is_windows_9x () == TRUE
5820 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5821 || !is_symlink (path))
5823 if (!errno)
5824 errno = EINVAL; /* not a symlink */
5825 return -1;
5828 /* Done with simple tests, now we're in for some _real_ work. */
5829 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5830 restore_privs = 1;
5831 /* Implementation note: From here and onward, don't return early,
5832 since that will fail to restore the original set of privileges of
5833 the calling thread. */
5835 retval = -1; /* not too optimistic, are we? */
5837 /* Note: In the next call to CreateFile, we use zero as the 2nd
5838 argument because, when the symlink is a hidden/system file,
5839 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5840 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5841 and directory symlinks. */
5842 if (w32_unicode_filenames)
5844 wchar_t path_w[MAX_PATH];
5846 filename_to_utf16 (path, path_w);
5847 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5848 FILE_FLAG_OPEN_REPARSE_POINT
5849 | FILE_FLAG_BACKUP_SEMANTICS,
5850 NULL);
5852 else
5854 char path_a[MAX_PATH];
5856 filename_to_ansi (path, path_a);
5857 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5858 FILE_FLAG_OPEN_REPARSE_POINT
5859 | FILE_FLAG_BACKUP_SEMANTICS,
5860 NULL);
5862 if (sh != INVALID_HANDLE_VALUE)
5864 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5865 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5866 DWORD retbytes;
5868 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5869 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5870 &retbytes, NULL))
5871 errno = EIO;
5872 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5873 errno = EINVAL;
5874 else
5876 /* Copy the link target name, in wide characters, from
5877 reparse_data, then convert it to multibyte encoding in
5878 the current locale's codepage. */
5879 WCHAR *lwname;
5880 size_t lname_size;
5881 USHORT lwname_len =
5882 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5883 WCHAR *lwname_src =
5884 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5885 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5886 size_t size_to_copy = buf_size;
5888 /* According to MSDN, PrintNameLength does not include the
5889 terminating null character. */
5890 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5891 memcpy (lwname, lwname_src, lwname_len);
5892 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5893 filename_from_utf16 (lwname, resolved);
5894 dostounix_filename (resolved);
5895 lname_size = strlen (resolved) + 1;
5896 if (lname_size <= buf_size)
5897 size_to_copy = lname_size;
5898 strncpy (buf, resolved, size_to_copy);
5899 /* Success! */
5900 retval = size_to_copy;
5902 CloseHandle (sh);
5904 else
5906 /* CreateFile failed. */
5907 DWORD w32err2 = GetLastError ();
5909 switch (w32err2)
5911 case ERROR_FILE_NOT_FOUND:
5912 case ERROR_PATH_NOT_FOUND:
5913 errno = ENOENT;
5914 break;
5915 case ERROR_ACCESS_DENIED:
5916 case ERROR_TOO_MANY_OPEN_FILES:
5917 errno = EACCES;
5918 break;
5919 default:
5920 errno = EPERM;
5921 break;
5924 if (restore_privs)
5926 restore_privilege (&privs);
5927 revert_to_self ();
5930 return retval;
5933 ssize_t
5934 readlinkat (int fd, char const *name, char *buffer,
5935 size_t buffer_size)
5937 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5938 as in fstatat. FIXME: Add proper support for readlinkat. */
5939 char fullname[MAX_UTF8_PATH];
5941 if (fd != AT_FDCWD)
5943 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5944 < 0)
5946 errno = ENAMETOOLONG;
5947 return -1;
5949 name = fullname;
5952 return readlink (name, buffer, buffer_size);
5955 /* If FILE is a symlink, return its target (stored in a static
5956 buffer); otherwise return FILE.
5958 This function repeatedly resolves symlinks in the last component of
5959 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5960 until it arrives at a file whose last component is not a symlink,
5961 or some error occurs. It returns the target of the last
5962 successfully resolved symlink in the chain. If it succeeds to
5963 resolve even a single symlink, the value returned is an absolute
5964 file name with backslashes (result of GetFullPathName). By
5965 contrast, if the original FILE is returned, it is unaltered.
5967 Note: This function can set errno even if it succeeds.
5969 Implementation note: we only resolve the last portion ("basename")
5970 of the argument FILE and of each following file in the chain,
5971 disregarding any possible symlinks in its leading directories.
5972 This is because Windows system calls and library functions
5973 transparently resolve symlinks in leading directories and return
5974 correct information, as long as the basename is not a symlink. */
5975 static char *
5976 chase_symlinks (const char *file)
5978 static char target[MAX_UTF8_PATH];
5979 char link[MAX_UTF8_PATH];
5980 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5981 char target_a[MAX_PATH], link_a[MAX_PATH];
5982 ssize_t res, link_len;
5983 int loop_count = 0;
5985 if (is_windows_9x () == TRUE || !is_symlink (file))
5986 return (char *)file;
5988 if (w32_unicode_filenames)
5990 wchar_t file_w[MAX_PATH];
5992 filename_to_utf16 (file, file_w);
5993 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5994 return (char *)file;
5995 filename_from_utf16 (link_w, link);
5997 else
5999 char file_a[MAX_PATH];
6001 filename_to_ansi (file, file_a);
6002 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6003 return (char *)file;
6004 filename_from_ansi (link_a, link);
6006 link_len = strlen (link);
6008 target[0] = '\0';
6009 do {
6011 /* Remove trailing slashes, as we want to resolve the last
6012 non-trivial part of the link name. */
6013 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6014 link[link_len--] = '\0';
6016 res = readlink (link, target, MAX_UTF8_PATH);
6017 if (res > 0)
6019 target[res] = '\0';
6020 if (!(IS_DEVICE_SEP (target[1])
6021 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6023 /* Target is relative. Append it to the directory part of
6024 the symlink, then copy the result back to target. */
6025 char *p = link + link_len;
6027 while (p > link && !IS_ANY_SEP (p[-1]))
6028 p--;
6029 strcpy (p, target);
6030 strcpy (target, link);
6032 /* Resolve any "." and ".." to get a fully-qualified file name
6033 in link[] again. */
6034 if (w32_unicode_filenames)
6036 filename_to_utf16 (target, target_w);
6037 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6038 if (link_len > 0)
6039 filename_from_utf16 (link_w, link);
6041 else
6043 filename_to_ansi (target, target_a);
6044 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6045 if (link_len > 0)
6046 filename_from_ansi (link_a, link);
6048 link_len = strlen (link);
6050 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6052 if (loop_count > 100)
6053 errno = ELOOP;
6055 if (target[0] == '\0') /* not a single call to readlink succeeded */
6056 return (char *)file;
6057 return target;
6061 /* Posix ACL emulation. */
6064 acl_valid (acl_t acl)
6066 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6069 char *
6070 acl_to_text (acl_t acl, ssize_t *size)
6072 LPTSTR str_acl;
6073 SECURITY_INFORMATION flags =
6074 OWNER_SECURITY_INFORMATION |
6075 GROUP_SECURITY_INFORMATION |
6076 DACL_SECURITY_INFORMATION;
6077 char *retval = NULL;
6078 ULONG local_size;
6079 int e = errno;
6081 errno = 0;
6083 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6085 errno = e;
6086 /* We don't want to mix heaps, so we duplicate the string in our
6087 heap and free the one allocated by the API. */
6088 retval = xstrdup (str_acl);
6089 if (size)
6090 *size = local_size;
6091 LocalFree (str_acl);
6093 else if (errno != ENOTSUP)
6094 errno = EINVAL;
6096 return retval;
6099 acl_t
6100 acl_from_text (const char *acl_str)
6102 PSECURITY_DESCRIPTOR psd, retval = NULL;
6103 ULONG sd_size;
6104 int e = errno;
6106 errno = 0;
6108 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6110 errno = e;
6111 retval = xmalloc (sd_size);
6112 memcpy (retval, psd, sd_size);
6113 LocalFree (psd);
6115 else if (errno != ENOTSUP)
6116 errno = EINVAL;
6118 return retval;
6122 acl_free (void *ptr)
6124 xfree (ptr);
6125 return 0;
6128 acl_t
6129 acl_get_file (const char *fname, acl_type_t type)
6131 PSECURITY_DESCRIPTOR psd = NULL;
6132 const char *filename;
6134 if (type == ACL_TYPE_ACCESS)
6136 DWORD sd_len, err;
6137 SECURITY_INFORMATION si =
6138 OWNER_SECURITY_INFORMATION |
6139 GROUP_SECURITY_INFORMATION |
6140 DACL_SECURITY_INFORMATION ;
6141 int e = errno;
6143 filename = map_w32_filename (fname, NULL);
6144 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6145 fname = chase_symlinks (filename);
6146 else
6147 fname = filename;
6149 errno = 0;
6150 if (!get_file_security (fname, si, psd, 0, &sd_len)
6151 && errno != ENOTSUP)
6153 err = GetLastError ();
6154 if (err == ERROR_INSUFFICIENT_BUFFER)
6156 psd = xmalloc (sd_len);
6157 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6159 xfree (psd);
6160 errno = EIO;
6161 psd = NULL;
6164 else if (err == ERROR_FILE_NOT_FOUND
6165 || err == ERROR_PATH_NOT_FOUND
6166 /* ERROR_INVALID_NAME is what we get if
6167 w32-unicode-filenames is nil and the file cannot
6168 be encoded in the current ANSI codepage. */
6169 || err == ERROR_INVALID_NAME)
6170 errno = ENOENT;
6171 else
6172 errno = EIO;
6174 else if (!errno)
6175 errno = e;
6177 else if (type != ACL_TYPE_DEFAULT)
6178 errno = EINVAL;
6180 return psd;
6184 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6186 TOKEN_PRIVILEGES old1, old2;
6187 DWORD err;
6188 int st = 0, retval = -1;
6189 SECURITY_INFORMATION flags = 0;
6190 PSID psidOwner, psidGroup;
6191 PACL pacl;
6192 BOOL dflt;
6193 BOOL dacl_present;
6194 int e;
6195 const char *filename;
6197 if (acl_valid (acl) != 0
6198 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6200 errno = EINVAL;
6201 return -1;
6204 if (type == ACL_TYPE_DEFAULT)
6206 errno = ENOSYS;
6207 return -1;
6210 filename = map_w32_filename (fname, NULL);
6211 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6212 fname = chase_symlinks (filename);
6213 else
6214 fname = filename;
6216 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6217 &dflt)
6218 && psidOwner)
6219 flags |= OWNER_SECURITY_INFORMATION;
6220 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6221 &dflt)
6222 && psidGroup)
6223 flags |= GROUP_SECURITY_INFORMATION;
6224 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6225 &pacl, &dflt)
6226 && dacl_present)
6227 flags |= DACL_SECURITY_INFORMATION;
6228 if (!flags)
6229 return 0;
6231 /* According to KB-245153, setting the owner will succeed if either:
6232 (1) the caller is the user who will be the new owner, and has the
6233 SE_TAKE_OWNERSHIP privilege, or
6234 (2) the caller has the SE_RESTORE privilege, in which case she can
6235 set any valid user or group as the owner
6237 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6238 privileges, and disregard any failures in obtaining them. If
6239 these privileges cannot be obtained, and do not already exist in
6240 the calling thread's security token, this function could fail
6241 with EPERM. */
6242 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6243 st++;
6244 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6245 st++;
6247 e = errno;
6248 errno = 0;
6249 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6250 DACL inheritance is involved, but it seems to preserve ownership
6251 better than SetNamedSecurityInfo, which is important e.g., in
6252 copy-file. */
6253 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6255 err = GetLastError ();
6257 if (errno != ENOTSUP)
6258 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6259 psidOwner, psidGroup, pacl, NULL);
6261 else
6262 err = ERROR_SUCCESS;
6263 if (err != ERROR_SUCCESS)
6265 if (errno == ENOTSUP)
6267 else if (err == ERROR_INVALID_OWNER
6268 || err == ERROR_NOT_ALL_ASSIGNED
6269 || err == ERROR_ACCESS_DENIED)
6271 /* Maybe the requested ACL and the one the file already has
6272 are identical, in which case we can silently ignore the
6273 failure. (And no, Windows doesn't.) */
6274 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6276 errno = EPERM;
6277 if (current_acl)
6279 char *acl_from = acl_to_text (current_acl, NULL);
6280 char *acl_to = acl_to_text (acl, NULL);
6282 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6284 retval = 0;
6285 errno = e;
6287 if (acl_from)
6288 acl_free (acl_from);
6289 if (acl_to)
6290 acl_free (acl_to);
6291 acl_free (current_acl);
6294 else if (err == ERROR_FILE_NOT_FOUND
6295 || err == ERROR_PATH_NOT_FOUND
6296 /* ERROR_INVALID_NAME is what we get if
6297 w32-unicode-filenames is nil and the file cannot be
6298 encoded in the current ANSI codepage. */
6299 || err == ERROR_INVALID_NAME)
6300 errno = ENOENT;
6301 else
6302 errno = EACCES;
6304 else
6306 retval = 0;
6307 errno = e;
6310 if (st)
6312 if (st >= 2)
6313 restore_privilege (&old2);
6314 restore_privilege (&old1);
6315 revert_to_self ();
6318 return retval;
6322 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6323 have a fixed max size for file names, so we don't need the kind of
6324 alloc/malloc/realloc dance the gnulib version does. We also don't
6325 support FD-relative symlinks. */
6326 char *
6327 careadlinkat (int fd, char const *filename,
6328 char *buffer, size_t buffer_size,
6329 struct allocator const *alloc,
6330 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6332 char linkname[MAX_UTF8_PATH];
6333 ssize_t link_size;
6335 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6337 if (link_size > 0)
6339 char *retval = buffer;
6341 linkname[link_size++] = '\0';
6342 if (link_size > buffer_size)
6343 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6344 if (retval)
6345 memcpy (retval, linkname, link_size);
6347 return retval;
6349 return NULL;
6353 w32_copy_file (const char *from, const char *to,
6354 int keep_time, int preserve_ownership, int copy_acls)
6356 acl_t acl = NULL;
6357 BOOL copy_result;
6358 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6359 char from_a[MAX_PATH], to_a[MAX_PATH];
6361 /* We ignore preserve_ownership for now. */
6362 preserve_ownership = preserve_ownership;
6364 if (copy_acls)
6366 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6367 if (acl == NULL && acl_errno_valid (errno))
6368 return -2;
6370 if (w32_unicode_filenames)
6372 filename_to_utf16 (from, from_w);
6373 filename_to_utf16 (to, to_w);
6374 copy_result = CopyFileW (from_w, to_w, FALSE);
6376 else
6378 filename_to_ansi (from, from_a);
6379 filename_to_ansi (to, to_a);
6380 copy_result = CopyFileA (from_a, to_a, FALSE);
6382 if (!copy_result)
6384 /* CopyFile doesn't set errno when it fails. By far the most
6385 "popular" reason is that the target is read-only. */
6386 DWORD err = GetLastError ();
6388 switch (err)
6390 case ERROR_FILE_NOT_FOUND:
6391 errno = ENOENT;
6392 break;
6393 case ERROR_ACCESS_DENIED:
6394 errno = EACCES;
6395 break;
6396 case ERROR_ENCRYPTION_FAILED:
6397 errno = EIO;
6398 break;
6399 default:
6400 errno = EPERM;
6401 break;
6404 if (acl)
6405 acl_free (acl);
6406 return -1;
6408 /* CopyFile retains the timestamp by default. However, see
6409 "Community Additions" for CopyFile: it sounds like that is not
6410 entirely true. Testing on Windows XP confirms that modified time
6411 is copied, but creation and last-access times are not.
6412 FIXME? */
6413 else if (!keep_time)
6415 struct timespec now;
6416 DWORD attributes;
6418 if (w32_unicode_filenames)
6420 /* Ensure file is writable while its times are set. */
6421 attributes = GetFileAttributesW (to_w);
6422 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6423 now = current_timespec ();
6424 if (set_file_times (-1, to, now, now))
6426 /* Restore original attributes. */
6427 SetFileAttributesW (to_w, attributes);
6428 if (acl)
6429 acl_free (acl);
6430 return -3;
6432 /* Restore original attributes. */
6433 SetFileAttributesW (to_w, attributes);
6435 else
6437 attributes = GetFileAttributesA (to_a);
6438 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6439 now = current_timespec ();
6440 if (set_file_times (-1, to, now, now))
6442 SetFileAttributesA (to_a, attributes);
6443 if (acl)
6444 acl_free (acl);
6445 return -3;
6447 SetFileAttributesA (to_a, attributes);
6450 if (acl != NULL)
6452 bool fail =
6453 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6454 acl_free (acl);
6455 if (fail && acl_errno_valid (errno))
6456 return -4;
6459 return 0;
6463 /* Support for browsing other processes and their attributes. See
6464 process.c for the Lisp bindings. */
6466 /* Helper wrapper functions. */
6468 static HANDLE WINAPI
6469 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6471 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6473 if (g_b_init_create_toolhelp32_snapshot == 0)
6475 g_b_init_create_toolhelp32_snapshot = 1;
6476 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6477 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6478 "CreateToolhelp32Snapshot");
6480 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6482 return INVALID_HANDLE_VALUE;
6484 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6487 static BOOL WINAPI
6488 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6490 static Process32First_Proc s_pfn_Process32_First = NULL;
6492 if (g_b_init_process32_first == 0)
6494 g_b_init_process32_first = 1;
6495 s_pfn_Process32_First = (Process32First_Proc)
6496 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6497 "Process32First");
6499 if (s_pfn_Process32_First == NULL)
6501 return FALSE;
6503 return (s_pfn_Process32_First (hSnapshot, lppe));
6506 static BOOL WINAPI
6507 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6509 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6511 if (g_b_init_process32_next == 0)
6513 g_b_init_process32_next = 1;
6514 s_pfn_Process32_Next = (Process32Next_Proc)
6515 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6516 "Process32Next");
6518 if (s_pfn_Process32_Next == NULL)
6520 return FALSE;
6522 return (s_pfn_Process32_Next (hSnapshot, lppe));
6525 static BOOL WINAPI
6526 open_thread_token (HANDLE ThreadHandle,
6527 DWORD DesiredAccess,
6528 BOOL OpenAsSelf,
6529 PHANDLE TokenHandle)
6531 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6532 HMODULE hm_advapi32 = NULL;
6533 if (is_windows_9x () == TRUE)
6535 SetLastError (ERROR_NOT_SUPPORTED);
6536 return FALSE;
6538 if (g_b_init_open_thread_token == 0)
6540 g_b_init_open_thread_token = 1;
6541 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6542 s_pfn_Open_Thread_Token =
6543 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6545 if (s_pfn_Open_Thread_Token == NULL)
6547 SetLastError (ERROR_NOT_SUPPORTED);
6548 return FALSE;
6550 return (
6551 s_pfn_Open_Thread_Token (
6552 ThreadHandle,
6553 DesiredAccess,
6554 OpenAsSelf,
6555 TokenHandle)
6559 static BOOL WINAPI
6560 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6562 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6563 HMODULE hm_advapi32 = NULL;
6564 if (is_windows_9x () == TRUE)
6566 return FALSE;
6568 if (g_b_init_impersonate_self == 0)
6570 g_b_init_impersonate_self = 1;
6571 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6572 s_pfn_Impersonate_Self =
6573 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6575 if (s_pfn_Impersonate_Self == NULL)
6577 return FALSE;
6579 return s_pfn_Impersonate_Self (ImpersonationLevel);
6582 static BOOL WINAPI
6583 revert_to_self (void)
6585 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6586 HMODULE hm_advapi32 = NULL;
6587 if (is_windows_9x () == TRUE)
6589 return FALSE;
6591 if (g_b_init_revert_to_self == 0)
6593 g_b_init_revert_to_self = 1;
6594 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6595 s_pfn_Revert_To_Self =
6596 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6598 if (s_pfn_Revert_To_Self == NULL)
6600 return FALSE;
6602 return s_pfn_Revert_To_Self ();
6605 static BOOL WINAPI
6606 get_process_memory_info (HANDLE h_proc,
6607 PPROCESS_MEMORY_COUNTERS mem_counters,
6608 DWORD bufsize)
6610 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6611 HMODULE hm_psapi = NULL;
6612 if (is_windows_9x () == TRUE)
6614 return FALSE;
6616 if (g_b_init_get_process_memory_info == 0)
6618 g_b_init_get_process_memory_info = 1;
6619 hm_psapi = LoadLibrary ("Psapi.dll");
6620 if (hm_psapi)
6621 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6622 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6624 if (s_pfn_Get_Process_Memory_Info == NULL)
6626 return FALSE;
6628 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6631 static BOOL WINAPI
6632 get_process_working_set_size (HANDLE h_proc,
6633 PSIZE_T minrss,
6634 PSIZE_T maxrss)
6636 static GetProcessWorkingSetSize_Proc
6637 s_pfn_Get_Process_Working_Set_Size = NULL;
6639 if (is_windows_9x () == TRUE)
6641 return FALSE;
6643 if (g_b_init_get_process_working_set_size == 0)
6645 g_b_init_get_process_working_set_size = 1;
6646 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6647 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6648 "GetProcessWorkingSetSize");
6650 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6652 return FALSE;
6654 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6657 static BOOL WINAPI
6658 global_memory_status (MEMORYSTATUS *buf)
6660 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6662 if (is_windows_9x () == TRUE)
6664 return FALSE;
6666 if (g_b_init_global_memory_status == 0)
6668 g_b_init_global_memory_status = 1;
6669 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6670 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6671 "GlobalMemoryStatus");
6673 if (s_pfn_Global_Memory_Status == NULL)
6675 return FALSE;
6677 return s_pfn_Global_Memory_Status (buf);
6680 static BOOL WINAPI
6681 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6683 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6685 if (is_windows_9x () == TRUE)
6687 return FALSE;
6689 if (g_b_init_global_memory_status_ex == 0)
6691 g_b_init_global_memory_status_ex = 1;
6692 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6693 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6694 "GlobalMemoryStatusEx");
6696 if (s_pfn_Global_Memory_Status_Ex == NULL)
6698 return FALSE;
6700 return s_pfn_Global_Memory_Status_Ex (buf);
6703 Lisp_Object
6704 list_system_processes (void)
6706 Lisp_Object proclist = Qnil;
6707 HANDLE h_snapshot;
6709 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6711 if (h_snapshot != INVALID_HANDLE_VALUE)
6713 PROCESSENTRY32 proc_entry;
6714 DWORD proc_id;
6715 BOOL res;
6717 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6718 for (res = process32_first (h_snapshot, &proc_entry); res;
6719 res = process32_next (h_snapshot, &proc_entry))
6721 proc_id = proc_entry.th32ProcessID;
6722 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6725 CloseHandle (h_snapshot);
6726 proclist = Fnreverse (proclist);
6729 return proclist;
6732 static int
6733 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6735 TOKEN_PRIVILEGES priv;
6736 DWORD priv_size = sizeof (priv);
6737 DWORD opriv_size = sizeof (*old_priv);
6738 HANDLE h_token = NULL;
6739 HANDLE h_thread = GetCurrentThread ();
6740 int ret_val = 0;
6741 BOOL res;
6743 res = open_thread_token (h_thread,
6744 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6745 FALSE, &h_token);
6746 if (!res && GetLastError () == ERROR_NO_TOKEN)
6748 if (impersonate_self (SecurityImpersonation))
6749 res = open_thread_token (h_thread,
6750 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6751 FALSE, &h_token);
6753 if (res)
6755 priv.PrivilegeCount = 1;
6756 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6757 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6758 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6759 old_priv, &opriv_size)
6760 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6761 ret_val = 1;
6763 if (h_token)
6764 CloseHandle (h_token);
6766 return ret_val;
6769 static int
6770 restore_privilege (TOKEN_PRIVILEGES *priv)
6772 DWORD priv_size = sizeof (*priv);
6773 HANDLE h_token = NULL;
6774 int ret_val = 0;
6776 if (open_thread_token (GetCurrentThread (),
6777 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6778 FALSE, &h_token))
6780 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6781 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6782 ret_val = 1;
6784 if (h_token)
6785 CloseHandle (h_token);
6787 return ret_val;
6790 static Lisp_Object
6791 ltime (ULONGLONG time_100ns)
6793 ULONGLONG time_sec = time_100ns / 10000000;
6794 int subsec = time_100ns % 10000000;
6795 return list4i (time_sec >> 16, time_sec & 0xffff,
6796 subsec / 10, subsec % 10 * 100000);
6799 #define U64_TO_LISP_TIME(time) ltime (time)
6801 static int
6802 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6803 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6804 double *pcpu)
6806 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6807 ULONGLONG tem1, tem2, tem3, tem;
6809 if (!h_proc
6810 || !get_process_times_fn
6811 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6812 &ft_kernel, &ft_user))
6813 return 0;
6815 GetSystemTimeAsFileTime (&ft_current);
6817 FILETIME_TO_U64 (tem1, ft_kernel);
6818 *stime = U64_TO_LISP_TIME (tem1);
6820 FILETIME_TO_U64 (tem2, ft_user);
6821 *utime = U64_TO_LISP_TIME (tem2);
6823 tem3 = tem1 + tem2;
6824 *ttime = U64_TO_LISP_TIME (tem3);
6826 FILETIME_TO_U64 (tem, ft_creation);
6827 /* Process no 4 (System) returns zero creation time. */
6828 if (tem)
6829 tem -= utc_base;
6830 *ctime = U64_TO_LISP_TIME (tem);
6832 if (tem)
6834 FILETIME_TO_U64 (tem3, ft_current);
6835 tem = (tem3 - utc_base) - tem;
6837 *etime = U64_TO_LISP_TIME (tem);
6839 if (tem)
6841 *pcpu = 100.0 * (tem1 + tem2) / tem;
6842 if (*pcpu > 100)
6843 *pcpu = 100.0;
6845 else
6846 *pcpu = 0;
6848 return 1;
6851 Lisp_Object
6852 system_process_attributes (Lisp_Object pid)
6854 Lisp_Object attrs = Qnil;
6855 Lisp_Object cmd_str, decoded_cmd, tem;
6856 HANDLE h_snapshot, h_proc;
6857 DWORD proc_id;
6858 int found_proc = 0;
6859 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6860 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6861 DWORD glength = sizeof (gname);
6862 HANDLE token = NULL;
6863 SID_NAME_USE user_type;
6864 unsigned char *buf = NULL;
6865 DWORD blen = 0;
6866 TOKEN_USER user_token;
6867 TOKEN_PRIMARY_GROUP group_token;
6868 unsigned euid;
6869 unsigned egid;
6870 PROCESS_MEMORY_COUNTERS mem;
6871 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6872 SIZE_T minrss, maxrss;
6873 MEMORYSTATUS memst;
6874 MEMORY_STATUS_EX memstex;
6875 double totphys = 0.0;
6876 Lisp_Object ctime, stime, utime, etime, ttime;
6877 double pcpu;
6878 BOOL result = FALSE;
6880 CHECK_NUMBER_OR_FLOAT (pid);
6881 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6883 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6885 if (h_snapshot != INVALID_HANDLE_VALUE)
6887 PROCESSENTRY32 pe;
6888 BOOL res;
6890 pe.dwSize = sizeof (PROCESSENTRY32);
6891 for (res = process32_first (h_snapshot, &pe); res;
6892 res = process32_next (h_snapshot, &pe))
6894 if (proc_id == pe.th32ProcessID)
6896 if (proc_id == 0)
6897 decoded_cmd = build_string ("Idle");
6898 else
6900 /* Decode the command name from locale-specific
6901 encoding. */
6902 cmd_str = build_unibyte_string (pe.szExeFile);
6904 decoded_cmd =
6905 code_convert_string_norecord (cmd_str,
6906 Vlocale_coding_system, 0);
6908 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6909 attrs = Fcons (Fcons (Qppid,
6910 make_fixnum_or_float (pe.th32ParentProcessID)),
6911 attrs);
6912 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6913 attrs);
6914 attrs = Fcons (Fcons (Qthcount,
6915 make_fixnum_or_float (pe.cntThreads)),
6916 attrs);
6917 found_proc = 1;
6918 break;
6922 CloseHandle (h_snapshot);
6925 if (!found_proc)
6926 return Qnil;
6928 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6929 FALSE, proc_id);
6930 /* If we were denied a handle to the process, try again after
6931 enabling the SeDebugPrivilege in our process. */
6932 if (!h_proc)
6934 TOKEN_PRIVILEGES priv_current;
6936 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6938 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6939 FALSE, proc_id);
6940 restore_privilege (&priv_current);
6941 revert_to_self ();
6944 if (h_proc)
6946 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6947 if (result)
6949 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6950 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6952 buf = xmalloc (blen);
6953 result = get_token_information (token, TokenUser,
6954 (LPVOID)buf, blen, &needed);
6955 if (result)
6957 memcpy (&user_token, buf, sizeof (user_token));
6958 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6960 euid = get_rid (user_token.User.Sid);
6961 result = lookup_account_sid (NULL, user_token.User.Sid,
6962 uname, &ulength,
6963 domain, &dlength,
6964 &user_type);
6965 if (result)
6966 w32_add_to_cache (user_token.User.Sid, euid, uname);
6967 else
6969 strcpy (uname, "unknown");
6970 result = TRUE;
6973 ulength = strlen (uname);
6977 if (result)
6979 /* Determine a reasonable euid and gid values. */
6980 if (xstrcasecmp ("administrator", uname) == 0)
6982 euid = 500; /* well-known Administrator uid */
6983 egid = 513; /* well-known None gid */
6985 else
6987 /* Get group id and name. */
6988 result = get_token_information (token, TokenPrimaryGroup,
6989 (LPVOID)buf, blen, &needed);
6990 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6992 buf = xrealloc (buf, blen = needed);
6993 result = get_token_information (token, TokenPrimaryGroup,
6994 (LPVOID)buf, blen, &needed);
6996 if (result)
6998 memcpy (&group_token, buf, sizeof (group_token));
6999 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7001 egid = get_rid (group_token.PrimaryGroup);
7002 dlength = sizeof (domain);
7003 result =
7004 lookup_account_sid (NULL, group_token.PrimaryGroup,
7005 gname, &glength, NULL, &dlength,
7006 &user_type);
7007 if (result)
7008 w32_add_to_cache (group_token.PrimaryGroup,
7009 egid, gname);
7010 else
7012 strcpy (gname, "None");
7013 result = TRUE;
7016 glength = strlen (gname);
7020 xfree (buf);
7022 if (!result)
7024 if (!is_windows_9x ())
7026 /* We couldn't open the process token, presumably because of
7027 insufficient access rights. Assume this process is run
7028 by the system. */
7029 strcpy (uname, "SYSTEM");
7030 strcpy (gname, "None");
7031 euid = 18; /* SYSTEM */
7032 egid = 513; /* None */
7033 glength = strlen (gname);
7034 ulength = strlen (uname);
7036 /* If we are running under Windows 9X, where security calls are
7037 not supported, we assume all processes are run by the current
7038 user. */
7039 else if (GetUserName (uname, &ulength))
7041 if (xstrcasecmp ("administrator", uname) == 0)
7042 euid = 0;
7043 else
7044 euid = 123;
7045 egid = euid;
7046 strcpy (gname, "None");
7047 glength = strlen (gname);
7048 ulength = strlen (uname);
7050 else
7052 euid = 123;
7053 egid = 123;
7054 strcpy (uname, "administrator");
7055 ulength = strlen (uname);
7056 strcpy (gname, "None");
7057 glength = strlen (gname);
7059 if (token)
7060 CloseHandle (token);
7063 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7064 tem = make_unibyte_string (uname, ulength);
7065 attrs = Fcons (Fcons (Quser,
7066 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7067 attrs);
7068 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7069 tem = make_unibyte_string (gname, glength);
7070 attrs = Fcons (Fcons (Qgroup,
7071 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7072 attrs);
7074 if (global_memory_status_ex (&memstex))
7075 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7076 totphys = memstex.ullTotalPhys / 1024.0;
7077 #else
7078 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7079 double, so we need to do this for it... */
7081 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7082 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7083 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7085 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7087 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7088 else if (global_memory_status (&memst))
7089 totphys = memst.dwTotalPhys / 1024.0;
7091 if (h_proc
7092 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7093 sizeof (mem_ex)))
7095 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7097 attrs = Fcons (Fcons (Qmajflt,
7098 make_fixnum_or_float (mem_ex.PageFaultCount)),
7099 attrs);
7100 attrs = Fcons (Fcons (Qvsize,
7101 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7102 attrs);
7103 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7104 if (totphys)
7105 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7107 else if (h_proc
7108 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7110 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7112 attrs = Fcons (Fcons (Qmajflt,
7113 make_fixnum_or_float (mem.PageFaultCount)),
7114 attrs);
7115 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7116 if (totphys)
7117 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7119 else if (h_proc
7120 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7122 DWORD rss = maxrss / 1024;
7124 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7125 if (totphys)
7126 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7129 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7131 attrs = Fcons (Fcons (Qutime, utime), attrs);
7132 attrs = Fcons (Fcons (Qstime, stime), attrs);
7133 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7134 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7135 attrs = Fcons (Fcons (Qetime, etime), attrs);
7136 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7139 /* FIXME: Retrieve command line by walking the PEB of the process. */
7141 if (h_proc)
7142 CloseHandle (h_proc);
7143 return attrs;
7147 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7148 unsigned long long *totalswap, unsigned long long *freeswap)
7150 MEMORYSTATUS memst;
7151 MEMORY_STATUS_EX memstex;
7153 /* Use GlobalMemoryStatusEx if available, as it can report more than
7154 2GB of memory. */
7155 if (global_memory_status_ex (&memstex))
7157 *totalram = memstex.ullTotalPhys;
7158 *freeram = memstex.ullAvailPhys;
7159 *totalswap = memstex.ullTotalPageFile;
7160 *freeswap = memstex.ullAvailPageFile;
7161 return 0;
7163 else if (global_memory_status (&memst))
7165 *totalram = memst.dwTotalPhys;
7166 *freeram = memst.dwAvailPhys;
7167 *totalswap = memst.dwTotalPageFile;
7168 *freeswap = memst.dwAvailPageFile;
7169 return 0;
7171 else
7172 return -1;
7176 /* Wrappers for winsock functions to map between our file descriptors
7177 and winsock's handles; also set h_errno for convenience.
7179 To allow Emacs to run on systems which don't have winsock support
7180 installed, we dynamically link to winsock on startup if present, and
7181 otherwise provide the minimum necessary functionality
7182 (eg. gethostname). */
7184 /* function pointers for relevant socket functions */
7185 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7186 void (PASCAL *pfn_WSASetLastError) (int iError);
7187 int (PASCAL *pfn_WSAGetLastError) (void);
7188 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7189 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7190 WSANETWORKEVENTS *NetworkEvents);
7192 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7193 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7194 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7195 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7196 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7197 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7198 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7199 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7200 int (PASCAL *pfn_closesocket) (SOCKET s);
7201 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7202 int (PASCAL *pfn_WSACleanup) (void);
7204 u_short (PASCAL *pfn_htons) (u_short hostshort);
7205 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7206 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7207 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7208 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7209 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7210 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7211 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7212 const char * optval, int optlen);
7213 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7214 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7215 int * namelen);
7216 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7217 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7218 struct sockaddr * from, int * fromlen);
7219 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7220 const struct sockaddr * to, int tolen);
7222 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7223 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7224 #ifndef HANDLE_FLAG_INHERIT
7225 #define HANDLE_FLAG_INHERIT 1
7226 #endif
7228 HANDLE winsock_lib;
7229 static int winsock_inuse;
7231 BOOL
7232 term_winsock (void)
7234 if (winsock_lib != NULL && winsock_inuse == 0)
7236 release_listen_threads ();
7237 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7238 after WSAStartup returns successfully, but it seems reasonable
7239 to allow unloading winsock anyway in that case. */
7240 if (pfn_WSACleanup () == 0 ||
7241 pfn_WSAGetLastError () == WSAENETDOWN)
7243 if (FreeLibrary (winsock_lib))
7244 winsock_lib = NULL;
7245 return TRUE;
7248 return FALSE;
7251 BOOL
7252 init_winsock (int load_now)
7254 WSADATA winsockData;
7256 if (winsock_lib != NULL)
7257 return TRUE;
7259 pfn_SetHandleInformation
7260 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7261 "SetHandleInformation");
7263 winsock_lib = LoadLibrary ("Ws2_32.dll");
7265 if (winsock_lib != NULL)
7267 /* dynamically link to socket functions */
7269 #define LOAD_PROC(fn) \
7270 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7271 goto fail;
7273 LOAD_PROC (WSAStartup);
7274 LOAD_PROC (WSASetLastError);
7275 LOAD_PROC (WSAGetLastError);
7276 LOAD_PROC (WSAEventSelect);
7277 LOAD_PROC (WSAEnumNetworkEvents);
7278 LOAD_PROC (WSACreateEvent);
7279 LOAD_PROC (WSACloseEvent);
7280 LOAD_PROC (socket);
7281 LOAD_PROC (bind);
7282 LOAD_PROC (connect);
7283 LOAD_PROC (ioctlsocket);
7284 LOAD_PROC (recv);
7285 LOAD_PROC (send);
7286 LOAD_PROC (closesocket);
7287 LOAD_PROC (shutdown);
7288 LOAD_PROC (htons);
7289 LOAD_PROC (ntohs);
7290 LOAD_PROC (inet_addr);
7291 LOAD_PROC (gethostname);
7292 LOAD_PROC (gethostbyname);
7293 LOAD_PROC (getservbyname);
7294 LOAD_PROC (getpeername);
7295 LOAD_PROC (WSACleanup);
7296 LOAD_PROC (setsockopt);
7297 LOAD_PROC (listen);
7298 LOAD_PROC (getsockname);
7299 LOAD_PROC (accept);
7300 LOAD_PROC (recvfrom);
7301 LOAD_PROC (sendto);
7302 #undef LOAD_PROC
7304 /* specify version 1.1 of winsock */
7305 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7307 if (winsockData.wVersion != 0x101)
7308 goto fail;
7310 if (!load_now)
7312 /* Report that winsock exists and is usable, but leave
7313 socket functions disabled. I am assuming that calling
7314 WSAStartup does not require any network interaction,
7315 and in particular does not cause or require a dial-up
7316 connection to be established. */
7318 pfn_WSACleanup ();
7319 FreeLibrary (winsock_lib);
7320 winsock_lib = NULL;
7322 winsock_inuse = 0;
7323 return TRUE;
7326 fail:
7327 FreeLibrary (winsock_lib);
7328 winsock_lib = NULL;
7331 return FALSE;
7335 int h_errno = 0;
7337 /* Function to map winsock error codes to errno codes for those errno
7338 code defined in errno.h (errno values not defined by errno.h are
7339 already in nt/inc/sys/socket.h). */
7340 static void
7341 set_errno (void)
7343 int wsa_err;
7345 h_errno = 0;
7346 if (winsock_lib == NULL)
7347 wsa_err = EINVAL;
7348 else
7349 wsa_err = pfn_WSAGetLastError ();
7351 switch (wsa_err)
7353 case WSAEACCES: errno = EACCES; break;
7354 case WSAEBADF: errno = EBADF; break;
7355 case WSAEFAULT: errno = EFAULT; break;
7356 case WSAEINTR: errno = EINTR; break;
7357 case WSAEINVAL: errno = EINVAL; break;
7358 case WSAEMFILE: errno = EMFILE; break;
7359 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7360 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7361 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7362 case WSAENOTCONN: errno = ENOTCONN; break;
7363 default: errno = wsa_err; break;
7367 static void
7368 check_errno (void)
7370 h_errno = 0;
7371 if (winsock_lib != NULL)
7372 pfn_WSASetLastError (0);
7375 /* Extend strerror to handle the winsock-specific error codes. */
7376 struct {
7377 int errnum;
7378 char * msg;
7379 } _wsa_errlist[] = {
7380 {WSAEINTR , "Interrupted function call"},
7381 {WSAEBADF , "Bad file descriptor"},
7382 {WSAEACCES , "Permission denied"},
7383 {WSAEFAULT , "Bad address"},
7384 {WSAEINVAL , "Invalid argument"},
7385 {WSAEMFILE , "Too many open files"},
7387 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7388 {WSAEINPROGRESS , "Operation now in progress"},
7389 {WSAEALREADY , "Operation already in progress"},
7390 {WSAENOTSOCK , "Socket operation on non-socket"},
7391 {WSAEDESTADDRREQ , "Destination address required"},
7392 {WSAEMSGSIZE , "Message too long"},
7393 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7394 {WSAENOPROTOOPT , "Bad protocol option"},
7395 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7396 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7397 {WSAEOPNOTSUPP , "Operation not supported"},
7398 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7399 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7400 {WSAEADDRINUSE , "Address already in use"},
7401 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7402 {WSAENETDOWN , "Network is down"},
7403 {WSAENETUNREACH , "Network is unreachable"},
7404 {WSAENETRESET , "Network dropped connection on reset"},
7405 {WSAECONNABORTED , "Software caused connection abort"},
7406 {WSAECONNRESET , "Connection reset by peer"},
7407 {WSAENOBUFS , "No buffer space available"},
7408 {WSAEISCONN , "Socket is already connected"},
7409 {WSAENOTCONN , "Socket is not connected"},
7410 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7411 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7412 {WSAETIMEDOUT , "Connection timed out"},
7413 {WSAECONNREFUSED , "Connection refused"},
7414 {WSAELOOP , "Network loop"}, /* not sure */
7415 {WSAENAMETOOLONG , "Name is too long"},
7416 {WSAEHOSTDOWN , "Host is down"},
7417 {WSAEHOSTUNREACH , "No route to host"},
7418 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7419 {WSAEPROCLIM , "Too many processes"},
7420 {WSAEUSERS , "Too many users"}, /* not sure */
7421 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7422 {WSAESTALE , "Data is stale"}, /* not sure */
7423 {WSAEREMOTE , "Remote error"}, /* not sure */
7425 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7426 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7427 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7428 {WSAEDISCON , "Graceful shutdown in progress"},
7429 #ifdef WSAENOMORE
7430 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7431 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7432 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7433 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7434 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7435 {WSASYSCALLFAILURE , "System call failure"},
7436 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7437 {WSATYPE_NOT_FOUND , "Class type not found"},
7438 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7439 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7440 {WSAEREFUSED , "Operation refused"}, /* not sure */
7441 #endif
7443 {WSAHOST_NOT_FOUND , "Host not found"},
7444 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7445 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7446 {WSANO_DATA , "Valid name, no data record of requested type"},
7448 {-1, NULL}
7451 char *
7452 sys_strerror (int error_no)
7454 int i;
7455 static char unknown_msg[40];
7457 if (error_no >= 0 && error_no < sys_nerr)
7458 return sys_errlist[error_no];
7460 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7461 if (_wsa_errlist[i].errnum == error_no)
7462 return _wsa_errlist[i].msg;
7464 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7465 return unknown_msg;
7468 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7469 but I believe the method of keeping the socket handle separate (and
7470 insuring it is not inheritable) is the correct one. */
7472 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7474 static int socket_to_fd (SOCKET s);
7477 sys_socket (int af, int type, int protocol)
7479 SOCKET s;
7481 if (winsock_lib == NULL)
7483 errno = ENETDOWN;
7484 return -1;
7487 check_errno ();
7489 /* call the real socket function */
7490 s = pfn_socket (af, type, protocol);
7492 if (s != INVALID_SOCKET)
7493 return socket_to_fd (s);
7495 set_errno ();
7496 return -1;
7499 /* Convert a SOCKET to a file descriptor. */
7500 static int
7501 socket_to_fd (SOCKET s)
7503 int fd;
7504 child_process * cp;
7506 /* Although under NT 3.5 _open_osfhandle will accept a socket
7507 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7508 that does not work under NT 3.1. However, we can get the same
7509 effect by using a backdoor function to replace an existing
7510 descriptor handle with the one we want. */
7512 /* allocate a file descriptor (with appropriate flags) */
7513 fd = _open ("NUL:", _O_RDWR);
7514 if (fd >= 0)
7516 /* Make a non-inheritable copy of the socket handle. Note
7517 that it is possible that sockets aren't actually kernel
7518 handles, which appears to be the case on Windows 9x when
7519 the MS Proxy winsock client is installed. */
7521 /* Apparently there is a bug in NT 3.51 with some service
7522 packs, which prevents using DuplicateHandle to make a
7523 socket handle non-inheritable (causes WSACleanup to
7524 hang). The work-around is to use SetHandleInformation
7525 instead if it is available and implemented. */
7526 if (pfn_SetHandleInformation)
7528 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7530 else
7532 HANDLE parent = GetCurrentProcess ();
7533 HANDLE new_s = INVALID_HANDLE_VALUE;
7535 if (DuplicateHandle (parent,
7536 (HANDLE) s,
7537 parent,
7538 &new_s,
7540 FALSE,
7541 DUPLICATE_SAME_ACCESS))
7543 /* It is possible that DuplicateHandle succeeds even
7544 though the socket wasn't really a kernel handle,
7545 because a real handle has the same value. So
7546 test whether the new handle really is a socket. */
7547 unsigned long nonblocking = 0;
7548 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7550 pfn_closesocket (s);
7551 s = (SOCKET) new_s;
7553 else
7555 CloseHandle (new_s);
7560 eassert (fd < MAXDESC);
7561 fd_info[fd].hnd = (HANDLE) s;
7563 /* set our own internal flags */
7564 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7566 cp = new_child ();
7567 if (cp)
7569 cp->fd = fd;
7570 cp->status = STATUS_READ_ACKNOWLEDGED;
7572 /* attach child_process to fd_info */
7573 if (fd_info[ fd ].cp != NULL)
7575 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7576 emacs_abort ();
7579 fd_info[ fd ].cp = cp;
7581 /* success! */
7582 winsock_inuse++; /* count open sockets */
7583 return fd;
7586 /* clean up */
7587 _close (fd);
7589 else
7590 pfn_closesocket (s);
7591 errno = EMFILE;
7592 return -1;
7596 sys_bind (int s, const struct sockaddr * addr, int namelen)
7598 if (winsock_lib == NULL)
7600 errno = ENOTSOCK;
7601 return SOCKET_ERROR;
7604 check_errno ();
7605 if (fd_info[s].flags & FILE_SOCKET)
7607 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7608 if (rc == SOCKET_ERROR)
7609 set_errno ();
7610 return rc;
7612 errno = ENOTSOCK;
7613 return SOCKET_ERROR;
7617 sys_connect (int s, const struct sockaddr * name, int namelen)
7619 if (winsock_lib == NULL)
7621 errno = ENOTSOCK;
7622 return SOCKET_ERROR;
7625 check_errno ();
7626 if (fd_info[s].flags & FILE_SOCKET)
7628 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7629 if (rc == SOCKET_ERROR)
7631 set_errno ();
7632 /* If this is a non-blocking 'connect', set the bit in flags
7633 that will tell reader_thread to wait for connection
7634 before trying to read. */
7635 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7637 errno = EINPROGRESS; /* that's what process.c expects */
7638 fd_info[s].flags |= FILE_CONNECT;
7641 return rc;
7643 errno = ENOTSOCK;
7644 return SOCKET_ERROR;
7647 u_short
7648 sys_htons (u_short hostshort)
7650 return (winsock_lib != NULL) ?
7651 pfn_htons (hostshort) : hostshort;
7654 u_short
7655 sys_ntohs (u_short netshort)
7657 return (winsock_lib != NULL) ?
7658 pfn_ntohs (netshort) : netshort;
7661 unsigned long
7662 sys_inet_addr (const char * cp)
7664 return (winsock_lib != NULL) ?
7665 pfn_inet_addr (cp) : INADDR_NONE;
7669 sys_gethostname (char * name, int namelen)
7671 if (winsock_lib != NULL)
7673 int retval;
7675 check_errno ();
7676 retval = pfn_gethostname (name, namelen);
7677 if (retval == SOCKET_ERROR)
7678 set_errno ();
7679 return retval;
7682 if (namelen > MAX_COMPUTERNAME_LENGTH)
7683 return !GetComputerName (name, (DWORD *)&namelen);
7685 errno = EFAULT;
7686 return SOCKET_ERROR;
7689 struct hostent *
7690 sys_gethostbyname (const char * name)
7692 struct hostent * host;
7693 int h_err = h_errno;
7695 if (winsock_lib == NULL)
7697 h_errno = NO_RECOVERY;
7698 errno = ENETDOWN;
7699 return NULL;
7702 check_errno ();
7703 host = pfn_gethostbyname (name);
7704 if (!host)
7706 set_errno ();
7707 h_errno = errno;
7709 else
7710 h_errno = h_err;
7711 return host;
7714 struct servent *
7715 sys_getservbyname (const char * name, const char * proto)
7717 struct servent * serv;
7719 if (winsock_lib == NULL)
7721 errno = ENETDOWN;
7722 return NULL;
7725 check_errno ();
7726 serv = pfn_getservbyname (name, proto);
7727 if (!serv)
7728 set_errno ();
7729 return serv;
7733 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7735 if (winsock_lib == NULL)
7737 errno = ENETDOWN;
7738 return SOCKET_ERROR;
7741 check_errno ();
7742 if (fd_info[s].flags & FILE_SOCKET)
7744 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7745 if (rc == SOCKET_ERROR)
7746 set_errno ();
7747 return rc;
7749 errno = ENOTSOCK;
7750 return SOCKET_ERROR;
7754 sys_shutdown (int s, int how)
7756 if (winsock_lib == NULL)
7758 errno = ENETDOWN;
7759 return SOCKET_ERROR;
7762 check_errno ();
7763 if (fd_info[s].flags & FILE_SOCKET)
7765 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7766 if (rc == SOCKET_ERROR)
7767 set_errno ();
7768 return rc;
7770 errno = ENOTSOCK;
7771 return SOCKET_ERROR;
7775 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7777 if (winsock_lib == NULL)
7779 errno = ENETDOWN;
7780 return SOCKET_ERROR;
7783 check_errno ();
7784 if (fd_info[s].flags & FILE_SOCKET)
7786 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7787 (const char *)optval, optlen);
7788 if (rc == SOCKET_ERROR)
7789 set_errno ();
7790 return rc;
7792 errno = ENOTSOCK;
7793 return SOCKET_ERROR;
7797 sys_listen (int s, int backlog)
7799 if (winsock_lib == NULL)
7801 errno = ENETDOWN;
7802 return SOCKET_ERROR;
7805 check_errno ();
7806 if (fd_info[s].flags & FILE_SOCKET)
7808 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7809 if (rc == SOCKET_ERROR)
7810 set_errno ();
7811 else
7812 fd_info[s].flags |= FILE_LISTEN;
7813 return rc;
7815 errno = ENOTSOCK;
7816 return SOCKET_ERROR;
7820 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7822 if (winsock_lib == NULL)
7824 errno = ENETDOWN;
7825 return SOCKET_ERROR;
7828 check_errno ();
7829 if (fd_info[s].flags & FILE_SOCKET)
7831 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7832 if (rc == SOCKET_ERROR)
7833 set_errno ();
7834 return rc;
7836 errno = ENOTSOCK;
7837 return SOCKET_ERROR;
7841 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7843 if (winsock_lib == NULL)
7845 errno = ENETDOWN;
7846 return -1;
7849 check_errno ();
7850 if (fd_info[s].flags & FILE_LISTEN)
7852 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7853 int fd = -1;
7854 if (t == INVALID_SOCKET)
7855 set_errno ();
7856 else
7857 fd = socket_to_fd (t);
7859 if (fd >= 0)
7861 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7862 ResetEvent (fd_info[s].cp->char_avail);
7864 return fd;
7866 errno = ENOTSOCK;
7867 return -1;
7871 sys_recvfrom (int s, char * buf, int len, int flags,
7872 struct sockaddr * from, int * fromlen)
7874 if (winsock_lib == NULL)
7876 errno = ENETDOWN;
7877 return SOCKET_ERROR;
7880 check_errno ();
7881 if (fd_info[s].flags & FILE_SOCKET)
7883 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7884 if (rc == SOCKET_ERROR)
7885 set_errno ();
7886 return rc;
7888 errno = ENOTSOCK;
7889 return SOCKET_ERROR;
7893 sys_sendto (int s, const char * buf, int len, int flags,
7894 const struct sockaddr * to, int tolen)
7896 if (winsock_lib == NULL)
7898 errno = ENETDOWN;
7899 return SOCKET_ERROR;
7902 check_errno ();
7903 if (fd_info[s].flags & FILE_SOCKET)
7905 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7906 if (rc == SOCKET_ERROR)
7907 set_errno ();
7908 return rc;
7910 errno = ENOTSOCK;
7911 return SOCKET_ERROR;
7914 /* Windows does not have an fcntl function. Provide an implementation
7915 good enough for Emacs. */
7917 fcntl (int s, int cmd, int options)
7919 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7920 invoked in a context where fd1 is closed and all descriptors less
7921 than fd1 are open, so sys_dup is an adequate implementation. */
7922 if (cmd == F_DUPFD_CLOEXEC)
7923 return sys_dup (s);
7925 check_errno ();
7926 if (fd_info[s].flags & FILE_SOCKET)
7928 if (winsock_lib == NULL)
7930 errno = ENETDOWN;
7931 return -1;
7934 if (cmd == F_SETFL && options == O_NONBLOCK)
7936 unsigned long nblock = 1;
7937 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7938 if (rc == SOCKET_ERROR)
7939 set_errno ();
7940 /* Keep track of the fact that we set this to non-blocking. */
7941 fd_info[s].flags |= FILE_NDELAY;
7942 return rc;
7944 else
7946 errno = EINVAL;
7947 return SOCKET_ERROR;
7950 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7951 == (FILE_PIPE | FILE_WRITE))
7953 /* Force our writes to pipes be non-blocking. */
7954 if (cmd == F_SETFL && options == O_NONBLOCK)
7956 HANDLE h = (HANDLE)_get_osfhandle (s);
7957 DWORD pipe_mode = PIPE_NOWAIT;
7959 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7961 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7962 return SOCKET_ERROR;
7964 fd_info[s].flags |= FILE_NDELAY;
7965 return 0;
7967 else
7969 errno = EINVAL;
7970 return SOCKET_ERROR;
7973 errno = ENOTSOCK;
7974 return SOCKET_ERROR;
7978 /* Shadow main io functions: we need to handle pipes and sockets more
7979 intelligently. */
7982 sys_close (int fd)
7984 int rc;
7986 if (fd < 0)
7988 errno = EBADF;
7989 return -1;
7992 if (fd < MAXDESC && fd_info[fd].cp)
7994 child_process * cp = fd_info[fd].cp;
7996 fd_info[fd].cp = NULL;
7998 if (CHILD_ACTIVE (cp))
8000 /* if last descriptor to active child_process then cleanup */
8001 int i;
8002 for (i = 0; i < MAXDESC; i++)
8004 if (i == fd)
8005 continue;
8006 if (fd_info[i].cp == cp)
8007 break;
8009 if (i == MAXDESC)
8011 if (fd_info[fd].flags & FILE_SOCKET)
8013 if (winsock_lib == NULL) emacs_abort ();
8015 pfn_shutdown (SOCK_HANDLE (fd), 2);
8016 rc = pfn_closesocket (SOCK_HANDLE (fd));
8018 winsock_inuse--; /* count open sockets */
8020 /* If the process handle is NULL, it's either a socket
8021 or serial connection, or a subprocess that was
8022 already reaped by reap_subprocess, but whose
8023 resources were not yet freed, because its output was
8024 not fully read yet by the time it was reaped. (This
8025 usually happens with async subprocesses whose output
8026 is being read by Emacs.) Otherwise, this process was
8027 not reaped yet, so we set its FD to a negative value
8028 to make sure sys_select will eventually get to
8029 calling the SIGCHLD handler for it, which will then
8030 invoke waitpid and reap_subprocess. */
8031 if (cp->procinfo.hProcess == NULL)
8032 delete_child (cp);
8033 else
8034 cp->fd = -1;
8039 if (fd >= 0 && fd < MAXDESC)
8040 fd_info[fd].flags = 0;
8042 /* Note that sockets do not need special treatment here (at least on
8043 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8044 closesocket is equivalent to CloseHandle, which is to be expected
8045 because socket handles are fully fledged kernel handles. */
8046 rc = _close (fd);
8048 return rc;
8052 sys_dup (int fd)
8054 int new_fd;
8056 new_fd = _dup (fd);
8057 if (new_fd >= 0 && new_fd < MAXDESC)
8059 /* duplicate our internal info as well */
8060 fd_info[new_fd] = fd_info[fd];
8062 return new_fd;
8066 sys_dup2 (int src, int dst)
8068 int rc;
8070 if (dst < 0 || dst >= MAXDESC)
8072 errno = EBADF;
8073 return -1;
8076 /* make sure we close the destination first if it's a pipe or socket */
8077 if (src != dst && fd_info[dst].flags != 0)
8078 sys_close (dst);
8080 rc = _dup2 (src, dst);
8081 if (rc == 0)
8083 /* duplicate our internal info as well */
8084 fd_info[dst] = fd_info[src];
8086 return rc;
8090 pipe2 (int * phandles, int pipe2_flags)
8092 int rc;
8093 unsigned flags;
8094 unsigned pipe_size = 0;
8096 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8098 /* Allow Lisp to override the default buffer size of the pipe. */
8099 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8100 pipe_size = w32_pipe_buffer_size;
8102 /* make pipe handles non-inheritable; when we spawn a child, we
8103 replace the relevant handle with an inheritable one. Also put
8104 pipes into binary mode; we will do text mode translation ourselves
8105 if required. */
8106 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8108 if (rc == 0)
8110 /* Protect against overflow, since Windows can open more handles than
8111 our fd_info array has room for. */
8112 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8114 _close (phandles[0]);
8115 _close (phandles[1]);
8116 errno = EMFILE;
8117 rc = -1;
8119 else
8121 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8122 fd_info[phandles[0]].flags = flags;
8124 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8125 fd_info[phandles[1]].flags = flags;
8129 return rc;
8132 /* Function to do blocking read of one byte, needed to implement
8133 select. It is only allowed on communication ports, sockets, or
8134 pipes. */
8136 _sys_read_ahead (int fd)
8138 child_process * cp;
8139 int rc;
8141 if (fd < 0 || fd >= MAXDESC)
8142 return STATUS_READ_ERROR;
8144 cp = fd_info[fd].cp;
8146 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8147 return STATUS_READ_ERROR;
8149 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8150 || (fd_info[fd].flags & FILE_READ) == 0)
8152 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8153 emacs_abort ();
8156 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8157 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8158 cp->status = STATUS_READ_IN_PROGRESS;
8160 if (fd_info[fd].flags & FILE_PIPE)
8162 rc = _read (fd, &cp->chr, sizeof (char));
8164 /* Give subprocess time to buffer some more output for us before
8165 reporting that input is available; we need this because Windows 95
8166 connects DOS programs to pipes by making the pipe appear to be
8167 the normal console stdout - as a result most DOS programs will
8168 write to stdout without buffering, ie. one character at a
8169 time. Even some W32 programs do this - "dir" in a command
8170 shell on NT is very slow if we don't do this. */
8171 if (rc > 0)
8173 int wait = w32_pipe_read_delay;
8175 if (wait > 0)
8176 Sleep (wait);
8177 else if (wait < 0)
8178 while (++wait <= 0)
8179 /* Yield remainder of our time slice, effectively giving a
8180 temporary priority boost to the child process. */
8181 Sleep (0);
8184 else if (fd_info[fd].flags & FILE_SERIAL)
8186 HANDLE hnd = fd_info[fd].hnd;
8187 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8188 COMMTIMEOUTS ct;
8190 /* Configure timeouts for blocking read. */
8191 if (!GetCommTimeouts (hnd, &ct))
8193 cp->status = STATUS_READ_ERROR;
8194 return STATUS_READ_ERROR;
8196 ct.ReadIntervalTimeout = 0;
8197 ct.ReadTotalTimeoutMultiplier = 0;
8198 ct.ReadTotalTimeoutConstant = 0;
8199 if (!SetCommTimeouts (hnd, &ct))
8201 cp->status = STATUS_READ_ERROR;
8202 return STATUS_READ_ERROR;
8205 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8207 if (GetLastError () != ERROR_IO_PENDING)
8209 cp->status = STATUS_READ_ERROR;
8210 return STATUS_READ_ERROR;
8212 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8214 cp->status = STATUS_READ_ERROR;
8215 return STATUS_READ_ERROR;
8219 else if (fd_info[fd].flags & FILE_SOCKET)
8221 unsigned long nblock = 0;
8222 /* We always want this to block, so temporarily disable NDELAY. */
8223 if (fd_info[fd].flags & FILE_NDELAY)
8224 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8226 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8228 if (fd_info[fd].flags & FILE_NDELAY)
8230 nblock = 1;
8231 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8235 if (rc == sizeof (char))
8236 cp->status = STATUS_READ_SUCCEEDED;
8237 else
8238 cp->status = STATUS_READ_FAILED;
8240 return cp->status;
8244 _sys_wait_accept (int fd)
8246 HANDLE hEv;
8247 child_process * cp;
8248 int rc;
8250 if (fd < 0 || fd >= MAXDESC)
8251 return STATUS_READ_ERROR;
8253 cp = fd_info[fd].cp;
8255 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8256 return STATUS_READ_ERROR;
8258 cp->status = STATUS_READ_FAILED;
8260 hEv = pfn_WSACreateEvent ();
8261 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8262 if (rc != SOCKET_ERROR)
8264 do {
8265 rc = WaitForSingleObject (hEv, 500);
8266 Sleep (5);
8267 } while (rc == WAIT_TIMEOUT
8268 && cp->status != STATUS_READ_ERROR
8269 && cp->char_avail);
8270 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8271 if (rc == WAIT_OBJECT_0)
8272 cp->status = STATUS_READ_SUCCEEDED;
8274 pfn_WSACloseEvent (hEv);
8276 return cp->status;
8280 _sys_wait_connect (int fd)
8282 HANDLE hEv;
8283 child_process * cp;
8284 int rc;
8286 if (fd < 0 || fd >= MAXDESC)
8287 return STATUS_READ_ERROR;
8289 cp = fd_info[fd].cp;
8290 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8291 return STATUS_READ_ERROR;
8293 cp->status = STATUS_READ_FAILED;
8295 hEv = pfn_WSACreateEvent ();
8296 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8297 if (rc != SOCKET_ERROR)
8299 do {
8300 rc = WaitForSingleObject (hEv, 500);
8301 Sleep (5);
8302 } while (rc == WAIT_TIMEOUT
8303 && cp->status != STATUS_READ_ERROR
8304 && cp->char_avail);
8305 if (rc == WAIT_OBJECT_0)
8307 /* We've got an event, but it could be a successful
8308 connection, or it could be a failure. Find out
8309 which one is it. */
8310 WSANETWORKEVENTS events;
8312 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8313 if ((events.lNetworkEvents & FD_CONNECT) != 0
8314 && events.iErrorCode[FD_CONNECT_BIT])
8316 cp->status = STATUS_CONNECT_FAILED;
8317 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8319 else
8321 cp->status = STATUS_READ_SUCCEEDED;
8322 cp->errcode = 0;
8325 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8327 else
8328 pfn_WSACloseEvent (hEv);
8330 return cp->status;
8334 sys_read (int fd, char * buffer, unsigned int count)
8336 int nchars;
8337 int to_read;
8338 DWORD waiting;
8339 char * orig_buffer = buffer;
8341 if (fd < 0)
8343 errno = EBADF;
8344 return -1;
8347 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8349 child_process *cp = fd_info[fd].cp;
8351 if ((fd_info[fd].flags & FILE_READ) == 0)
8353 errno = EBADF;
8354 return -1;
8357 nchars = 0;
8359 /* re-read CR carried over from last read */
8360 if (fd_info[fd].flags & FILE_LAST_CR)
8362 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8363 *buffer++ = 0x0d;
8364 count--;
8365 nchars++;
8366 fd_info[fd].flags &= ~FILE_LAST_CR;
8369 /* presence of a child_process structure means we are operating in
8370 non-blocking mode - otherwise we just call _read directly.
8371 Note that the child_process structure might be missing because
8372 reap_subprocess has been called; in this case the pipe is
8373 already broken, so calling _read on it is okay. */
8374 if (cp)
8376 int current_status = cp->status;
8378 switch (current_status)
8380 case STATUS_READ_FAILED:
8381 case STATUS_READ_ERROR:
8382 /* report normal EOF if nothing in buffer */
8383 if (nchars <= 0)
8384 fd_info[fd].flags |= FILE_AT_EOF;
8385 return nchars;
8387 case STATUS_READ_READY:
8388 case STATUS_READ_IN_PROGRESS:
8389 #if 0
8390 /* This happens all the time during GnuTLS handshake
8391 with the remote, evidently because GnuTLS waits for
8392 the read to complete by retrying the read operation
8393 upon EAGAIN. So I'm disabling the DebPrint to avoid
8394 wasting cycles on something that is not a real
8395 problem. Enable if you need to debug something that
8396 bumps into this. */
8397 DebPrint (("sys_read called when read is in progress %d\n",
8398 current_status));
8399 #endif
8400 errno = EWOULDBLOCK;
8401 return -1;
8403 case STATUS_READ_SUCCEEDED:
8404 /* consume read-ahead char */
8405 *buffer++ = cp->chr;
8406 count--;
8407 nchars++;
8408 cp->status = STATUS_READ_ACKNOWLEDGED;
8409 ResetEvent (cp->char_avail);
8411 case STATUS_READ_ACKNOWLEDGED:
8412 case STATUS_CONNECT_FAILED:
8413 break;
8415 default:
8416 DebPrint (("sys_read: bad status %d\n", current_status));
8417 errno = EBADF;
8418 return -1;
8421 if (fd_info[fd].flags & FILE_PIPE)
8423 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8424 to_read = min (waiting, (DWORD) count);
8426 if (to_read > 0)
8427 nchars += _read (fd, buffer, to_read);
8429 else if (fd_info[fd].flags & FILE_SERIAL)
8431 HANDLE hnd = fd_info[fd].hnd;
8432 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8433 int rc = 0;
8434 COMMTIMEOUTS ct;
8436 if (count > 0)
8438 /* Configure timeouts for non-blocking read. */
8439 if (!GetCommTimeouts (hnd, &ct))
8441 errno = EIO;
8442 return -1;
8444 ct.ReadIntervalTimeout = MAXDWORD;
8445 ct.ReadTotalTimeoutMultiplier = 0;
8446 ct.ReadTotalTimeoutConstant = 0;
8447 if (!SetCommTimeouts (hnd, &ct))
8449 errno = EIO;
8450 return -1;
8453 if (!ResetEvent (ovl->hEvent))
8455 errno = EIO;
8456 return -1;
8458 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8460 if (GetLastError () != ERROR_IO_PENDING)
8462 errno = EIO;
8463 return -1;
8465 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8467 errno = EIO;
8468 return -1;
8471 nchars += rc;
8474 else /* FILE_SOCKET */
8476 if (winsock_lib == NULL) emacs_abort ();
8478 /* When a non-blocking 'connect' call fails,
8479 wait_reading_process_output detects this by calling
8480 'getpeername', and then attempts to obtain the connection
8481 error code by trying to read 1 byte from the socket. If
8482 we try to serve that read by calling 'recv' below, the
8483 error we get is a generic WSAENOTCONN, not the actual
8484 connection error. So instead, we use the actual error
8485 code stashed by '_sys_wait_connect' in cp->errcode.
8486 Alternatively, we could have used 'getsockopt', like on
8487 GNU/Linux, but: (a) I have no idea whether the winsock
8488 version could hang, as it does "on some systems" (see the
8489 comment in process.c); and (b) 'getsockopt' on Windows is
8490 documented to clear the socket error for the entire
8491 process, which I'm not sure is TRT; FIXME. */
8492 if (current_status == STATUS_CONNECT_FAILED
8493 && (fd_info[fd].flags & FILE_CONNECT) != 0
8494 && cp->errcode != 0)
8496 pfn_WSASetLastError (cp->errcode);
8497 set_errno ();
8498 return -1;
8500 /* Do the equivalent of a non-blocking read. */
8501 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8502 if (waiting == 0 && nchars == 0)
8504 errno = EWOULDBLOCK;
8505 return -1;
8508 if (waiting)
8510 /* always use binary mode for sockets */
8511 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8512 if (res == SOCKET_ERROR)
8514 set_errno ();
8515 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8516 errno, SOCK_HANDLE (fd)));
8517 return -1;
8519 nchars += res;
8523 else
8525 int nread = _read (fd, buffer, count);
8526 if (nread >= 0)
8527 nchars += nread;
8528 else if (nchars == 0)
8529 nchars = nread;
8532 if (nchars <= 0)
8533 fd_info[fd].flags |= FILE_AT_EOF;
8534 /* Perform text mode translation if required. */
8535 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8537 nchars = crlf_to_lf (nchars, orig_buffer);
8538 /* If buffer contains only CR, return that. To be absolutely
8539 sure we should attempt to read the next char, but in
8540 practice a CR to be followed by LF would not appear by
8541 itself in the buffer. */
8542 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8544 fd_info[fd].flags |= FILE_LAST_CR;
8545 nchars--;
8549 else
8550 nchars = _read (fd, buffer, count);
8552 return nchars;
8555 /* From w32xfns.c */
8556 extern HANDLE interrupt_handle;
8559 sys_write (int fd, const void * buffer, unsigned int count)
8561 int nchars;
8562 USE_SAFE_ALLOCA;
8564 if (fd < 0)
8566 errno = EBADF;
8567 return -1;
8570 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8572 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8574 errno = EBADF;
8575 return -1;
8578 /* Perform text mode translation if required. */
8579 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8581 char * tmpbuf;
8582 const unsigned char * src = buffer;
8583 unsigned char * dst;
8584 int nbytes = count;
8586 SAFE_NALLOCA (tmpbuf, 2, count);
8587 dst = (unsigned char *)tmpbuf;
8589 while (1)
8591 unsigned char *next;
8592 /* Copy next line or remaining bytes. */
8593 next = _memccpy (dst, src, '\n', nbytes);
8594 if (next)
8596 /* Copied one line ending with '\n'. */
8597 int copied = next - dst;
8598 nbytes -= copied;
8599 src += copied;
8600 /* Insert '\r' before '\n'. */
8601 next[-1] = '\r';
8602 next[0] = '\n';
8603 dst = next + 1;
8604 count++;
8606 else
8607 /* Copied remaining partial line -> now finished. */
8608 break;
8610 buffer = tmpbuf;
8614 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8616 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8617 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8618 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8619 DWORD active = 0;
8621 /* This is async (a.k.a. "overlapped") I/O, so the return value
8622 of FALSE from WriteFile means either an error or the output
8623 will be completed asynchronously (ERROR_IO_PENDING). */
8624 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8626 if (GetLastError () != ERROR_IO_PENDING)
8628 errno = EIO;
8629 nchars = -1;
8631 else
8633 /* Wait for the write to complete, and watch C-g while
8634 at that. */
8635 if (detect_input_pending ())
8636 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8637 INFINITE, QS_ALLINPUT);
8638 else
8639 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8640 switch (active)
8642 case WAIT_OBJECT_0:
8643 /* User pressed C-g, cancel write, then leave.
8644 Don't bother cleaning up as we may only get stuck
8645 in buggy drivers. */
8646 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8647 CancelIo (hnd);
8648 errno = EIO; /* Why not EINTR? */
8649 nchars = -1;
8650 break;
8651 case WAIT_OBJECT_0 + 1:
8652 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8654 errno = EIO;
8655 nchars = -1;
8657 break;
8662 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8664 unsigned long nblock = 0;
8665 if (winsock_lib == NULL) emacs_abort ();
8667 /* TODO: implement select() properly so non-blocking I/O works. */
8668 /* For now, make sure the write blocks. */
8669 if (fd_info[fd].flags & FILE_NDELAY)
8670 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8672 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8674 /* Set the socket back to non-blocking if it was before,
8675 for other operations that support it. */
8676 if (fd_info[fd].flags & FILE_NDELAY)
8678 nblock = 1;
8679 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8682 if (nchars == SOCKET_ERROR)
8684 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8685 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8686 set_errno ();
8689 else
8691 /* Some networked filesystems don't like too large writes, so
8692 break them into smaller chunks. See the Comments section of
8693 the MSDN documentation of WriteFile for details behind the
8694 choice of the value of CHUNK below. See also the thread
8695 http://thread.gmane.org/gmane.comp.version-control.git/145294
8696 in the git mailing list. */
8697 const unsigned char *p = buffer;
8698 const bool is_pipe = (fd < MAXDESC
8699 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8700 == (FILE_PIPE | FILE_NDELAY)));
8701 /* Some programs, notably Node.js's node.exe, seem to never
8702 completely empty the pipe, so writing more than the size of
8703 the pipe's buffer always returns ENOSPC, and we loop forever
8704 between send_process and here. As a workaround, write no
8705 more than the pipe's buffer can hold. */
8706 DWORD pipe_buffer_size;
8707 if (is_pipe)
8709 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8710 NULL, &pipe_buffer_size, NULL, NULL))
8712 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8713 pipe_buffer_size = 4096;
8716 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8718 nchars = 0;
8719 errno = 0;
8720 while (count > 0)
8722 unsigned this_chunk = count < chunk ? count : chunk;
8723 int n = _write (fd, p, this_chunk);
8725 if (n > 0)
8726 nchars += n;
8727 if (n < 0)
8729 /* When there's no buffer space in a pipe that is in the
8730 non-blocking mode, _write returns ENOSPC. We return
8731 EAGAIN instead, which should trigger the logic in
8732 send_process that enters waiting loop and calls
8733 wait_reading_process_output to allow process input to
8734 be accepted during the wait. Those calls to
8735 wait_reading_process_output allow sys_select to
8736 notice when process input becomes available, thus
8737 avoiding deadlock whereby each side of the pipe is
8738 blocked on write, waiting for the other party to read
8739 its end of the pipe. */
8740 if (errno == ENOSPC && is_pipe)
8741 errno = EAGAIN;
8742 if (nchars == 0)
8743 nchars = -1;
8744 break;
8746 else if (n < this_chunk)
8747 break;
8748 count -= n;
8749 p += n;
8753 SAFE_FREE ();
8754 return nchars;
8758 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8760 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8762 /* Return information about network interface IFNAME, or about all
8763 interfaces (if IFNAME is nil). */
8764 static Lisp_Object
8765 network_interface_get_info (Lisp_Object ifname)
8767 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8768 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8769 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8770 Lisp_Object res = Qnil;
8772 if (retval == ERROR_BUFFER_OVERFLOW)
8774 ainfo = xrealloc (ainfo, ainfo_len);
8775 retval = get_adapters_info (ainfo, &ainfo_len);
8778 if (retval == ERROR_SUCCESS)
8780 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8781 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8782 int if_num;
8783 struct sockaddr_in sa;
8785 /* For the below, we need some winsock functions, so make sure
8786 the winsock DLL is loaded. If we cannot successfully load
8787 it, they will have no use of the information we provide,
8788 anyway, so punt. */
8789 if (!winsock_lib && !init_winsock (1))
8790 goto done;
8792 for (adapter = ainfo; adapter; adapter = adapter->Next)
8794 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8795 u_long ip_addr;
8796 /* Present Unix-compatible interface names, instead of the
8797 Windows names, which are really GUIDs not readable by
8798 humans. */
8799 static const char *ifmt[] = {
8800 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8801 "lo", "ifx%d"
8803 enum {
8804 NONE = -1,
8805 ETHERNET = 0,
8806 TOKENRING = 1,
8807 FDDI = 2,
8808 PPP = 3,
8809 SLIP = 4,
8810 WLAN = 5,
8811 LOOPBACK = 6,
8812 OTHER_IF = 7
8813 } ifmt_idx;
8815 switch (adapter->Type)
8817 case MIB_IF_TYPE_ETHERNET:
8818 /* Windows before Vista reports wireless adapters as
8819 Ethernet. Work around by looking at the Description
8820 string. */
8821 if (strstr (adapter->Description, "Wireless "))
8823 ifmt_idx = WLAN;
8824 if_num = wlan_count++;
8826 else
8828 ifmt_idx = ETHERNET;
8829 if_num = eth_count++;
8831 break;
8832 case MIB_IF_TYPE_TOKENRING:
8833 ifmt_idx = TOKENRING;
8834 if_num = tr_count++;
8835 break;
8836 case MIB_IF_TYPE_FDDI:
8837 ifmt_idx = FDDI;
8838 if_num = fddi_count++;
8839 break;
8840 case MIB_IF_TYPE_PPP:
8841 ifmt_idx = PPP;
8842 if_num = ppp_count++;
8843 break;
8844 case MIB_IF_TYPE_SLIP:
8845 ifmt_idx = SLIP;
8846 if_num = sl_count++;
8847 break;
8848 case IF_TYPE_IEEE80211:
8849 ifmt_idx = WLAN;
8850 if_num = wlan_count++;
8851 break;
8852 case MIB_IF_TYPE_LOOPBACK:
8853 if (lo_count < 0)
8855 ifmt_idx = LOOPBACK;
8856 if_num = lo_count++;
8858 else
8859 ifmt_idx = NONE;
8860 break;
8861 default:
8862 ifmt_idx = OTHER_IF;
8863 if_num = ifx_count++;
8864 break;
8866 if (ifmt_idx == NONE)
8867 continue;
8868 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8870 sa.sin_family = AF_INET;
8871 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8872 if (ip_addr == INADDR_NONE)
8874 /* Bogus address, skip this interface. */
8875 continue;
8877 sa.sin_addr.s_addr = ip_addr;
8878 sa.sin_port = 0;
8879 if (NILP (ifname))
8880 res = Fcons (Fcons (build_string (namebuf),
8881 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8882 sizeof (struct sockaddr))),
8883 res);
8884 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8886 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8887 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8888 Lisp_Object flags = Qnil;
8889 int n;
8890 u_long net_mask;
8892 /* Flags. We guess most of them by type, since the
8893 Windows flags are different and hard to get by. */
8894 flags = Fcons (intern ("up"), flags);
8895 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8897 flags = Fcons (intern ("broadcast"), flags);
8898 flags = Fcons (intern ("multicast"), flags);
8900 flags = Fcons (intern ("running"), flags);
8901 if (ifmt_idx == PPP)
8903 flags = Fcons (intern ("pointopoint"), flags);
8904 flags = Fcons (intern ("noarp"), flags);
8906 if (adapter->HaveWins)
8907 flags = Fcons (intern ("WINS"), flags);
8908 if (adapter->DhcpEnabled)
8909 flags = Fcons (intern ("dynamic"), flags);
8911 res = Fcons (flags, res);
8913 /* Hardware address and its family. */
8914 for (n = 0; n < adapter->AddressLength; n++)
8915 p->contents[n] = make_number ((int) adapter->Address[n]);
8916 /* Windows does not support AF_LINK or AF_PACKET family
8917 of addresses. Use an arbitrary family number that is
8918 identical to what GNU/Linux returns. */
8919 res = Fcons (Fcons (make_number (1), hwaddr), res);
8921 /* Network mask. */
8922 sa.sin_family = AF_INET;
8923 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8924 if (net_mask != INADDR_NONE)
8926 sa.sin_addr.s_addr = net_mask;
8927 sa.sin_port = 0;
8928 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8929 sizeof (struct sockaddr)),
8930 res);
8932 else
8933 res = Fcons (Qnil, res);
8935 sa.sin_family = AF_INET;
8936 if (ip_addr != INADDR_NONE)
8938 /* Broadcast address is only reported by
8939 GetAdaptersAddresses, which is of limited
8940 availability. Generate it on our own. */
8941 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8943 sa.sin_addr.s_addr = bcast_addr;
8944 sa.sin_port = 0;
8945 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8946 sizeof (struct sockaddr)),
8947 res);
8949 /* IP address. */
8950 sa.sin_addr.s_addr = ip_addr;
8951 sa.sin_port = 0;
8952 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8953 sizeof (struct sockaddr)),
8954 res);
8956 else
8957 res = Fcons (Qnil, Fcons (Qnil, res));
8960 /* GetAdaptersInfo is documented to not report loopback
8961 interfaces, so we generate one out of thin air. */
8962 if (!lo_count)
8964 sa.sin_family = AF_INET;
8965 sa.sin_port = 0;
8966 if (NILP (ifname))
8968 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8969 res = Fcons (Fcons (build_string ("lo"),
8970 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8971 sizeof (struct sockaddr))),
8972 res);
8974 else if (strcmp (SSDATA (ifname), "lo") == 0)
8976 res = Fcons (Fcons (intern ("running"),
8977 Fcons (intern ("loopback"),
8978 Fcons (intern ("up"), Qnil))), Qnil);
8979 /* 772 is what 3 different GNU/Linux systems report for
8980 the loopback interface. */
8981 res = Fcons (Fcons (make_number (772),
8982 Fmake_vector (make_number (6),
8983 make_number (0))),
8984 res);
8985 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8986 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8987 sizeof (struct sockaddr)),
8988 res);
8989 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8990 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8991 sizeof (struct sockaddr)),
8992 res);
8993 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8994 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8995 sizeof (struct sockaddr)),
8996 res);
9002 done:
9003 xfree (ainfo);
9004 return res;
9007 Lisp_Object
9008 network_interface_list (void)
9010 return network_interface_get_info (Qnil);
9013 Lisp_Object
9014 network_interface_info (Lisp_Object ifname)
9016 CHECK_STRING (ifname);
9017 return network_interface_get_info (ifname);
9021 /* The Windows CRT functions are "optimized for speed", so they don't
9022 check for timezone and DST changes if they were last called less
9023 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9024 all Emacs features that repeatedly call time functions (e.g.,
9025 display-time) are in real danger of missing timezone and DST
9026 changes. Calling tzset before each localtime call fixes that. */
9027 struct tm *
9028 sys_localtime (const time_t *t)
9030 tzset ();
9031 return localtime (t);
9036 /* Try loading LIBRARY_ID from the file(s) specified in
9037 Vdynamic_library_alist. If the library is loaded successfully,
9038 return the handle of the DLL, and record the filename in the
9039 property :loaded-from of LIBRARY_ID. If the library could not be
9040 found, or when it was already loaded (because the handle is not
9041 recorded anywhere, and so is lost after use), return NULL.
9043 We could also save the handle in :loaded-from, but currently
9044 there's no use case for it. */
9045 HMODULE
9046 w32_delayed_load (Lisp_Object library_id)
9048 HMODULE dll_handle = NULL;
9050 CHECK_SYMBOL (library_id);
9052 if (CONSP (Vdynamic_library_alist)
9053 && NILP (Fassq (library_id, Vlibrary_cache)))
9055 Lisp_Object found = Qnil;
9056 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9058 if (CONSP (dlls))
9059 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9061 Lisp_Object dll = XCAR (dlls);
9062 char name[MAX_UTF8_PATH];
9063 DWORD res = -1;
9065 CHECK_STRING (dll);
9066 dll = ENCODE_FILE (dll);
9067 if (w32_unicode_filenames)
9069 wchar_t name_w[MAX_PATH];
9071 filename_to_utf16 (SSDATA (dll), name_w);
9072 dll_handle = LoadLibraryW (name_w);
9073 if (dll_handle)
9075 res = GetModuleFileNameW (dll_handle, name_w,
9076 sizeof (name_w));
9077 if (res > 0)
9078 filename_from_utf16 (name_w, name);
9081 else
9083 char name_a[MAX_PATH];
9085 filename_to_ansi (SSDATA (dll), name_a);
9086 dll_handle = LoadLibraryA (name_a);
9087 if (dll_handle)
9089 res = GetModuleFileNameA (dll_handle, name_a,
9090 sizeof (name_a));
9091 if (res > 0)
9092 filename_from_ansi (name_a, name);
9095 if (dll_handle)
9097 ptrdiff_t len = strlen (name);
9098 found = Fcons (dll,
9099 (res > 0)
9100 /* Possibly truncated */
9101 ? make_specified_string (name, -1, len, 1)
9102 : Qnil);
9103 /* This prevents thread start and end notifications
9104 from being sent to the DLL, for every thread we
9105 start. We don't need those notifications because
9106 threads we create never use any of these DLLs, only
9107 the main thread uses them. This is supposed to
9108 speed up thread creation. */
9109 DisableThreadLibraryCalls (dll_handle);
9110 break;
9114 Fput (library_id, QCloaded_from, found);
9117 return dll_handle;
9121 void
9122 check_windows_init_file (void)
9124 /* A common indication that Emacs is not installed properly is when
9125 it cannot find the Windows installation file. If this file does
9126 not exist in the expected place, tell the user. */
9128 if (!noninteractive && !inhibit_window_system
9129 /* Vload_path is not yet initialized when we are loading
9130 loadup.el. */
9131 && NILP (Vpurify_flag))
9133 Lisp_Object init_file;
9134 int fd;
9136 /* Implementation note: this function runs early during Emacs
9137 startup, before startup.el is run. So Vload_path is still in
9138 its initial unibyte form, but it holds UTF-8 encoded file
9139 names, since init_callproc was already called. So we do not
9140 need to ENCODE_FILE here, but we do need to convert the file
9141 names from UTF-8 to ANSI. */
9142 init_file = build_string ("term/w32-win");
9143 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9144 if (fd < 0)
9146 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9147 char *init_file_name = SSDATA (init_file);
9148 char *load_path = SSDATA (load_path_print);
9149 char *buffer = alloca (1024
9150 + strlen (init_file_name)
9151 + strlen (load_path));
9152 char *msg = buffer;
9153 int needed;
9155 sprintf (buffer,
9156 "The Emacs Windows initialization file \"%s.el\" "
9157 "could not be found in your Emacs installation. "
9158 "Emacs checked the following directories for this file:\n"
9159 "\n%s\n\n"
9160 "When Emacs cannot find this file, it usually means that it "
9161 "was not installed properly, or its distribution file was "
9162 "not unpacked properly.\nSee the README.W32 file in the "
9163 "top-level Emacs directory for more information.",
9164 init_file_name, load_path);
9165 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9166 buffer, -1, NULL, 0);
9167 if (needed > 0)
9169 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9171 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9172 -1, msg_w, needed);
9173 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9174 NULL, 0, NULL, NULL);
9175 if (needed > 0)
9177 char *msg_a = alloca (needed + 1);
9179 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9180 NULL, NULL);
9181 msg = msg_a;
9184 MessageBox (NULL,
9185 msg,
9186 "Emacs Abort Dialog",
9187 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9188 /* Use the low-level system abort. */
9189 abort ();
9191 else
9193 _close (fd);
9198 void
9199 term_ntproc (int ignored)
9201 (void)ignored;
9203 term_timers ();
9205 /* shutdown the socket interface if necessary */
9206 term_winsock ();
9208 term_w32select ();
9211 void
9212 init_ntproc (int dumping)
9214 sigset_t initial_mask = 0;
9216 /* Initialize the socket interface now if available and requested by
9217 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9218 delayed until open-network-stream is called (w32-has-winsock can
9219 also be used to dynamically load or reload winsock).
9221 Conveniently, init_environment is called before us, so
9222 PRELOAD_WINSOCK can be set in the registry. */
9224 /* Always initialize this correctly. */
9225 winsock_lib = NULL;
9227 if (getenv ("PRELOAD_WINSOCK") != NULL)
9228 init_winsock (TRUE);
9230 /* Initial preparation for subprocess support: replace our standard
9231 handles with non-inheritable versions. */
9233 HANDLE parent;
9234 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9235 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9236 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9238 parent = GetCurrentProcess ();
9240 /* ignore errors when duplicating and closing; typically the
9241 handles will be invalid when running as a gui program. */
9242 DuplicateHandle (parent,
9243 GetStdHandle (STD_INPUT_HANDLE),
9244 parent,
9245 &stdin_save,
9247 FALSE,
9248 DUPLICATE_SAME_ACCESS);
9250 DuplicateHandle (parent,
9251 GetStdHandle (STD_OUTPUT_HANDLE),
9252 parent,
9253 &stdout_save,
9255 FALSE,
9256 DUPLICATE_SAME_ACCESS);
9258 DuplicateHandle (parent,
9259 GetStdHandle (STD_ERROR_HANDLE),
9260 parent,
9261 &stderr_save,
9263 FALSE,
9264 DUPLICATE_SAME_ACCESS);
9266 fclose (stdin);
9267 fclose (stdout);
9268 fclose (stderr);
9270 if (stdin_save != INVALID_HANDLE_VALUE)
9271 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9272 else
9273 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9274 _fdopen (0, "r");
9276 if (stdout_save != INVALID_HANDLE_VALUE)
9277 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9278 else
9279 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9280 _fdopen (1, "w");
9282 if (stderr_save != INVALID_HANDLE_VALUE)
9283 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9284 else
9285 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9286 _fdopen (2, "w");
9289 /* unfortunately, atexit depends on implementation of malloc */
9290 /* atexit (term_ntproc); */
9291 if (!dumping)
9293 /* Make sure we start with all signals unblocked. */
9294 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9295 signal (SIGABRT, term_ntproc);
9297 init_timers ();
9299 /* determine which drives are fixed, for GetCachedVolumeInformation */
9301 /* GetDriveType must have trailing backslash. */
9302 char drive[] = "A:\\";
9304 /* Loop over all possible drive letters */
9305 while (*drive <= 'Z')
9307 /* Record if this drive letter refers to a fixed drive. */
9308 fixed_drives[DRIVE_INDEX (*drive)] =
9309 (GetDriveType (drive) == DRIVE_FIXED);
9311 (*drive)++;
9314 /* Reset the volume info cache. */
9315 volume_cache = NULL;
9320 shutdown_handler ensures that buffers' autosave files are
9321 up to date when the user logs off, or the system shuts down.
9323 static BOOL WINAPI
9324 shutdown_handler (DWORD type)
9326 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9327 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9328 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9329 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9331 /* Shut down cleanly, making sure autosave files are up to date. */
9332 shut_down_emacs (0, Qnil);
9335 /* Allow other handlers to handle this signal. */
9336 return FALSE;
9339 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9340 NT, return a handle to GDI32.DLL. */
9341 HANDLE
9342 maybe_load_unicows_dll (void)
9344 if (os_subtype == OS_9X)
9346 HANDLE ret = LoadLibrary ("Unicows.dll");
9347 if (ret)
9349 /* These two functions are present on Windows 9X as stubs
9350 that always fail. We need the real implementations from
9351 UNICOWS.DLL, so we must call these functions through
9352 pointers, and assign the correct addresses to these
9353 pointers at program startup (see emacs.c, which calls
9354 this function early on). */
9355 pMultiByteToWideChar =
9356 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9357 pWideCharToMultiByte =
9358 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9359 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9360 return ret;
9362 else
9364 int button;
9366 button = MessageBox (NULL,
9367 "Emacs cannot load the UNICOWS.DLL library.\n"
9368 "This library is essential for using Emacs\n"
9369 "on this system. You need to install it.\n\n"
9370 "Emacs will exit when you click OK.",
9371 "Emacs cannot load UNICOWS.DLL",
9372 MB_ICONERROR | MB_TASKMODAL
9373 | MB_SETFOREGROUND | MB_OK);
9374 switch (button)
9376 case IDOK:
9377 default:
9378 exit (1);
9382 else
9384 /* On NT family of Windows, these two functions are always
9385 linked in, so we just assign their addresses to the 2
9386 pointers; no need for the LoadLibrary dance. */
9387 pMultiByteToWideChar = MultiByteToWideChar;
9388 pWideCharToMultiByte = WideCharToMultiByte;
9389 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9390 if (w32_major_version < 5)
9391 multiByteToWideCharFlags = 0;
9392 else
9393 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9394 return LoadLibrary ("Gdi32.dll");
9399 globals_of_w32 is used to initialize those global variables that
9400 must always be initialized on startup even when the global variable
9401 initialized is non zero (see the function main in emacs.c).
9403 void
9404 globals_of_w32 (void)
9406 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9408 get_process_times_fn = (GetProcessTimes_Proc)
9409 GetProcAddress (kernel32, "GetProcessTimes");
9411 DEFSYM (QCloaded_from, ":loaded-from");
9413 g_b_init_is_windows_9x = 0;
9414 g_b_init_open_process_token = 0;
9415 g_b_init_get_token_information = 0;
9416 g_b_init_lookup_account_sid = 0;
9417 g_b_init_get_sid_sub_authority = 0;
9418 g_b_init_get_sid_sub_authority_count = 0;
9419 g_b_init_get_security_info = 0;
9420 g_b_init_get_file_security_w = 0;
9421 g_b_init_get_file_security_a = 0;
9422 g_b_init_get_security_descriptor_owner = 0;
9423 g_b_init_get_security_descriptor_group = 0;
9424 g_b_init_is_valid_sid = 0;
9425 g_b_init_create_toolhelp32_snapshot = 0;
9426 g_b_init_process32_first = 0;
9427 g_b_init_process32_next = 0;
9428 g_b_init_open_thread_token = 0;
9429 g_b_init_impersonate_self = 0;
9430 g_b_init_revert_to_self = 0;
9431 g_b_init_get_process_memory_info = 0;
9432 g_b_init_get_process_working_set_size = 0;
9433 g_b_init_global_memory_status = 0;
9434 g_b_init_global_memory_status_ex = 0;
9435 g_b_init_equal_sid = 0;
9436 g_b_init_copy_sid = 0;
9437 g_b_init_get_length_sid = 0;
9438 g_b_init_get_native_system_info = 0;
9439 g_b_init_get_system_times = 0;
9440 g_b_init_create_symbolic_link_w = 0;
9441 g_b_init_create_symbolic_link_a = 0;
9442 g_b_init_get_security_descriptor_dacl = 0;
9443 g_b_init_convert_sd_to_sddl = 0;
9444 g_b_init_convert_sddl_to_sd = 0;
9445 g_b_init_is_valid_security_descriptor = 0;
9446 g_b_init_set_file_security_w = 0;
9447 g_b_init_set_file_security_a = 0;
9448 g_b_init_set_named_security_info_w = 0;
9449 g_b_init_set_named_security_info_a = 0;
9450 g_b_init_get_adapters_info = 0;
9451 g_b_init_compare_string_w = 0;
9452 num_of_processors = 0;
9453 /* The following sets a handler for shutdown notifications for
9454 console apps. This actually applies to Emacs in both console and
9455 GUI modes, since we had to fool windows into thinking emacs is a
9456 console application to get console mode to work. */
9457 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9459 /* "None" is the default group name on standalone workstations. */
9460 strcpy (dflt_group_name, "None");
9462 /* Reset, in case it has some value inherited from dump time. */
9463 w32_stat_get_owner_group = 0;
9465 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9466 (a.k.a. "wide") APIs to invoke functions that accept file
9467 names. */
9468 if (is_windows_9x ())
9469 w32_unicode_filenames = 0;
9470 else
9471 w32_unicode_filenames = 1;
9473 #ifdef HAVE_MODULES
9474 extern void dynlib_reset_last_error (void);
9475 dynlib_reset_last_error ();
9476 #endif
9478 w32_crypto_hprov = (HCRYPTPROV)0;
9481 /* For make-serial-process */
9483 serial_open (Lisp_Object port_obj)
9485 char *port = SSDATA (port_obj);
9486 HANDLE hnd;
9487 child_process *cp;
9488 int fd = -1;
9490 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9491 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9492 if (hnd == INVALID_HANDLE_VALUE)
9493 error ("Could not open %s", port);
9494 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9495 if (fd == -1)
9496 error ("Could not open %s", port);
9498 cp = new_child ();
9499 if (!cp)
9500 error ("Could not create child process");
9501 cp->fd = fd;
9502 cp->status = STATUS_READ_ACKNOWLEDGED;
9503 fd_info[ fd ].hnd = hnd;
9504 fd_info[ fd ].flags |=
9505 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9506 if (fd_info[ fd ].cp != NULL)
9508 error ("fd_info[fd = %d] is already in use", fd);
9510 fd_info[ fd ].cp = cp;
9511 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9512 if (cp->ovl_read.hEvent == NULL)
9513 error ("Could not create read event");
9514 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9515 if (cp->ovl_write.hEvent == NULL)
9516 error ("Could not create write event");
9518 return fd;
9521 /* For serial-process-configure */
9522 void
9523 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9525 Lisp_Object childp2 = Qnil;
9526 Lisp_Object tem = Qnil;
9527 HANDLE hnd;
9528 DCB dcb;
9529 COMMTIMEOUTS ct;
9530 char summary[4] = "???"; /* This usually becomes "8N1". */
9532 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9533 error ("Not a serial process");
9534 hnd = fd_info[ p->outfd ].hnd;
9536 childp2 = Fcopy_sequence (p->childp);
9538 /* Initialize timeouts for blocking read and blocking write. */
9539 if (!GetCommTimeouts (hnd, &ct))
9540 error ("GetCommTimeouts() failed");
9541 ct.ReadIntervalTimeout = 0;
9542 ct.ReadTotalTimeoutMultiplier = 0;
9543 ct.ReadTotalTimeoutConstant = 0;
9544 ct.WriteTotalTimeoutMultiplier = 0;
9545 ct.WriteTotalTimeoutConstant = 0;
9546 if (!SetCommTimeouts (hnd, &ct))
9547 error ("SetCommTimeouts() failed");
9548 /* Read port attributes and prepare default configuration. */
9549 memset (&dcb, 0, sizeof (dcb));
9550 dcb.DCBlength = sizeof (DCB);
9551 if (!GetCommState (hnd, &dcb))
9552 error ("GetCommState() failed");
9553 dcb.fBinary = TRUE;
9554 dcb.fNull = FALSE;
9555 dcb.fAbortOnError = FALSE;
9556 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9557 dcb.ErrorChar = 0;
9558 dcb.EofChar = 0;
9559 dcb.EvtChar = 0;
9561 /* Configure speed. */
9562 if (!NILP (Fplist_member (contact, QCspeed)))
9563 tem = Fplist_get (contact, QCspeed);
9564 else
9565 tem = Fplist_get (p->childp, QCspeed);
9566 CHECK_NUMBER (tem);
9567 dcb.BaudRate = XINT (tem);
9568 childp2 = Fplist_put (childp2, QCspeed, tem);
9570 /* Configure bytesize. */
9571 if (!NILP (Fplist_member (contact, QCbytesize)))
9572 tem = Fplist_get (contact, QCbytesize);
9573 else
9574 tem = Fplist_get (p->childp, QCbytesize);
9575 if (NILP (tem))
9576 tem = make_number (8);
9577 CHECK_NUMBER (tem);
9578 if (XINT (tem) != 7 && XINT (tem) != 8)
9579 error (":bytesize must be nil (8), 7, or 8");
9580 dcb.ByteSize = XINT (tem);
9581 summary[0] = XINT (tem) + '0';
9582 childp2 = Fplist_put (childp2, QCbytesize, tem);
9584 /* Configure parity. */
9585 if (!NILP (Fplist_member (contact, QCparity)))
9586 tem = Fplist_get (contact, QCparity);
9587 else
9588 tem = Fplist_get (p->childp, QCparity);
9589 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9590 error (":parity must be nil (no parity), `even', or `odd'");
9591 dcb.fParity = FALSE;
9592 dcb.Parity = NOPARITY;
9593 dcb.fErrorChar = FALSE;
9594 if (NILP (tem))
9596 summary[1] = 'N';
9598 else if (EQ (tem, Qeven))
9600 summary[1] = 'E';
9601 dcb.fParity = TRUE;
9602 dcb.Parity = EVENPARITY;
9603 dcb.fErrorChar = TRUE;
9605 else if (EQ (tem, Qodd))
9607 summary[1] = 'O';
9608 dcb.fParity = TRUE;
9609 dcb.Parity = ODDPARITY;
9610 dcb.fErrorChar = TRUE;
9612 childp2 = Fplist_put (childp2, QCparity, tem);
9614 /* Configure stopbits. */
9615 if (!NILP (Fplist_member (contact, QCstopbits)))
9616 tem = Fplist_get (contact, QCstopbits);
9617 else
9618 tem = Fplist_get (p->childp, QCstopbits);
9619 if (NILP (tem))
9620 tem = make_number (1);
9621 CHECK_NUMBER (tem);
9622 if (XINT (tem) != 1 && XINT (tem) != 2)
9623 error (":stopbits must be nil (1 stopbit), 1, or 2");
9624 summary[2] = XINT (tem) + '0';
9625 if (XINT (tem) == 1)
9626 dcb.StopBits = ONESTOPBIT;
9627 else if (XINT (tem) == 2)
9628 dcb.StopBits = TWOSTOPBITS;
9629 childp2 = Fplist_put (childp2, QCstopbits, tem);
9631 /* Configure flowcontrol. */
9632 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9633 tem = Fplist_get (contact, QCflowcontrol);
9634 else
9635 tem = Fplist_get (p->childp, QCflowcontrol);
9636 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9637 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9638 dcb.fOutxCtsFlow = FALSE;
9639 dcb.fOutxDsrFlow = FALSE;
9640 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9641 dcb.fDsrSensitivity = FALSE;
9642 dcb.fTXContinueOnXoff = FALSE;
9643 dcb.fOutX = FALSE;
9644 dcb.fInX = FALSE;
9645 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9646 dcb.XonChar = 17; /* Control-Q */
9647 dcb.XoffChar = 19; /* Control-S */
9648 if (NILP (tem))
9650 /* Already configured. */
9652 else if (EQ (tem, Qhw))
9654 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9655 dcb.fOutxCtsFlow = TRUE;
9657 else if (EQ (tem, Qsw))
9659 dcb.fOutX = TRUE;
9660 dcb.fInX = TRUE;
9662 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9664 /* Activate configuration. */
9665 if (!SetCommState (hnd, &dcb))
9666 error ("SetCommState() failed");
9668 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9669 pset_childp (p, childp2);
9672 /* For make-pipe-process */
9673 void
9674 register_aux_fd (int infd)
9676 child_process *cp;
9678 cp = new_child ();
9679 if (!cp)
9680 error ("Could not create child process");
9681 cp->fd = infd;
9682 cp->status = STATUS_READ_ACKNOWLEDGED;
9684 if (fd_info[ infd ].cp != NULL)
9686 error ("fd_info[fd = %d] is already in use", infd);
9688 fd_info[ infd ].cp = cp;
9689 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9692 #ifdef HAVE_GNUTLS
9694 ssize_t
9695 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9697 int n, err;
9698 struct Lisp_Process *process = (struct Lisp_Process *)p;
9699 int fd = process->infd;
9701 n = sys_read (fd, (char*)buf, sz);
9703 if (n >= 0)
9704 return n;
9706 err = errno;
9708 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9709 if (err == EWOULDBLOCK)
9710 err = EAGAIN;
9712 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9714 return -1;
9717 ssize_t
9718 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9720 struct Lisp_Process *process = (struct Lisp_Process *)p;
9721 int fd = process->outfd;
9722 ssize_t n = sys_write (fd, buf, sz);
9724 /* 0 or more bytes written means everything went fine. */
9725 if (n >= 0)
9726 return n;
9728 /* Negative bytes written means we got an error in errno.
9729 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9730 emacs_gnutls_transport_set_errno (process->gnutls_state,
9731 errno == EWOULDBLOCK ? EAGAIN : errno);
9733 return -1;
9735 #endif /* HAVE_GNUTLS */
9737 /* end of w32.c */