Bump version to 24.4.91
[emacs.git] / src / w32.c
blobf8284f3e4cca06152b9e97c3defe75f46df198f5
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <float.h> /* for DBL_EPSILON */
29 #include <io.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <sys/file.h>
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
36 #include <sys/time.h>
37 #include <sys/utime.h>
38 #include <math.h>
40 /* must include CRT headers *before* config.h */
42 #include <config.h>
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
45 #undef access
46 #undef chdir
47 #undef chmod
48 #undef creat
49 #undef ctime
50 #undef fopen
51 #undef link
52 #undef mkdir
53 #undef open
54 #undef rename
55 #undef rmdir
56 #undef unlink
58 #undef close
59 #undef dup
60 #undef dup2
61 #undef pipe
62 #undef read
63 #undef write
65 #undef strerror
67 #undef localtime
69 #include "lisp.h"
70 #include "epaths.h" /* for SHELL */
72 #include <pwd.h>
73 #include <grp.h>
75 /* MinGW64 defines these in its _mingw.h. */
76 #if defined(__GNUC__) && !defined(MINGW_W64)
77 #define _ANONYMOUS_UNION
78 #define _ANONYMOUS_STRUCT
79 #endif
80 #include <windows.h>
81 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
82 use a different name to avoid compilation problems. */
83 typedef struct _MEMORY_STATUS_EX {
84 DWORD dwLength;
85 DWORD dwMemoryLoad;
86 DWORDLONG ullTotalPhys;
87 DWORDLONG ullAvailPhys;
88 DWORDLONG ullTotalPageFile;
89 DWORDLONG ullAvailPageFile;
90 DWORDLONG ullTotalVirtual;
91 DWORDLONG ullAvailVirtual;
92 DWORDLONG ullAvailExtendedVirtual;
93 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
95 /* These are here so that GDB would know about these data types. This
96 allows to attach GDB to Emacs when a fatal exception is triggered
97 and Windows pops up the "application needs to be closed" dialog.
98 At that point, _gnu_exception_handler, the top-level exception
99 handler installed by the MinGW startup code, is somewhere on the
100 call-stack of the main thread, so going to that call frame and
101 looking at the argument to _gnu_exception_handler, which is a
102 PEXCEPTION_POINTERS pointer, can reveal the exception code
103 (excptr->ExceptionRecord->ExceptionCode) and the address where the
104 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
105 well as some additional information specific to the exception. */
106 PEXCEPTION_POINTERS excptr;
107 PEXCEPTION_RECORD excprec;
108 PCONTEXT ctxrec;
110 #include <lmcons.h>
111 #include <shlobj.h>
113 #include <tlhelp32.h>
114 #include <psapi.h>
115 #ifndef _MSC_VER
116 #include <w32api.h>
117 #endif
118 #if _WIN32_WINNT < 0x0500
119 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
120 /* This either is not in psapi.h or guarded by higher value of
121 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
122 defines it in psapi.h */
123 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
124 DWORD cb;
125 DWORD PageFaultCount;
126 SIZE_T PeakWorkingSetSize;
127 SIZE_T WorkingSetSize;
128 SIZE_T QuotaPeakPagedPoolUsage;
129 SIZE_T QuotaPagedPoolUsage;
130 SIZE_T QuotaPeakNonPagedPoolUsage;
131 SIZE_T QuotaNonPagedPoolUsage;
132 SIZE_T PagefileUsage;
133 SIZE_T PeakPagefileUsage;
134 SIZE_T PrivateUsage;
135 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
136 #endif
137 #endif
139 #include <winioctl.h>
140 #include <aclapi.h>
141 #include <sddl.h>
143 #include <sys/acl.h>
144 #include <acl.h>
146 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
147 define them by hand if not already defined. */
148 #ifndef SDDL_REVISION_1
149 #define SDDL_REVISION_1 1
150 #endif /* SDDL_REVISION_1 */
152 #if defined(_MSC_VER) || defined(MINGW_W64)
153 /* MSVC and MinGW64 don't provide the definition of
154 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
155 which cannot be included because it triggers conflicts with other
156 Windows API headers. So we define it here by hand. */
158 typedef struct _REPARSE_DATA_BUFFER {
159 ULONG ReparseTag;
160 USHORT ReparseDataLength;
161 USHORT Reserved;
162 union {
163 struct {
164 USHORT SubstituteNameOffset;
165 USHORT SubstituteNameLength;
166 USHORT PrintNameOffset;
167 USHORT PrintNameLength;
168 ULONG Flags;
169 WCHAR PathBuffer[1];
170 } SymbolicLinkReparseBuffer;
171 struct {
172 USHORT SubstituteNameOffset;
173 USHORT SubstituteNameLength;
174 USHORT PrintNameOffset;
175 USHORT PrintNameLength;
176 WCHAR PathBuffer[1];
177 } MountPointReparseBuffer;
178 struct {
179 UCHAR DataBuffer[1];
180 } GenericReparseBuffer;
181 } DUMMYUNIONNAME;
182 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
184 #ifndef FILE_DEVICE_FILE_SYSTEM
185 #define FILE_DEVICE_FILE_SYSTEM 9
186 #endif
187 #ifndef METHOD_BUFFERED
188 #define METHOD_BUFFERED 0
189 #endif
190 #ifndef FILE_ANY_ACCESS
191 #define FILE_ANY_ACCESS 0x00000000
192 #endif
193 #ifndef CTL_CODE
194 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
195 #endif
196 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
197 #ifndef FSCTL_GET_REPARSE_POINT
198 #define FSCTL_GET_REPARSE_POINT \
199 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
200 #endif
201 #endif
203 /* TCP connection support. */
204 #include <sys/socket.h>
205 #undef socket
206 #undef bind
207 #undef connect
208 #undef htons
209 #undef ntohs
210 #undef inet_addr
211 #undef gethostname
212 #undef gethostbyname
213 #undef getservbyname
214 #undef getpeername
215 #undef shutdown
216 #undef setsockopt
217 #undef listen
218 #undef getsockname
219 #undef accept
220 #undef recvfrom
221 #undef sendto
223 #include <iphlpapi.h> /* should be after winsock2.h */
225 #include "w32.h"
226 #include <dirent.h>
227 #include "w32common.h"
228 #include "w32heap.h"
229 #include "w32select.h"
230 #include "systime.h"
231 #include "dispextern.h" /* for xstrcasecmp */
232 #include "coding.h" /* for Vlocale_coding_system */
234 #include "careadlinkat.h"
235 #include "allocator.h"
237 /* For serial_configure and serial_open. */
238 #include "process.h"
240 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
241 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
243 Lisp_Object QCloaded_from;
245 void globals_of_w32 (void);
246 static DWORD get_rid (PSID);
247 static int is_symlink (const char *);
248 static char * chase_symlinks (const char *);
249 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
250 static int restore_privilege (TOKEN_PRIVILEGES *);
251 static BOOL WINAPI revert_to_self (void);
253 static int sys_access (const char *, int);
254 extern void *e_malloc (size_t);
255 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
256 struct timespec *, void *);
257 extern int sys_dup (int);
262 /* Initialization states.
264 WARNING: If you add any more such variables for additional APIs,
265 you MUST add initialization for them to globals_of_w32
266 below. This is because these variables might get set
267 to non-NULL values during dumping, but the dumped Emacs
268 cannot reuse those values, because it could be run on a
269 different version of the OS, where API addresses are
270 different. */
271 static BOOL g_b_init_is_windows_9x;
272 static BOOL g_b_init_open_process_token;
273 static BOOL g_b_init_get_token_information;
274 static BOOL g_b_init_lookup_account_sid;
275 static BOOL g_b_init_get_sid_sub_authority;
276 static BOOL g_b_init_get_sid_sub_authority_count;
277 static BOOL g_b_init_get_security_info;
278 static BOOL g_b_init_get_file_security_w;
279 static BOOL g_b_init_get_file_security_a;
280 static BOOL g_b_init_get_security_descriptor_owner;
281 static BOOL g_b_init_get_security_descriptor_group;
282 static BOOL g_b_init_is_valid_sid;
283 static BOOL g_b_init_create_toolhelp32_snapshot;
284 static BOOL g_b_init_process32_first;
285 static BOOL g_b_init_process32_next;
286 static BOOL g_b_init_open_thread_token;
287 static BOOL g_b_init_impersonate_self;
288 static BOOL g_b_init_revert_to_self;
289 static BOOL g_b_init_get_process_memory_info;
290 static BOOL g_b_init_get_process_working_set_size;
291 static BOOL g_b_init_global_memory_status;
292 static BOOL g_b_init_global_memory_status_ex;
293 static BOOL g_b_init_get_length_sid;
294 static BOOL g_b_init_equal_sid;
295 static BOOL g_b_init_copy_sid;
296 static BOOL g_b_init_get_native_system_info;
297 static BOOL g_b_init_get_system_times;
298 static BOOL g_b_init_create_symbolic_link_w;
299 static BOOL g_b_init_create_symbolic_link_a;
300 static BOOL g_b_init_get_security_descriptor_dacl;
301 static BOOL g_b_init_convert_sd_to_sddl;
302 static BOOL g_b_init_convert_sddl_to_sd;
303 static BOOL g_b_init_is_valid_security_descriptor;
304 static BOOL g_b_init_set_file_security_w;
305 static BOOL g_b_init_set_file_security_a;
306 static BOOL g_b_init_set_named_security_info_w;
307 static BOOL g_b_init_set_named_security_info_a;
308 static BOOL g_b_init_get_adapters_info;
311 BEGIN: Wrapper functions around OpenProcessToken
312 and other functions in advapi32.dll that are only
313 supported in Windows NT / 2k / XP
315 /* ** Function pointer typedefs ** */
316 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
317 HANDLE ProcessHandle,
318 DWORD DesiredAccess,
319 PHANDLE TokenHandle);
320 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
321 HANDLE TokenHandle,
322 TOKEN_INFORMATION_CLASS TokenInformationClass,
323 LPVOID TokenInformation,
324 DWORD TokenInformationLength,
325 PDWORD ReturnLength);
326 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
327 HANDLE process_handle,
328 LPFILETIME creation_time,
329 LPFILETIME exit_time,
330 LPFILETIME kernel_time,
331 LPFILETIME user_time);
333 GetProcessTimes_Proc get_process_times_fn = NULL;
335 #ifdef _UNICODE
336 const char * const LookupAccountSid_Name = "LookupAccountSidW";
337 #else
338 const char * const LookupAccountSid_Name = "LookupAccountSidA";
339 #endif
340 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
341 LPCTSTR lpSystemName,
342 PSID Sid,
343 LPTSTR Name,
344 LPDWORD cbName,
345 LPTSTR DomainName,
346 LPDWORD cbDomainName,
347 PSID_NAME_USE peUse);
348 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
349 PSID pSid,
350 DWORD n);
351 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
352 PSID pSid);
353 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
354 HANDLE handle,
355 SE_OBJECT_TYPE ObjectType,
356 SECURITY_INFORMATION SecurityInfo,
357 PSID *ppsidOwner,
358 PSID *ppsidGroup,
359 PACL *ppDacl,
360 PACL *ppSacl,
361 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
362 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
363 LPCWSTR lpFileName,
364 SECURITY_INFORMATION RequestedInformation,
365 PSECURITY_DESCRIPTOR pSecurityDescriptor,
366 DWORD nLength,
367 LPDWORD lpnLengthNeeded);
368 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
369 LPCSTR lpFileName,
370 SECURITY_INFORMATION RequestedInformation,
371 PSECURITY_DESCRIPTOR pSecurityDescriptor,
372 DWORD nLength,
373 LPDWORD lpnLengthNeeded);
374 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
375 LPCWSTR lpFileName,
376 SECURITY_INFORMATION SecurityInformation,
377 PSECURITY_DESCRIPTOR pSecurityDescriptor);
378 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
379 LPCSTR lpFileName,
380 SECURITY_INFORMATION SecurityInformation,
381 PSECURITY_DESCRIPTOR pSecurityDescriptor);
382 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
383 LPCWSTR lpObjectName,
384 SE_OBJECT_TYPE ObjectType,
385 SECURITY_INFORMATION SecurityInformation,
386 PSID psidOwner,
387 PSID psidGroup,
388 PACL pDacl,
389 PACL pSacl);
390 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
391 LPCSTR lpObjectName,
392 SE_OBJECT_TYPE ObjectType,
393 SECURITY_INFORMATION SecurityInformation,
394 PSID psidOwner,
395 PSID psidGroup,
396 PACL pDacl,
397 PACL pSacl);
398 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
399 PSECURITY_DESCRIPTOR pSecurityDescriptor,
400 PSID *pOwner,
401 LPBOOL lpbOwnerDefaulted);
402 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
403 PSECURITY_DESCRIPTOR pSecurityDescriptor,
404 PSID *pGroup,
405 LPBOOL lpbGroupDefaulted);
406 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
407 PSECURITY_DESCRIPTOR pSecurityDescriptor,
408 LPBOOL lpbDaclPresent,
409 PACL *pDacl,
410 LPBOOL lpbDaclDefaulted);
411 typedef BOOL (WINAPI * IsValidSid_Proc) (
412 PSID sid);
413 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
414 DWORD dwFlags,
415 DWORD th32ProcessID);
416 typedef BOOL (WINAPI * Process32First_Proc) (
417 HANDLE hSnapshot,
418 LPPROCESSENTRY32 lppe);
419 typedef BOOL (WINAPI * Process32Next_Proc) (
420 HANDLE hSnapshot,
421 LPPROCESSENTRY32 lppe);
422 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
423 HANDLE ThreadHandle,
424 DWORD DesiredAccess,
425 BOOL OpenAsSelf,
426 PHANDLE TokenHandle);
427 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
428 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
429 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
430 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
431 HANDLE Process,
432 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
433 DWORD cb);
434 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
435 HANDLE hProcess,
436 PSIZE_T lpMinimumWorkingSetSize,
437 PSIZE_T lpMaximumWorkingSetSize);
438 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
439 LPMEMORYSTATUS lpBuffer);
440 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
441 LPMEMORY_STATUS_EX lpBuffer);
442 typedef BOOL (WINAPI * CopySid_Proc) (
443 DWORD nDestinationSidLength,
444 PSID pDestinationSid,
445 PSID pSourceSid);
446 typedef BOOL (WINAPI * EqualSid_Proc) (
447 PSID pSid1,
448 PSID pSid2);
449 typedef DWORD (WINAPI * GetLengthSid_Proc) (
450 PSID pSid);
451 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
452 LPSYSTEM_INFO lpSystemInfo);
453 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
454 LPFILETIME lpIdleTime,
455 LPFILETIME lpKernelTime,
456 LPFILETIME lpUserTime);
457 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
458 LPCWSTR lpSymlinkFileName,
459 LPCWSTR lpTargetFileName,
460 DWORD dwFlags);
461 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
462 LPCSTR lpSymlinkFileName,
463 LPCSTR lpTargetFileName,
464 DWORD dwFlags);
465 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
466 LPCTSTR StringSecurityDescriptor,
467 DWORD StringSDRevision,
468 PSECURITY_DESCRIPTOR *SecurityDescriptor,
469 PULONG SecurityDescriptorSize);
470 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
471 PSECURITY_DESCRIPTOR SecurityDescriptor,
472 DWORD RequestedStringSDRevision,
473 SECURITY_INFORMATION SecurityInformation,
474 LPTSTR *StringSecurityDescriptor,
475 PULONG StringSecurityDescriptorLen);
476 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
477 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
478 PIP_ADAPTER_INFO pAdapterInfo,
479 PULONG pOutBufLen);
481 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
482 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
484 /* ** A utility function ** */
485 static BOOL
486 is_windows_9x (void)
488 static BOOL s_b_ret = 0;
489 OSVERSIONINFO os_ver;
490 if (g_b_init_is_windows_9x == 0)
492 g_b_init_is_windows_9x = 1;
493 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
494 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
495 if (GetVersionEx (&os_ver))
497 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
500 return s_b_ret;
503 static Lisp_Object ltime (ULONGLONG);
505 /* Get total user and system times for get-internal-run-time.
506 Returns a list of integers if the times are provided by the OS
507 (NT derivatives), otherwise it returns the result of current-time. */
508 Lisp_Object
509 w32_get_internal_run_time (void)
511 if (get_process_times_fn)
513 FILETIME create, exit, kernel, user;
514 HANDLE proc = GetCurrentProcess ();
515 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
517 LARGE_INTEGER user_int, kernel_int, total;
518 user_int.LowPart = user.dwLowDateTime;
519 user_int.HighPart = user.dwHighDateTime;
520 kernel_int.LowPart = kernel.dwLowDateTime;
521 kernel_int.HighPart = kernel.dwHighDateTime;
522 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
523 return ltime (total.QuadPart);
527 return Fcurrent_time ();
530 /* ** The wrapper functions ** */
532 static BOOL WINAPI
533 open_process_token (HANDLE ProcessHandle,
534 DWORD DesiredAccess,
535 PHANDLE TokenHandle)
537 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
538 HMODULE hm_advapi32 = NULL;
539 if (is_windows_9x () == TRUE)
541 return FALSE;
543 if (g_b_init_open_process_token == 0)
545 g_b_init_open_process_token = 1;
546 hm_advapi32 = LoadLibrary ("Advapi32.dll");
547 s_pfn_Open_Process_Token =
548 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
550 if (s_pfn_Open_Process_Token == NULL)
552 return FALSE;
554 return (
555 s_pfn_Open_Process_Token (
556 ProcessHandle,
557 DesiredAccess,
558 TokenHandle)
562 static BOOL WINAPI
563 get_token_information (HANDLE TokenHandle,
564 TOKEN_INFORMATION_CLASS TokenInformationClass,
565 LPVOID TokenInformation,
566 DWORD TokenInformationLength,
567 PDWORD ReturnLength)
569 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
570 HMODULE hm_advapi32 = NULL;
571 if (is_windows_9x () == TRUE)
573 return FALSE;
575 if (g_b_init_get_token_information == 0)
577 g_b_init_get_token_information = 1;
578 hm_advapi32 = LoadLibrary ("Advapi32.dll");
579 s_pfn_Get_Token_Information =
580 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
582 if (s_pfn_Get_Token_Information == NULL)
584 return FALSE;
586 return (
587 s_pfn_Get_Token_Information (
588 TokenHandle,
589 TokenInformationClass,
590 TokenInformation,
591 TokenInformationLength,
592 ReturnLength)
596 static BOOL WINAPI
597 lookup_account_sid (LPCTSTR lpSystemName,
598 PSID Sid,
599 LPTSTR Name,
600 LPDWORD cbName,
601 LPTSTR DomainName,
602 LPDWORD cbDomainName,
603 PSID_NAME_USE peUse)
605 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
606 HMODULE hm_advapi32 = NULL;
607 if (is_windows_9x () == TRUE)
609 return FALSE;
611 if (g_b_init_lookup_account_sid == 0)
613 g_b_init_lookup_account_sid = 1;
614 hm_advapi32 = LoadLibrary ("Advapi32.dll");
615 s_pfn_Lookup_Account_Sid =
616 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
618 if (s_pfn_Lookup_Account_Sid == NULL)
620 return FALSE;
622 return (
623 s_pfn_Lookup_Account_Sid (
624 lpSystemName,
625 Sid,
626 Name,
627 cbName,
628 DomainName,
629 cbDomainName,
630 peUse)
634 static PDWORD WINAPI
635 get_sid_sub_authority (PSID pSid, DWORD n)
637 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
638 static DWORD zero = 0U;
639 HMODULE hm_advapi32 = NULL;
640 if (is_windows_9x () == TRUE)
642 return &zero;
644 if (g_b_init_get_sid_sub_authority == 0)
646 g_b_init_get_sid_sub_authority = 1;
647 hm_advapi32 = LoadLibrary ("Advapi32.dll");
648 s_pfn_Get_Sid_Sub_Authority =
649 (GetSidSubAuthority_Proc) GetProcAddress (
650 hm_advapi32, "GetSidSubAuthority");
652 if (s_pfn_Get_Sid_Sub_Authority == NULL)
654 return &zero;
656 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
659 static PUCHAR WINAPI
660 get_sid_sub_authority_count (PSID pSid)
662 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
663 static UCHAR zero = 0U;
664 HMODULE hm_advapi32 = NULL;
665 if (is_windows_9x () == TRUE)
667 return &zero;
669 if (g_b_init_get_sid_sub_authority_count == 0)
671 g_b_init_get_sid_sub_authority_count = 1;
672 hm_advapi32 = LoadLibrary ("Advapi32.dll");
673 s_pfn_Get_Sid_Sub_Authority_Count =
674 (GetSidSubAuthorityCount_Proc) GetProcAddress (
675 hm_advapi32, "GetSidSubAuthorityCount");
677 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
679 return &zero;
681 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
684 static DWORD WINAPI
685 get_security_info (HANDLE handle,
686 SE_OBJECT_TYPE ObjectType,
687 SECURITY_INFORMATION SecurityInfo,
688 PSID *ppsidOwner,
689 PSID *ppsidGroup,
690 PACL *ppDacl,
691 PACL *ppSacl,
692 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
694 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
695 HMODULE hm_advapi32 = NULL;
696 if (is_windows_9x () == TRUE)
698 return FALSE;
700 if (g_b_init_get_security_info == 0)
702 g_b_init_get_security_info = 1;
703 hm_advapi32 = LoadLibrary ("Advapi32.dll");
704 s_pfn_Get_Security_Info =
705 (GetSecurityInfo_Proc) GetProcAddress (
706 hm_advapi32, "GetSecurityInfo");
708 if (s_pfn_Get_Security_Info == NULL)
710 return FALSE;
712 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
713 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
714 ppSecurityDescriptor));
717 static BOOL WINAPI
718 get_file_security (const char *lpFileName,
719 SECURITY_INFORMATION RequestedInformation,
720 PSECURITY_DESCRIPTOR pSecurityDescriptor,
721 DWORD nLength,
722 LPDWORD lpnLengthNeeded)
724 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
725 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
726 HMODULE hm_advapi32 = NULL;
727 if (is_windows_9x () == TRUE)
729 errno = ENOTSUP;
730 return FALSE;
732 if (w32_unicode_filenames)
734 wchar_t filename_w[MAX_PATH];
736 if (g_b_init_get_file_security_w == 0)
738 g_b_init_get_file_security_w = 1;
739 hm_advapi32 = LoadLibrary ("Advapi32.dll");
740 s_pfn_Get_File_SecurityW =
741 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
742 "GetFileSecurityW");
744 if (s_pfn_Get_File_SecurityW == NULL)
746 errno = ENOTSUP;
747 return FALSE;
749 filename_to_utf16 (lpFileName, filename_w);
750 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
751 pSecurityDescriptor, nLength,
752 lpnLengthNeeded));
754 else
756 char filename_a[MAX_PATH];
758 if (g_b_init_get_file_security_a == 0)
760 g_b_init_get_file_security_a = 1;
761 hm_advapi32 = LoadLibrary ("Advapi32.dll");
762 s_pfn_Get_File_SecurityA =
763 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
764 "GetFileSecurityA");
766 if (s_pfn_Get_File_SecurityA == NULL)
768 errno = ENOTSUP;
769 return FALSE;
771 filename_to_ansi (lpFileName, filename_a);
772 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
773 pSecurityDescriptor, nLength,
774 lpnLengthNeeded));
778 static BOOL WINAPI
779 set_file_security (const char *lpFileName,
780 SECURITY_INFORMATION SecurityInformation,
781 PSECURITY_DESCRIPTOR pSecurityDescriptor)
783 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
784 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
785 HMODULE hm_advapi32 = NULL;
786 if (is_windows_9x () == TRUE)
788 errno = ENOTSUP;
789 return FALSE;
791 if (w32_unicode_filenames)
793 wchar_t filename_w[MAX_PATH];
795 if (g_b_init_set_file_security_w == 0)
797 g_b_init_set_file_security_w = 1;
798 hm_advapi32 = LoadLibrary ("Advapi32.dll");
799 s_pfn_Set_File_SecurityW =
800 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
801 "SetFileSecurityW");
803 if (s_pfn_Set_File_SecurityW == NULL)
805 errno = ENOTSUP;
806 return FALSE;
808 filename_to_utf16 (lpFileName, filename_w);
809 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
810 pSecurityDescriptor));
812 else
814 char filename_a[MAX_PATH];
816 if (g_b_init_set_file_security_a == 0)
818 g_b_init_set_file_security_a = 1;
819 hm_advapi32 = LoadLibrary ("Advapi32.dll");
820 s_pfn_Set_File_SecurityA =
821 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
822 "SetFileSecurityA");
824 if (s_pfn_Set_File_SecurityA == NULL)
826 errno = ENOTSUP;
827 return FALSE;
829 filename_to_ansi (lpFileName, filename_a);
830 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
831 pSecurityDescriptor));
835 static DWORD WINAPI
836 set_named_security_info (LPCTSTR lpObjectName,
837 SE_OBJECT_TYPE ObjectType,
838 SECURITY_INFORMATION SecurityInformation,
839 PSID psidOwner,
840 PSID psidGroup,
841 PACL pDacl,
842 PACL pSacl)
844 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
845 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
846 HMODULE hm_advapi32 = NULL;
847 if (is_windows_9x () == TRUE)
849 errno = ENOTSUP;
850 return ENOTSUP;
852 if (w32_unicode_filenames)
854 wchar_t filename_w[MAX_PATH];
856 if (g_b_init_set_named_security_info_w == 0)
858 g_b_init_set_named_security_info_w = 1;
859 hm_advapi32 = LoadLibrary ("Advapi32.dll");
860 s_pfn_Set_Named_Security_InfoW =
861 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
862 "SetNamedSecurityInfoW");
864 if (s_pfn_Set_Named_Security_InfoW == NULL)
866 errno = ENOTSUP;
867 return ENOTSUP;
869 filename_to_utf16 (lpObjectName, filename_w);
870 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
871 SecurityInformation, psidOwner,
872 psidGroup, pDacl, pSacl));
874 else
876 char filename_a[MAX_PATH];
878 if (g_b_init_set_named_security_info_a == 0)
880 g_b_init_set_named_security_info_a = 1;
881 hm_advapi32 = LoadLibrary ("Advapi32.dll");
882 s_pfn_Set_Named_Security_InfoA =
883 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
884 "SetNamedSecurityInfoA");
886 if (s_pfn_Set_Named_Security_InfoA == NULL)
888 errno = ENOTSUP;
889 return ENOTSUP;
891 filename_to_ansi (lpObjectName, filename_a);
892 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
893 SecurityInformation, psidOwner,
894 psidGroup, pDacl, pSacl));
898 static BOOL WINAPI
899 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
900 PSID *pOwner,
901 LPBOOL lpbOwnerDefaulted)
903 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
904 HMODULE hm_advapi32 = NULL;
905 if (is_windows_9x () == TRUE)
907 errno = ENOTSUP;
908 return FALSE;
910 if (g_b_init_get_security_descriptor_owner == 0)
912 g_b_init_get_security_descriptor_owner = 1;
913 hm_advapi32 = LoadLibrary ("Advapi32.dll");
914 s_pfn_Get_Security_Descriptor_Owner =
915 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
916 hm_advapi32, "GetSecurityDescriptorOwner");
918 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
920 errno = ENOTSUP;
921 return FALSE;
923 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
924 lpbOwnerDefaulted));
927 static BOOL WINAPI
928 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
929 PSID *pGroup,
930 LPBOOL lpbGroupDefaulted)
932 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
933 HMODULE hm_advapi32 = NULL;
934 if (is_windows_9x () == TRUE)
936 errno = ENOTSUP;
937 return FALSE;
939 if (g_b_init_get_security_descriptor_group == 0)
941 g_b_init_get_security_descriptor_group = 1;
942 hm_advapi32 = LoadLibrary ("Advapi32.dll");
943 s_pfn_Get_Security_Descriptor_Group =
944 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
945 hm_advapi32, "GetSecurityDescriptorGroup");
947 if (s_pfn_Get_Security_Descriptor_Group == NULL)
949 errno = ENOTSUP;
950 return FALSE;
952 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
953 lpbGroupDefaulted));
956 static BOOL WINAPI
957 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
958 LPBOOL lpbDaclPresent,
959 PACL *pDacl,
960 LPBOOL lpbDaclDefaulted)
962 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
963 HMODULE hm_advapi32 = NULL;
964 if (is_windows_9x () == TRUE)
966 errno = ENOTSUP;
967 return FALSE;
969 if (g_b_init_get_security_descriptor_dacl == 0)
971 g_b_init_get_security_descriptor_dacl = 1;
972 hm_advapi32 = LoadLibrary ("Advapi32.dll");
973 s_pfn_Get_Security_Descriptor_Dacl =
974 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
975 hm_advapi32, "GetSecurityDescriptorDacl");
977 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
979 errno = ENOTSUP;
980 return FALSE;
982 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
983 lpbDaclPresent, pDacl,
984 lpbDaclDefaulted));
987 static BOOL WINAPI
988 is_valid_sid (PSID sid)
990 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
991 HMODULE hm_advapi32 = NULL;
992 if (is_windows_9x () == TRUE)
994 return FALSE;
996 if (g_b_init_is_valid_sid == 0)
998 g_b_init_is_valid_sid = 1;
999 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1000 s_pfn_Is_Valid_Sid =
1001 (IsValidSid_Proc) GetProcAddress (
1002 hm_advapi32, "IsValidSid");
1004 if (s_pfn_Is_Valid_Sid == NULL)
1006 return FALSE;
1008 return (s_pfn_Is_Valid_Sid (sid));
1011 static BOOL WINAPI
1012 equal_sid (PSID sid1, PSID sid2)
1014 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1015 HMODULE hm_advapi32 = NULL;
1016 if (is_windows_9x () == TRUE)
1018 return FALSE;
1020 if (g_b_init_equal_sid == 0)
1022 g_b_init_equal_sid = 1;
1023 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1024 s_pfn_Equal_Sid =
1025 (EqualSid_Proc) GetProcAddress (
1026 hm_advapi32, "EqualSid");
1028 if (s_pfn_Equal_Sid == NULL)
1030 return FALSE;
1032 return (s_pfn_Equal_Sid (sid1, sid2));
1035 static DWORD WINAPI
1036 get_length_sid (PSID sid)
1038 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1039 HMODULE hm_advapi32 = NULL;
1040 if (is_windows_9x () == TRUE)
1042 return 0;
1044 if (g_b_init_get_length_sid == 0)
1046 g_b_init_get_length_sid = 1;
1047 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1048 s_pfn_Get_Length_Sid =
1049 (GetLengthSid_Proc) GetProcAddress (
1050 hm_advapi32, "GetLengthSid");
1052 if (s_pfn_Get_Length_Sid == NULL)
1054 return 0;
1056 return (s_pfn_Get_Length_Sid (sid));
1059 static BOOL WINAPI
1060 copy_sid (DWORD destlen, PSID dest, PSID src)
1062 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1063 HMODULE hm_advapi32 = NULL;
1064 if (is_windows_9x () == TRUE)
1066 return FALSE;
1068 if (g_b_init_copy_sid == 0)
1070 g_b_init_copy_sid = 1;
1071 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1072 s_pfn_Copy_Sid =
1073 (CopySid_Proc) GetProcAddress (
1074 hm_advapi32, "CopySid");
1076 if (s_pfn_Copy_Sid == NULL)
1078 return FALSE;
1080 return (s_pfn_Copy_Sid (destlen, dest, src));
1084 END: Wrapper functions around OpenProcessToken
1085 and other functions in advapi32.dll that are only
1086 supported in Windows NT / 2k / XP
1089 static void WINAPI
1090 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1092 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1093 if (is_windows_9x () != TRUE)
1095 if (g_b_init_get_native_system_info == 0)
1097 g_b_init_get_native_system_info = 1;
1098 s_pfn_Get_Native_System_Info =
1099 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1100 "GetNativeSystemInfo");
1102 if (s_pfn_Get_Native_System_Info != NULL)
1103 s_pfn_Get_Native_System_Info (lpSystemInfo);
1105 else
1106 lpSystemInfo->dwNumberOfProcessors = -1;
1109 static BOOL WINAPI
1110 get_system_times (LPFILETIME lpIdleTime,
1111 LPFILETIME lpKernelTime,
1112 LPFILETIME lpUserTime)
1114 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1115 if (is_windows_9x () == TRUE)
1117 return FALSE;
1119 if (g_b_init_get_system_times == 0)
1121 g_b_init_get_system_times = 1;
1122 s_pfn_Get_System_times =
1123 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1124 "GetSystemTimes");
1126 if (s_pfn_Get_System_times == NULL)
1127 return FALSE;
1128 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1131 static BOOLEAN WINAPI
1132 create_symbolic_link (LPCSTR lpSymlinkFilename,
1133 LPCSTR lpTargetFileName,
1134 DWORD dwFlags)
1136 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1137 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1138 BOOLEAN retval;
1140 if (is_windows_9x () == TRUE)
1142 errno = ENOSYS;
1143 return 0;
1145 if (w32_unicode_filenames)
1147 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1149 if (g_b_init_create_symbolic_link_w == 0)
1151 g_b_init_create_symbolic_link_w = 1;
1152 s_pfn_Create_Symbolic_LinkW =
1153 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1154 "CreateSymbolicLinkW");
1156 if (s_pfn_Create_Symbolic_LinkW == NULL)
1158 errno = ENOSYS;
1159 return 0;
1162 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1163 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1164 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1165 /* If we were denied creation of the symlink, try again after
1166 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1167 if (!retval)
1169 TOKEN_PRIVILEGES priv_current;
1171 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1172 &priv_current))
1174 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1175 restore_privilege (&priv_current);
1176 revert_to_self ();
1180 else
1182 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1184 if (g_b_init_create_symbolic_link_a == 0)
1186 g_b_init_create_symbolic_link_a = 1;
1187 s_pfn_Create_Symbolic_LinkA =
1188 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1189 "CreateSymbolicLinkA");
1191 if (s_pfn_Create_Symbolic_LinkA == NULL)
1193 errno = ENOSYS;
1194 return 0;
1197 filename_to_ansi (lpSymlinkFilename, symfn_a);
1198 filename_to_ansi (lpTargetFileName, tgtfn_a);
1199 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1200 /* If we were denied creation of the symlink, try again after
1201 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1202 if (!retval)
1204 TOKEN_PRIVILEGES priv_current;
1206 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1207 &priv_current))
1209 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1210 restore_privilege (&priv_current);
1211 revert_to_self ();
1215 return retval;
1218 static BOOL WINAPI
1219 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1221 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1223 if (is_windows_9x () == TRUE)
1225 errno = ENOTSUP;
1226 return FALSE;
1229 if (g_b_init_is_valid_security_descriptor == 0)
1231 g_b_init_is_valid_security_descriptor = 1;
1232 s_pfn_Is_Valid_Security_Descriptor_Proc =
1233 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1234 "IsValidSecurityDescriptor");
1236 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1238 errno = ENOTSUP;
1239 return FALSE;
1242 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1245 static BOOL WINAPI
1246 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1247 DWORD RequestedStringSDRevision,
1248 SECURITY_INFORMATION SecurityInformation,
1249 LPTSTR *StringSecurityDescriptor,
1250 PULONG StringSecurityDescriptorLen)
1252 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1253 BOOL retval;
1255 if (is_windows_9x () == TRUE)
1257 errno = ENOTSUP;
1258 return FALSE;
1261 if (g_b_init_convert_sd_to_sddl == 0)
1263 g_b_init_convert_sd_to_sddl = 1;
1264 #ifdef _UNICODE
1265 s_pfn_Convert_SD_To_SDDL =
1266 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1267 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1268 #else
1269 s_pfn_Convert_SD_To_SDDL =
1270 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1271 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1272 #endif
1274 if (s_pfn_Convert_SD_To_SDDL == NULL)
1276 errno = ENOTSUP;
1277 return FALSE;
1280 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1281 RequestedStringSDRevision,
1282 SecurityInformation,
1283 StringSecurityDescriptor,
1284 StringSecurityDescriptorLen);
1286 return retval;
1289 static BOOL WINAPI
1290 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1291 DWORD StringSDRevision,
1292 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1293 PULONG SecurityDescriptorSize)
1295 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1296 BOOL retval;
1298 if (is_windows_9x () == TRUE)
1300 errno = ENOTSUP;
1301 return FALSE;
1304 if (g_b_init_convert_sddl_to_sd == 0)
1306 g_b_init_convert_sddl_to_sd = 1;
1307 #ifdef _UNICODE
1308 s_pfn_Convert_SDDL_To_SD =
1309 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1310 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1311 #else
1312 s_pfn_Convert_SDDL_To_SD =
1313 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1314 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1315 #endif
1317 if (s_pfn_Convert_SDDL_To_SD == NULL)
1319 errno = ENOTSUP;
1320 return FALSE;
1323 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1324 StringSDRevision,
1325 SecurityDescriptor,
1326 SecurityDescriptorSize);
1328 return retval;
1331 static DWORD WINAPI
1332 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1334 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1335 HMODULE hm_iphlpapi = NULL;
1337 if (is_windows_9x () == TRUE)
1338 return ERROR_NOT_SUPPORTED;
1340 if (g_b_init_get_adapters_info == 0)
1342 g_b_init_get_adapters_info = 1;
1343 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1344 if (hm_iphlpapi)
1345 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1346 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1348 if (s_pfn_Get_Adapters_Info == NULL)
1349 return ERROR_NOT_SUPPORTED;
1350 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1355 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1356 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1358 This is called from alloc.c:valid_pointer_p. */
1360 w32_valid_pointer_p (void *p, int size)
1362 SIZE_T done;
1363 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1365 if (h)
1367 unsigned char *buf = alloca (size);
1368 int retval = ReadProcessMemory (h, p, buf, size, &done);
1370 CloseHandle (h);
1371 return retval;
1373 else
1374 return -1;
1379 /* Here's an overview of how the Windows build supports file names
1380 that cannot be encoded by the current system codepage.
1382 From the POV of Lisp and layers of C code above the functions here,
1383 Emacs on Windows pretends that its file names are encoded in UTF-8;
1384 see encode_file and decode_file on coding.c. Any file name that is
1385 passed as a unibyte string to C functions defined here is assumed
1386 to be in UTF-8 encoding. Any file name returned by functions
1387 defined here must be in UTF-8 encoding, with only a few exceptions
1388 reserved for a couple of special cases. (Be sure to use
1389 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1390 as they can be much longer than MAX_PATH!)
1392 The UTF-8 encoded file names cannot be passed to system APIs, as
1393 Windows does not support that. Therefore, they are converted
1394 either to UTF-16 or to the ANSI codepage, depending on the value of
1395 w32-unicode-filenames, before calling any system APIs or CRT library
1396 functions. The default value of that variable is determined by the
1397 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1398 user can change that default (although I don't see why would she
1399 want to).
1401 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1402 filename_from_utf16, and filename_from_ansi, are the workhorses of
1403 these conversions. They rely on Windows native APIs
1404 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1405 functions from coding.c here, because they allocate memory, which
1406 is a bad idea on the level of libc, which is what the functions
1407 here emulate. (If you worry about performance due to constant
1408 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1409 it was measured to take only a few microseconds on a not-so-fast
1410 machine, and second, that's exactly what the ANSI APIs we used
1411 before did anyway, because they are just thin wrappers around the
1412 Unicode APIs.)
1414 The variables file-name-coding-system and default-file-name-coding-system
1415 still exist, but are actually used only when a file name needs to
1416 be converted to the ANSI codepage. This happens all the time when
1417 w32-unicode-filenames is nil, but can also happen from time to time
1418 when it is t. Otherwise, these variables have no effect on file-name
1419 encoding when w32-unicode-filenames is t; this is similar to
1420 selection-coding-system.
1422 This arrangement works very well, but it has a few gotchas and
1423 limitations:
1425 . Lisp code that encodes or decodes file names manually should
1426 normally use 'utf-8' as the coding-system on Windows,
1427 disregarding file-name-coding-system. This is a somewhat
1428 unpleasant consequence, but it cannot be avoided. Fortunately,
1429 very few Lisp packages need to do that.
1431 More generally, passing to library functions (e.g., fopen or
1432 opendir) file names already encoded in the ANSI codepage is
1433 explicitly *verboten*, as all those functions, as shadowed and
1434 emulated here, assume they will receive UTF-8 encoded file names.
1436 For the same reasons, no CRT function or Win32 API can be called
1437 directly in Emacs sources, without either converting the file
1438 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1439 some shadowing function defined here.
1441 . Environment variables stored in Vprocess_environment are encoded
1442 in the ANSI codepage, so if getenv/egetenv is used for a variable
1443 whose value is a file name or a list of directories, it needs to
1444 be converted to UTF-8, before it is used as argument to functions
1445 or decoded into a Lisp string.
1447 . File names passed to external libraries, like the image libraries
1448 and GnuTLS, need special handling. These libraries generally
1449 don't support UTF-16 or UTF-8 file names, so they must get file
1450 names encoded in the ANSI codepage. To facilitate using these
1451 libraries with file names that are not encodable in the ANSI
1452 codepage, use the function ansi_encode_filename, which will try
1453 to use the short 8+3 alias of a file name if that file name is
1454 not encodable in the ANSI codepage. See image.c and gnutls.c for
1455 examples of how this should be done.
1457 . Running subprocesses in non-ASCII directories and with non-ASCII
1458 file arguments is limited to the current codepage (even though
1459 Emacs is perfectly capable of finding an executable program file
1460 in a directory whose name cannot be encoded in the current
1461 codepage). This is because the command-line arguments are
1462 encoded _before_ they get to the w32-specific level, and the
1463 encoding is not known in advance (it doesn't have to be the
1464 current ANSI codepage), so w32proc.c functions cannot re-encode
1465 them in UTF-16. This should be fixed, but will also require
1466 changes in cmdproxy. The current limitation is not terribly bad
1467 anyway, since very few, if any, Windows console programs that are
1468 likely to be invoked by Emacs support UTF-16 encoded command
1469 lines.
1471 . For similar reasons, server.el and emacsclient are also limited
1472 to the current ANSI codepage for now.
1474 . Emacs itself can only handle command-line arguments encoded in
1475 the current codepage.
1477 . Turning on w32-unicode-filename on Windows 9X (if it at all
1478 works) requires UNICOWS.DLL, which is thus a requirement even in
1479 non-GUI sessions, something the we previously avoided. */
1483 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1484 codepage defined by file-name-coding-system. */
1486 /* Current codepage for encoding file names. */
1487 static int file_name_codepage;
1489 /* Produce a Windows ANSI codepage suitable for encoding file names.
1490 Return the information about that codepage in CP_INFO. */
1491 static int
1492 codepage_for_filenames (CPINFO *cp_info)
1494 /* A simple cache to avoid calling GetCPInfo every time we need to
1495 encode/decode a file name. The file-name encoding is not
1496 supposed to be changed too frequently, if ever. */
1497 static Lisp_Object last_file_name_encoding;
1498 static CPINFO cp;
1499 Lisp_Object current_encoding;
1501 current_encoding = Vfile_name_coding_system;
1502 if (NILP (current_encoding))
1503 current_encoding = Vdefault_file_name_coding_system;
1505 if (!EQ (last_file_name_encoding, current_encoding))
1507 /* Default to the current ANSI codepage. */
1508 file_name_codepage = w32_ansi_code_page;
1510 if (NILP (current_encoding))
1512 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1513 char *cp = NULL, *end;
1514 int cpnum;
1516 if (strncmp (cpname, "cp", 2) == 0)
1517 cp = cpname + 2;
1518 else if (strncmp (cpname, "windows-", 8) == 0)
1519 cp = cpname + 8;
1521 if (cp)
1523 end = cp;
1524 cpnum = strtol (cp, &end, 10);
1525 if (cpnum && *end == '\0' && end - cp >= 2)
1526 file_name_codepage = cpnum;
1530 if (!file_name_codepage)
1531 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1533 if (!GetCPInfo (file_name_codepage, &cp))
1535 file_name_codepage = CP_ACP;
1536 if (!GetCPInfo (file_name_codepage, &cp))
1537 emacs_abort ();
1540 if (cp_info)
1541 *cp_info = cp;
1543 return file_name_codepage;
1547 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1549 int result = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, fn_in, -1,
1550 fn_out, MAX_PATH);
1552 if (!result)
1554 DWORD err = GetLastError ();
1556 switch (err)
1558 case ERROR_INVALID_FLAGS:
1559 case ERROR_INVALID_PARAMETER:
1560 errno = EINVAL;
1561 break;
1562 case ERROR_INSUFFICIENT_BUFFER:
1563 case ERROR_NO_UNICODE_TRANSLATION:
1564 default:
1565 errno = ENOENT;
1566 break;
1568 return -1;
1570 return 0;
1574 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1576 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1577 fn_out, MAX_UTF8_PATH, NULL, NULL);
1579 if (!result)
1581 DWORD err = GetLastError ();
1583 switch (err)
1585 case ERROR_INVALID_FLAGS:
1586 case ERROR_INVALID_PARAMETER:
1587 errno = EINVAL;
1588 break;
1589 case ERROR_INSUFFICIENT_BUFFER:
1590 case ERROR_NO_UNICODE_TRANSLATION:
1591 default:
1592 errno = ENOENT;
1593 break;
1595 return -1;
1597 return 0;
1601 filename_to_ansi (const char *fn_in, char *fn_out)
1603 wchar_t fn_utf16[MAX_PATH];
1605 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1607 int result;
1608 int codepage = codepage_for_filenames (NULL);
1610 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1611 fn_out, MAX_PATH, NULL, NULL);
1612 if (!result)
1614 DWORD err = GetLastError ();
1616 switch (err)
1618 case ERROR_INVALID_FLAGS:
1619 case ERROR_INVALID_PARAMETER:
1620 errno = EINVAL;
1621 break;
1622 case ERROR_INSUFFICIENT_BUFFER:
1623 case ERROR_NO_UNICODE_TRANSLATION:
1624 default:
1625 errno = ENOENT;
1626 break;
1628 return -1;
1630 return 0;
1632 return -1;
1636 filename_from_ansi (const char *fn_in, char *fn_out)
1638 wchar_t fn_utf16[MAX_PATH];
1639 int codepage = codepage_for_filenames (NULL);
1640 int result = pMultiByteToWideChar (codepage, MB_ERR_INVALID_CHARS, fn_in, -1,
1641 fn_utf16, MAX_PATH);
1643 if (!result)
1645 DWORD err = GetLastError ();
1647 switch (err)
1649 case ERROR_INVALID_FLAGS:
1650 case ERROR_INVALID_PARAMETER:
1651 errno = EINVAL;
1652 break;
1653 case ERROR_INSUFFICIENT_BUFFER:
1654 case ERROR_NO_UNICODE_TRANSLATION:
1655 default:
1656 errno = ENOENT;
1657 break;
1659 return -1;
1661 return filename_from_utf16 (fn_utf16, fn_out);
1666 /* The directory where we started, in UTF-8. */
1667 static char startup_dir[MAX_UTF8_PATH];
1669 /* Get the current working directory. */
1670 char *
1671 getcwd (char *dir, int dirsize)
1673 if (!dirsize)
1675 errno = EINVAL;
1676 return NULL;
1678 if (dirsize <= strlen (startup_dir))
1680 errno = ERANGE;
1681 return NULL;
1683 #if 0
1684 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1685 return dir;
1686 return NULL;
1687 #else
1688 /* Emacs doesn't actually change directory itself, it stays in the
1689 same directory where it was started. */
1690 strcpy (dir, startup_dir);
1691 return dir;
1692 #endif
1695 /* Emulate getloadavg. */
1697 struct load_sample {
1698 time_t sample_time;
1699 ULONGLONG idle;
1700 ULONGLONG kernel;
1701 ULONGLONG user;
1704 /* Number of processors on this machine. */
1705 static unsigned num_of_processors;
1707 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1708 static struct load_sample samples[16*60];
1709 static int first_idx = -1, last_idx = -1;
1710 static int max_idx = sizeof (samples) / sizeof (samples[0]);
1712 static int
1713 buf_next (int from)
1715 int next_idx = from + 1;
1717 if (next_idx >= max_idx)
1718 next_idx = 0;
1720 return next_idx;
1723 static int
1724 buf_prev (int from)
1726 int prev_idx = from - 1;
1728 if (prev_idx < 0)
1729 prev_idx = max_idx - 1;
1731 return prev_idx;
1734 static void
1735 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1737 SYSTEM_INFO sysinfo;
1738 FILETIME ft_idle, ft_user, ft_kernel;
1740 /* Initialize the number of processors on this machine. */
1741 if (num_of_processors <= 0)
1743 get_native_system_info (&sysinfo);
1744 num_of_processors = sysinfo.dwNumberOfProcessors;
1745 if (num_of_processors <= 0)
1747 GetSystemInfo (&sysinfo);
1748 num_of_processors = sysinfo.dwNumberOfProcessors;
1750 if (num_of_processors <= 0)
1751 num_of_processors = 1;
1754 /* TODO: Take into account threads that are ready to run, by
1755 sampling the "\System\Processor Queue Length" performance
1756 counter. The code below accounts only for threads that are
1757 actually running. */
1759 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1761 ULARGE_INTEGER uidle, ukernel, uuser;
1763 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1764 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1765 memcpy (&uuser, &ft_user, sizeof (ft_user));
1766 *idle = uidle.QuadPart;
1767 *kernel = ukernel.QuadPart;
1768 *user = uuser.QuadPart;
1770 else
1772 *idle = 0;
1773 *kernel = 0;
1774 *user = 0;
1778 /* Produce the load average for a given time interval, using the
1779 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1780 1-minute, 5-minute, or 15-minute average, respectively. */
1781 static double
1782 getavg (int which)
1784 double retval = -1.0;
1785 double tdiff;
1786 int idx;
1787 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1788 time_t now = samples[last_idx].sample_time;
1790 if (first_idx != last_idx)
1792 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1794 tdiff = difftime (now, samples[idx].sample_time);
1795 if (tdiff >= span - 2*DBL_EPSILON*now)
1797 long double sys =
1798 samples[last_idx].kernel + samples[last_idx].user
1799 - (samples[idx].kernel + samples[idx].user);
1800 long double idl = samples[last_idx].idle - samples[idx].idle;
1802 retval = (1.0 - idl / sys) * num_of_processors;
1803 break;
1805 if (idx == first_idx)
1806 break;
1810 return retval;
1814 getloadavg (double loadavg[], int nelem)
1816 int elem;
1817 ULONGLONG idle, kernel, user;
1818 time_t now = time (NULL);
1820 /* If system time jumped back for some reason, delete all samples
1821 whose time is later than the current wall-clock time. This
1822 prevents load average figures from becoming frozen for prolonged
1823 periods of time, when system time is reset backwards. */
1824 if (last_idx >= 0)
1826 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1828 if (last_idx == first_idx)
1830 first_idx = last_idx = -1;
1831 break;
1833 last_idx = buf_prev (last_idx);
1837 /* Store another sample. We ignore samples that are less than 1 sec
1838 apart. */
1839 if (last_idx < 0
1840 || (difftime (now, samples[last_idx].sample_time)
1841 >= 1.0 - 2*DBL_EPSILON*now))
1843 sample_system_load (&idle, &kernel, &user);
1844 last_idx = buf_next (last_idx);
1845 samples[last_idx].sample_time = now;
1846 samples[last_idx].idle = idle;
1847 samples[last_idx].kernel = kernel;
1848 samples[last_idx].user = user;
1849 /* If the buffer has more that 15 min worth of samples, discard
1850 the old ones. */
1851 if (first_idx == -1)
1852 first_idx = last_idx;
1853 while (first_idx != last_idx
1854 && (difftime (now, samples[first_idx].sample_time)
1855 >= 15.0*60 + 2*DBL_EPSILON*now))
1856 first_idx = buf_next (first_idx);
1859 for (elem = 0; elem < nelem; elem++)
1861 double avg = getavg (elem);
1863 if (avg < 0)
1864 break;
1865 loadavg[elem] = avg;
1868 return elem;
1871 /* Emulate getpwuid, getpwnam and others. */
1873 #define PASSWD_FIELD_SIZE 256
1875 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1876 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1877 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1878 static char dflt_passwd_dir[MAX_UTF8_PATH];
1879 static char dflt_passwd_shell[MAX_UTF8_PATH];
1881 static struct passwd dflt_passwd =
1883 dflt_passwd_name,
1884 dflt_passwd_passwd,
1888 dflt_passwd_gecos,
1889 dflt_passwd_dir,
1890 dflt_passwd_shell,
1893 static char dflt_group_name[GNLEN+1];
1895 static struct group dflt_group =
1897 /* When group information is not available, we return this as the
1898 group for all files. */
1899 dflt_group_name,
1903 unsigned
1904 getuid (void)
1906 return dflt_passwd.pw_uid;
1909 unsigned
1910 geteuid (void)
1912 /* I could imagine arguing for checking to see whether the user is
1913 in the Administrators group and returning a UID of 0 for that
1914 case, but I don't know how wise that would be in the long run. */
1915 return getuid ();
1918 unsigned
1919 getgid (void)
1921 return dflt_passwd.pw_gid;
1924 unsigned
1925 getegid (void)
1927 return getgid ();
1930 struct passwd *
1931 getpwuid (unsigned uid)
1933 if (uid == dflt_passwd.pw_uid)
1934 return &dflt_passwd;
1935 return NULL;
1938 struct group *
1939 getgrgid (gid_t gid)
1941 return &dflt_group;
1944 struct passwd *
1945 getpwnam (char *name)
1947 struct passwd *pw;
1949 pw = getpwuid (getuid ());
1950 if (!pw)
1951 return pw;
1953 if (xstrcasecmp (name, pw->pw_name))
1954 return NULL;
1956 return pw;
1959 static void
1960 init_user_info (void)
1962 /* Find the user's real name by opening the process token and
1963 looking up the name associated with the user-sid in that token.
1965 Use the relative portion of the identifier authority value from
1966 the user-sid as the user id value (same for group id using the
1967 primary group sid from the process token). */
1969 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1970 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1971 DWORD glength = sizeof (gname);
1972 HANDLE token = NULL;
1973 SID_NAME_USE user_type;
1974 unsigned char *buf = NULL;
1975 DWORD blen = 0;
1976 TOKEN_USER user_token;
1977 TOKEN_PRIMARY_GROUP group_token;
1978 BOOL result;
1980 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1981 if (result)
1983 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1984 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1986 buf = xmalloc (blen);
1987 result = get_token_information (token, TokenUser,
1988 (LPVOID)buf, blen, &needed);
1989 if (result)
1991 memcpy (&user_token, buf, sizeof (user_token));
1992 result = lookup_account_sid (NULL, user_token.User.Sid,
1993 uname, &ulength,
1994 domain, &dlength, &user_type);
1997 else
1998 result = FALSE;
2000 if (result)
2002 strcpy (dflt_passwd.pw_name, uname);
2003 /* Determine a reasonable uid value. */
2004 if (xstrcasecmp ("administrator", uname) == 0)
2006 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2007 dflt_passwd.pw_gid = 513; /* well-known None gid */
2009 else
2011 /* Use the last sub-authority value of the RID, the relative
2012 portion of the SID, as user/group ID. */
2013 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2015 /* Get group id and name. */
2016 result = get_token_information (token, TokenPrimaryGroup,
2017 (LPVOID)buf, blen, &needed);
2018 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2020 buf = xrealloc (buf, blen = needed);
2021 result = get_token_information (token, TokenPrimaryGroup,
2022 (LPVOID)buf, blen, &needed);
2024 if (result)
2026 memcpy (&group_token, buf, sizeof (group_token));
2027 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2028 dlength = sizeof (domain);
2029 /* If we can get at the real Primary Group name, use that.
2030 Otherwise, the default group name was already set to
2031 "None" in globals_of_w32. */
2032 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2033 gname, &glength, NULL, &dlength,
2034 &user_type))
2035 strcpy (dflt_group_name, gname);
2037 else
2038 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2041 /* If security calls are not supported (presumably because we
2042 are running under Windows 9X), fallback to this: */
2043 else if (GetUserName (uname, &ulength))
2045 strcpy (dflt_passwd.pw_name, uname);
2046 if (xstrcasecmp ("administrator", uname) == 0)
2047 dflt_passwd.pw_uid = 0;
2048 else
2049 dflt_passwd.pw_uid = 123;
2050 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2052 else
2054 strcpy (dflt_passwd.pw_name, "unknown");
2055 dflt_passwd.pw_uid = 123;
2056 dflt_passwd.pw_gid = 123;
2058 dflt_group.gr_gid = dflt_passwd.pw_gid;
2060 /* Set dir and shell from environment variables. */
2061 if (w32_unicode_filenames)
2063 wchar_t *home = _wgetenv (L"HOME");
2064 wchar_t *shell = _wgetenv (L"SHELL");
2066 /* Ensure HOME and SHELL are defined. */
2067 if (home == NULL)
2068 emacs_abort ();
2069 if (shell == NULL)
2070 emacs_abort ();
2071 filename_from_utf16 (home, dflt_passwd.pw_dir);
2072 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2074 else
2076 char *home = getenv ("HOME");
2077 char *shell = getenv ("SHELL");
2079 if (home == NULL)
2080 emacs_abort ();
2081 if (shell == NULL)
2082 emacs_abort ();
2083 filename_from_ansi (home, dflt_passwd.pw_dir);
2084 filename_from_ansi (shell, dflt_passwd.pw_shell);
2087 xfree (buf);
2088 if (token)
2089 CloseHandle (token);
2093 random (void)
2095 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2096 return ((rand () << 15) | rand ());
2099 void
2100 srandom (int seed)
2102 srand (seed);
2105 /* Return the maximum length in bytes of a multibyte character
2106 sequence encoded in the current ANSI codepage. This is required to
2107 correctly walk the encoded file names one character at a time. */
2108 static int
2109 max_filename_mbslen (void)
2111 CPINFO cp_info;
2113 codepage_for_filenames (&cp_info);
2114 return cp_info.MaxCharSize;
2117 /* Normalize filename by converting in-place all of its path
2118 separators to the separator specified by PATH_SEP. */
2120 static void
2121 normalize_filename (register char *fp, char path_sep)
2123 char *p2;
2125 /* Always lower-case drive letters a-z, even if the filesystem
2126 preserves case in filenames.
2127 This is so filenames can be compared by string comparison
2128 functions that are case-sensitive. Even case-preserving filesystems
2129 do not distinguish case in drive letters. */
2130 p2 = fp + 1;
2132 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2134 *fp += 'a' - 'A';
2135 fp += 2;
2138 while (*fp)
2140 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2141 *fp = path_sep;
2142 fp++;
2146 /* Destructively turn backslashes into slashes. */
2147 void
2148 dostounix_filename (register char *p)
2150 normalize_filename (p, '/');
2153 /* Destructively turn slashes into backslashes. */
2154 void
2155 unixtodos_filename (register char *p)
2157 normalize_filename (p, '\\');
2160 /* Remove all CR's that are followed by a LF.
2161 (From msdos.c...probably should figure out a way to share it,
2162 although this code isn't going to ever change.) */
2163 static int
2164 crlf_to_lf (register int n, register unsigned char *buf)
2166 unsigned char *np = buf;
2167 unsigned char *startp = buf;
2168 unsigned char *endp = buf + n;
2170 if (n == 0)
2171 return n;
2172 while (buf < endp - 1)
2174 if (*buf == 0x0d)
2176 if (*(++buf) != 0x0a)
2177 *np++ = 0x0d;
2179 else
2180 *np++ = *buf++;
2182 if (buf < endp)
2183 *np++ = *buf++;
2184 return np - startp;
2187 /* Parse the root part of file name, if present. Return length and
2188 optionally store pointer to char after root. */
2189 static int
2190 parse_root (const char * name, const char ** pPath)
2192 const char * start = name;
2194 if (name == NULL)
2195 return 0;
2197 /* find the root name of the volume if given */
2198 if (isalpha (name[0]) && name[1] == ':')
2200 /* skip past drive specifier */
2201 name += 2;
2202 if (IS_DIRECTORY_SEP (name[0]))
2203 name++;
2205 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2207 int slashes = 2;
2209 name += 2;
2212 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2213 break;
2214 name++;
2216 while ( *name );
2217 if (IS_DIRECTORY_SEP (name[0]))
2218 name++;
2221 if (pPath)
2222 *pPath = name;
2224 return name - start;
2227 /* Get long base name for name; name is assumed to be absolute. */
2228 static int
2229 get_long_basename (char * name, char * buf, int size)
2231 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2232 char fname_utf8[MAX_UTF8_PATH];
2233 int len = 0;
2234 int cstatus = -1;
2236 /* Must be valid filename, no wild cards or other invalid characters. */
2237 if (strpbrk (name, "*?|<>\""))
2238 return 0;
2240 if (w32_unicode_filenames)
2242 wchar_t fname_utf16[MAX_PATH];
2243 WIN32_FIND_DATAW find_data_wide;
2245 filename_to_utf16 (name, fname_utf16);
2246 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2247 if (dir_handle != INVALID_HANDLE_VALUE)
2248 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2250 else
2252 char fname_ansi[MAX_PATH];
2253 WIN32_FIND_DATAA find_data_ansi;
2255 filename_to_ansi (name, fname_ansi);
2256 /* If the ANSI name includes ? characters, it is not encodable
2257 in the ANSI codepage. In that case, we deliver the question
2258 marks to the caller; calling FindFirstFileA in this case
2259 could return some unrelated file name in the same
2260 directory. */
2261 if (_mbspbrk (fname_ansi, "?"))
2263 /* Find the basename of fname_ansi. */
2264 char *p = strrchr (fname_ansi, '\\');
2266 if (!p)
2267 p = fname_ansi;
2268 else
2269 p++;
2270 cstatus = filename_from_ansi (p, fname_utf8);
2272 else
2274 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2275 if (dir_handle != INVALID_HANDLE_VALUE)
2276 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2280 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2281 memcpy (buf, fname_utf8, len + 1);
2282 else
2283 len = 0;
2285 if (dir_handle != INVALID_HANDLE_VALUE)
2286 FindClose (dir_handle);
2288 return len;
2291 /* Get long name for file, if possible (assumed to be absolute). */
2292 BOOL
2293 w32_get_long_filename (char * name, char * buf, int size)
2295 char * o = buf;
2296 char * p;
2297 const char * q;
2298 char full[ MAX_UTF8_PATH ];
2299 int len;
2301 len = strlen (name);
2302 if (len >= MAX_UTF8_PATH)
2303 return FALSE;
2305 /* Use local copy for destructive modification. */
2306 memcpy (full, name, len+1);
2307 unixtodos_filename (full);
2309 /* Copy root part verbatim. */
2310 len = parse_root (full, (const char **)&p);
2311 memcpy (o, full, len);
2312 o += len;
2313 *o = '\0';
2314 size -= len;
2316 while (p != NULL && *p)
2318 q = p;
2319 p = strchr (q, '\\');
2320 if (p) *p = '\0';
2321 len = get_long_basename (full, o, size);
2322 if (len > 0)
2324 o += len;
2325 size -= len;
2326 if (p != NULL)
2328 *p++ = '\\';
2329 if (size < 2)
2330 return FALSE;
2331 *o++ = '\\';
2332 size--;
2333 *o = '\0';
2336 else
2337 return FALSE;
2340 return TRUE;
2343 unsigned int
2344 w32_get_short_filename (char * name, char * buf, int size)
2346 if (w32_unicode_filenames)
2348 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2349 unsigned int retval;
2351 filename_to_utf16 (name, name_utf16);
2352 retval = GetShortPathNameW (name_utf16, short_name, size);
2353 if (retval && retval < size)
2354 filename_from_utf16 (short_name, buf);
2355 return retval;
2357 else
2359 char name_ansi[MAX_PATH];
2361 filename_to_ansi (name, name_ansi);
2362 return GetShortPathNameA (name_ansi, buf, size);
2366 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2367 MS-Windows ANSI codepage. If FILENAME includes characters not
2368 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2369 if it exists. This is needed because the w32 build wants to
2370 support file names outside of the system locale, but image
2371 libraries typically don't support wide (a.k.a. "Unicode") APIs
2372 required for that. */
2374 Lisp_Object
2375 ansi_encode_filename (Lisp_Object filename)
2377 Lisp_Object encoded_filename;
2378 char fname[MAX_PATH];
2380 filename_to_ansi (SSDATA (filename), fname);
2381 if (_mbspbrk (fname, "?"))
2383 char shortname[MAX_PATH];
2385 if (w32_get_short_filename (SDATA (filename), shortname, MAX_PATH))
2387 dostounix_filename (shortname);
2388 encoded_filename = build_string (shortname);
2390 else
2391 encoded_filename = build_unibyte_string (fname);
2393 else
2394 encoded_filename = build_unibyte_string (fname);
2395 return encoded_filename;
2398 static int
2399 is_unc_volume (const char *filename)
2401 const char *ptr = filename;
2403 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2404 return 0;
2406 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2407 return 0;
2409 return 1;
2412 /* Emulate the Posix unsetenv. */
2414 unsetenv (const char *name)
2416 char *var;
2417 size_t name_len;
2418 int retval;
2420 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2422 errno = EINVAL;
2423 return -1;
2425 name_len = strlen (name);
2426 /* MS docs says an environment variable cannot be longer than 32K. */
2427 if (name_len > 32767)
2429 errno = ENOMEM;
2430 return 0;
2432 /* It is safe to use 'alloca' with 32K size, since the stack is at
2433 least 2MB, and we set it to 8MB in the link command line. */
2434 var = alloca (name_len + 2);
2435 strncpy (var, name, name_len);
2436 var[name_len++] = '=';
2437 var[name_len] = '\0';
2438 return _putenv (var);
2441 /* MS _putenv doesn't support removing a variable when the argument
2442 does not include the '=' character, so we fix that here. */
2444 sys_putenv (char *str)
2446 const char *const name_end = strchr (str, '=');
2448 if (name_end == NULL)
2450 /* Remove the variable from the environment. */
2451 return unsetenv (str);
2454 return _putenv (str);
2457 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2459 LPBYTE
2460 w32_get_resource (char *key, LPDWORD lpdwtype)
2462 LPBYTE lpvalue;
2463 HKEY hrootkey = NULL;
2464 DWORD cbData;
2466 /* Check both the current user and the local machine to see if
2467 we have any resources. */
2469 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2471 lpvalue = NULL;
2473 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2474 && (lpvalue = xmalloc (cbData)) != NULL
2475 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2477 RegCloseKey (hrootkey);
2478 return (lpvalue);
2481 xfree (lpvalue);
2483 RegCloseKey (hrootkey);
2486 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2488 lpvalue = NULL;
2490 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2491 && (lpvalue = xmalloc (cbData)) != NULL
2492 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2494 RegCloseKey (hrootkey);
2495 return (lpvalue);
2498 xfree (lpvalue);
2500 RegCloseKey (hrootkey);
2503 return (NULL);
2506 /* The argv[] array holds ANSI-encoded strings, and so this function
2507 works with ANS_encoded strings. */
2508 void
2509 init_environment (char ** argv)
2511 static const char * const tempdirs[] = {
2512 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2515 int i;
2517 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
2519 /* Implementation note: This function explicitly works with ANSI
2520 file names, not with UTF-8 encoded file names. This is because
2521 this function pushes variables into the Emacs's environment, and
2522 the environment variables are always assumed to be in the
2523 locale-specific encoding. Do NOT call any functions that accept
2524 UTF-8 file names from this function! */
2526 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2527 temporary files and assume "/tmp" if $TMPDIR is unset, which
2528 will break on DOS/Windows. Refuse to work if we cannot find
2529 a directory, not even "c:/", usable for that purpose. */
2530 for (i = 0; i < imax ; i++)
2532 const char *tmp = tempdirs[i];
2534 if (*tmp == '$')
2535 tmp = getenv (tmp + 1);
2536 /* Note that `access' can lie to us if the directory resides on a
2537 read-only filesystem, like CD-ROM or a write-protected floppy.
2538 The only way to be really sure is to actually create a file and
2539 see if it succeeds. But I think that's too much to ask. */
2541 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2542 if (tmp && sys_access (tmp, D_OK) == 0)
2544 char * var = alloca (strlen (tmp) + 8);
2545 sprintf (var, "TMPDIR=%s", tmp);
2546 _putenv (strdup (var));
2547 break;
2550 if (i >= imax)
2551 cmd_error_internal
2552 (Fcons (Qerror,
2553 Fcons (build_string ("no usable temporary directories found!!"),
2554 Qnil)),
2555 "While setting TMPDIR: ");
2557 /* Check for environment variables and use registry settings if they
2558 don't exist. Fallback on default values where applicable. */
2560 int i;
2561 LPBYTE lpval;
2562 DWORD dwType;
2563 char locale_name[32];
2564 char default_home[MAX_PATH];
2565 int appdata = 0;
2567 static const struct env_entry
2569 char * name;
2570 char * def_value;
2571 } dflt_envvars[] =
2573 /* If the default value is NULL, we will use the value from the
2574 outside environment or the Registry, but will not push the
2575 variable into the Emacs environment if it is defined neither
2576 in the Registry nor in the outside environment. */
2577 {"HOME", "C:/"},
2578 {"PRELOAD_WINSOCK", NULL},
2579 {"emacs_dir", "C:/emacs"},
2580 {"EMACSLOADPATH", NULL},
2581 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2582 {"EMACSDATA", NULL},
2583 {"EMACSPATH", NULL},
2584 {"INFOPATH", NULL},
2585 {"EMACSDOC", NULL},
2586 {"TERM", "cmd"},
2587 {"LANG", NULL},
2590 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2592 /* We need to copy dflt_envvars[] and work on the copy because we
2593 don't want the dumped Emacs to inherit the values of
2594 environment variables we saw during dumping (which could be on
2595 a different system). The defaults above must be left intact. */
2596 struct env_entry env_vars[N_ENV_VARS];
2598 for (i = 0; i < N_ENV_VARS; i++)
2599 env_vars[i] = dflt_envvars[i];
2601 /* For backwards compatibility, check if a .emacs file exists in C:/
2602 If not, then we can try to default to the appdata directory under the
2603 user's profile, which is more likely to be writable. */
2604 if (sys_access ("C:/.emacs", F_OK) != 0)
2606 HRESULT profile_result;
2607 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2608 of Windows 95 and NT4 that have not been updated to include
2609 MSIE 5. */
2610 ShGetFolderPath_fn get_folder_path;
2611 get_folder_path = (ShGetFolderPath_fn)
2612 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2614 if (get_folder_path != NULL)
2616 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2617 0, default_home);
2619 /* If we can't get the appdata dir, revert to old behavior. */
2620 if (profile_result == S_OK)
2622 env_vars[0].def_value = default_home;
2623 appdata = 1;
2628 /* Get default locale info and use it for LANG. */
2629 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2630 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2631 locale_name, sizeof (locale_name)))
2633 for (i = 0; i < N_ENV_VARS; i++)
2635 if (strcmp (env_vars[i].name, "LANG") == 0)
2637 env_vars[i].def_value = locale_name;
2638 break;
2643 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2645 /* Treat emacs_dir specially: set it unconditionally based on our
2646 location. */
2648 char *p;
2649 char modname[MAX_PATH];
2651 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2652 emacs_abort ();
2653 if ((p = _mbsrchr (modname, '\\')) == NULL)
2654 emacs_abort ();
2655 *p = 0;
2657 if ((p = _mbsrchr (modname, '\\'))
2658 /* From bin means installed Emacs, from src means uninstalled. */
2659 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2661 char buf[SET_ENV_BUF_SIZE];
2662 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2664 *p = 0;
2665 for (p = modname; *p; p = CharNext (p))
2666 if (*p == '\\') *p = '/';
2668 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2669 _putenv (strdup (buf));
2670 /* If we are running from the Posix-like build tree, define
2671 SHELL to point to our own cmdproxy. The loop below will
2672 then disregard PATH_EXEC and the default value. */
2673 if (within_build_tree)
2675 _snprintf (buf, sizeof (buf) - 1,
2676 "SHELL=%s/nt/cmdproxy.exe", modname);
2677 _putenv (strdup (buf));
2682 for (i = 0; i < N_ENV_VARS; i++)
2684 if (!getenv (env_vars[i].name))
2686 int dont_free = 0;
2687 char bufc[SET_ENV_BUF_SIZE];
2689 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2690 /* Also ignore empty environment variables. */
2691 || *lpval == 0)
2693 xfree (lpval);
2694 dont_free = 1;
2695 if (strcmp (env_vars[i].name, "SHELL") == 0)
2697 /* Look for cmdproxy.exe in every directory in
2698 PATH_EXEC. FIXME: This does not find cmdproxy
2699 in nt/ when we run uninstalled. */
2700 char fname[MAX_PATH];
2701 const char *pstart = PATH_EXEC, *pend;
2703 do {
2704 pend = _mbschr (pstart, ';');
2705 if (!pend)
2706 pend = pstart + strlen (pstart);
2707 /* Be defensive against series of ;;; characters. */
2708 if (pend > pstart)
2710 strncpy (fname, pstart, pend - pstart);
2711 fname[pend - pstart] = '/';
2712 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2713 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2714 sizeof (bufc));
2715 if (sys_access (bufc, F_OK) == 0)
2717 lpval = bufc;
2718 dwType = REG_SZ;
2719 break;
2722 if (*pend)
2723 pstart = pend + 1;
2724 else
2725 pstart = pend;
2726 if (!*pstart)
2728 /* If not found in any directory, use the
2729 default as the last resort. */
2730 lpval = env_vars[i].def_value;
2731 dwType = REG_EXPAND_SZ;
2733 } while (*pstart);
2735 else
2737 lpval = env_vars[i].def_value;
2738 dwType = REG_EXPAND_SZ;
2740 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2741 Vdelayed_warnings_list
2742 = Fcons (listn (CONSTYPE_HEAP, 2,
2743 intern ("initialization"),
2744 build_string ("Setting HOME to C:\\ by default is deprecated")),
2745 Vdelayed_warnings_list);
2748 if (lpval)
2750 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2752 if (dwType == REG_EXPAND_SZ)
2753 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2754 else if (dwType == REG_SZ)
2755 strcpy (buf1, lpval);
2756 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2758 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2759 buf1);
2760 _putenv (strdup (buf2));
2763 if (!dont_free)
2764 xfree (lpval);
2770 /* Rebuild system configuration to reflect invoking system. */
2771 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2773 /* Another special case: on NT, the PATH variable is actually named
2774 "Path" although cmd.exe (perhaps NT itself) arranges for
2775 environment variable lookup and setting to be case insensitive.
2776 However, Emacs assumes a fully case sensitive environment, so we
2777 need to change "Path" to "PATH" to match the expectations of
2778 various elisp packages. We do this by the sneaky method of
2779 modifying the string in the C runtime environ entry.
2781 The same applies to COMSPEC. */
2783 char ** envp;
2785 for (envp = environ; *envp; envp++)
2786 if (_strnicmp (*envp, "PATH=", 5) == 0)
2787 memcpy (*envp, "PATH=", 5);
2788 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2789 memcpy (*envp, "COMSPEC=", 8);
2792 /* Remember the initial working directory for getcwd. */
2793 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2794 Does it matter anywhere in Emacs? */
2795 if (w32_unicode_filenames)
2797 wchar_t wstartup_dir[MAX_PATH];
2799 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2800 emacs_abort ();
2801 filename_from_utf16 (wstartup_dir, startup_dir);
2803 else
2805 char astartup_dir[MAX_PATH];
2807 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2808 emacs_abort ();
2809 filename_from_ansi (astartup_dir, startup_dir);
2813 static char modname[MAX_PATH];
2815 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2816 emacs_abort ();
2817 argv[0] = modname;
2820 /* Determine if there is a middle mouse button, to allow parse_button
2821 to decide whether right mouse events should be mouse-2 or
2822 mouse-3. */
2823 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2825 init_user_info ();
2828 /* Called from expand-file-name when default-directory is not a string. */
2830 char *
2831 emacs_root_dir (void)
2833 static char root_dir[MAX_UTF8_PATH];
2834 const char *p;
2836 p = getenv ("emacs_dir");
2837 if (p == NULL)
2838 emacs_abort ();
2839 filename_from_ansi (p, root_dir);
2840 root_dir[parse_root (root_dir, NULL)] = '\0';
2841 dostounix_filename (root_dir);
2842 return root_dir;
2845 #include <sys/timeb.h>
2847 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2849 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2851 struct _timeb tb;
2852 _ftime (&tb);
2854 tv->tv_sec = tb.time;
2855 tv->tv_usec = tb.millitm * 1000L;
2856 /* Implementation note: _ftime sometimes doesn't update the dstflag
2857 according to the new timezone when the system timezone is
2858 changed. We could fix that by using GetSystemTime and
2859 GetTimeZoneInformation, but that doesn't seem necessary, since
2860 Emacs always calls gettimeofday with the 2nd argument NULL (see
2861 current_emacs_time). */
2862 if (tz)
2864 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2865 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2867 return 0;
2870 /* Emulate fdutimens. */
2872 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2873 TIMESPEC[0] and TIMESPEC[1], respectively.
2874 FD must be either negative -- in which case it is ignored --
2875 or a file descriptor that is open on FILE.
2876 If FD is nonnegative, then FILE can be NULL, which means
2877 use just futimes instead of utimes.
2878 If TIMESPEC is null, FAIL.
2879 Return 0 on success, -1 (setting errno) on failure. */
2882 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2884 if (!timespec)
2886 errno = ENOSYS;
2887 return -1;
2889 if (fd < 0 && !file)
2891 errno = EBADF;
2892 return -1;
2894 /* _futime's prototype defines 2nd arg as having the type 'struct
2895 _utimbuf', while utime needs to accept 'struct utimbuf' for
2896 compatibility with Posix. So we need to use 2 different (but
2897 equivalent) types to avoid compiler warnings, sigh. */
2898 if (fd >= 0)
2900 struct _utimbuf _ut;
2902 _ut.actime = timespec[0].tv_sec;
2903 _ut.modtime = timespec[1].tv_sec;
2904 return _futime (fd, &_ut);
2906 else
2908 struct utimbuf ut;
2910 ut.actime = timespec[0].tv_sec;
2911 ut.modtime = timespec[1].tv_sec;
2912 /* Call 'utime', which is implemented below, not the MS library
2913 function, which fails on directories. */
2914 return utime (file, &ut);
2919 /* ------------------------------------------------------------------------- */
2920 /* IO support and wrapper functions for the Windows API. */
2921 /* ------------------------------------------------------------------------- */
2923 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2924 on network directories, so we handle that case here.
2925 (Ulrich Leodolter, 1/11/95). */
2926 char *
2927 sys_ctime (const time_t *t)
2929 char *str = (char *) ctime (t);
2930 return (str ? str : "Sun Jan 01 00:00:00 1970");
2933 /* Emulate sleep...we could have done this with a define, but that
2934 would necessitate including windows.h in the files that used it.
2935 This is much easier. */
2936 void
2937 sys_sleep (int seconds)
2939 Sleep (seconds * 1000);
2942 /* Internal MSVC functions for low-level descriptor munging */
2943 extern int __cdecl _set_osfhnd (int fd, long h);
2944 extern int __cdecl _free_osfhnd (int fd);
2946 /* parallel array of private info on file handles */
2947 filedesc fd_info [ MAXDESC ];
2949 typedef struct volume_info_data {
2950 struct volume_info_data * next;
2952 /* time when info was obtained */
2953 DWORD timestamp;
2955 /* actual volume info */
2956 char * root_dir;
2957 DWORD serialnum;
2958 DWORD maxcomp;
2959 DWORD flags;
2960 char * name;
2961 char * type;
2962 } volume_info_data;
2964 /* Global referenced by various functions. */
2965 static volume_info_data volume_info;
2967 /* Vector to indicate which drives are local and fixed (for which cached
2968 data never expires). */
2969 static BOOL fixed_drives[26];
2971 /* Consider cached volume information to be stale if older than 10s,
2972 at least for non-local drives. Info for fixed drives is never stale. */
2973 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2974 #define VOLINFO_STILL_VALID( root_dir, info ) \
2975 ( ( isalpha (root_dir[0]) && \
2976 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2977 || GetTickCount () - info->timestamp < 10000 )
2979 /* Cache support functions. */
2981 /* Simple linked list with linear search is sufficient. */
2982 static volume_info_data *volume_cache = NULL;
2984 static volume_info_data *
2985 lookup_volume_info (char * root_dir)
2987 volume_info_data * info;
2989 for (info = volume_cache; info; info = info->next)
2990 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2991 break;
2992 return info;
2995 static void
2996 add_volume_info (char * root_dir, volume_info_data * info)
2998 info->root_dir = xstrdup (root_dir);
2999 unixtodos_filename (info->root_dir);
3000 info->next = volume_cache;
3001 volume_cache = info;
3005 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3006 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3007 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3008 static volume_info_data *
3009 GetCachedVolumeInformation (char * root_dir)
3011 volume_info_data * info;
3012 char default_root[ MAX_UTF8_PATH ];
3013 char name[MAX_PATH+1];
3014 char type[MAX_PATH+1];
3016 /* NULL for root_dir means use root from current directory. */
3017 if (root_dir == NULL)
3019 if (w32_unicode_filenames)
3021 wchar_t curdirw[MAX_PATH];
3023 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3024 return NULL;
3025 filename_from_utf16 (curdirw, default_root);
3027 else
3029 char curdira[MAX_PATH];
3031 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3032 return NULL;
3033 filename_from_ansi (curdira, default_root);
3035 parse_root (default_root, (const char **)&root_dir);
3036 *root_dir = 0;
3037 root_dir = default_root;
3040 /* Local fixed drives can be cached permanently. Removable drives
3041 cannot be cached permanently, since the volume name and serial
3042 number (if nothing else) can change. Remote drives should be
3043 treated as if they are removable, since there is no sure way to
3044 tell whether they are or not. Also, the UNC association of drive
3045 letters mapped to remote volumes can be changed at any time (even
3046 by other processes) without notice.
3048 As a compromise, so we can benefit from caching info for remote
3049 volumes, we use a simple expiry mechanism to invalidate cache
3050 entries that are more than ten seconds old. */
3052 #if 0
3053 /* No point doing this, because WNetGetConnection is even slower than
3054 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3055 GetDriveType is about the only call of this type which does not
3056 involve network access, and so is extremely quick). */
3058 /* Map drive letter to UNC if remote. */
3059 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3061 char remote_name[ 256 ];
3062 char drive[3] = { root_dir[0], ':' };
3064 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3065 == NO_ERROR)
3066 /* do something */ ;
3068 #endif
3070 info = lookup_volume_info (root_dir);
3072 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3074 DWORD serialnum;
3075 DWORD maxcomp;
3076 DWORD flags;
3078 /* Info is not cached, or is stale. */
3079 if (w32_unicode_filenames)
3081 wchar_t root_w[MAX_PATH];
3082 wchar_t name_w[MAX_PATH+1];
3083 wchar_t type_w[MAX_PATH+1];
3085 filename_to_utf16 (root_dir, root_w);
3086 if (!GetVolumeInformationW (root_w,
3087 name_w, sizeof (name_w),
3088 &serialnum,
3089 &maxcomp,
3090 &flags,
3091 type_w, sizeof (type_w)))
3092 return NULL;
3093 /* Hmm... not really 100% correct, as these 2 are not file
3094 names... */
3095 filename_from_utf16 (name_w, name);
3096 filename_from_utf16 (type_w, type);
3098 else
3100 char root_a[MAX_PATH];
3101 char name_a[MAX_PATH+1];
3102 char type_a[MAX_PATH+1];
3104 filename_to_ansi (root_dir, root_a);
3105 if (!GetVolumeInformationA (root_a,
3106 name_a, sizeof (name_a),
3107 &serialnum,
3108 &maxcomp,
3109 &flags,
3110 type_a, sizeof (type_a)))
3111 return NULL;
3112 filename_from_ansi (name_a, name);
3113 filename_from_ansi (type_a, type);
3116 /* Cache the volume information for future use, overwriting existing
3117 entry if present. */
3118 if (info == NULL)
3120 info = xmalloc (sizeof (volume_info_data));
3121 add_volume_info (root_dir, info);
3123 else
3125 xfree (info->name);
3126 xfree (info->type);
3129 info->name = xstrdup (name);
3130 unixtodos_filename (info->name);
3131 info->serialnum = serialnum;
3132 info->maxcomp = maxcomp;
3133 info->flags = flags;
3134 info->type = xstrdup (type);
3135 info->timestamp = GetTickCount ();
3138 return info;
3141 /* Get information on the volume where NAME is held; set path pointer to
3142 start of pathname in NAME (past UNC header\volume header if present),
3143 if pPath is non-NULL.
3145 Note: if NAME includes symlinks, the information is for the volume
3146 of the symlink, not of its target. That's because, even though
3147 GetVolumeInformation returns information about the symlink target
3148 of its argument, we only pass the root directory to
3149 GetVolumeInformation, not the full NAME. */
3150 static int
3151 get_volume_info (const char * name, const char ** pPath)
3153 char temp[MAX_UTF8_PATH];
3154 char *rootname = NULL; /* default to current volume */
3155 volume_info_data * info;
3156 int root_len = parse_root (name, pPath);
3158 if (name == NULL)
3159 return FALSE;
3161 /* Copy the root name of the volume, if given. */
3162 if (root_len)
3164 strncpy (temp, name, root_len);
3165 temp[root_len] = '\0';
3166 unixtodos_filename (temp);
3167 rootname = temp;
3170 info = GetCachedVolumeInformation (rootname);
3171 if (info != NULL)
3173 /* Set global referenced by other functions. */
3174 volume_info = *info;
3175 return TRUE;
3177 return FALSE;
3180 /* Determine if volume is FAT format (ie. only supports short 8.3
3181 names); also set path pointer to start of pathname in name, if
3182 pPath is non-NULL. */
3183 static int
3184 is_fat_volume (const char * name, const char ** pPath)
3186 if (get_volume_info (name, pPath))
3187 return (volume_info.maxcomp == 12);
3188 return FALSE;
3191 /* Convert all slashes in a filename to backslashes, and map filename
3192 to a valid 8.3 name if necessary. The result is a pointer to a
3193 static buffer, so CAVEAT EMPTOR! */
3194 const char *
3195 map_w32_filename (const char * name, const char ** pPath)
3197 static char shortname[MAX_UTF8_PATH];
3198 char * str = shortname;
3199 char c;
3200 char * path;
3201 const char * save_name = name;
3203 if (strlen (name) >= sizeof (shortname))
3205 /* Return a filename which will cause callers to fail. */
3206 strcpy (shortname, "?");
3207 return shortname;
3210 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3212 register int left = 8; /* maximum number of chars in part */
3213 register int extn = 0; /* extension added? */
3214 register int dots = 2; /* maximum number of dots allowed */
3216 while (name < path)
3217 *str++ = *name++; /* skip past UNC header */
3219 while ((c = *name++))
3221 switch ( c )
3223 case ':':
3224 case '\\':
3225 case '/':
3226 *str++ = (c == ':' ? ':' : '\\');
3227 extn = 0; /* reset extension flags */
3228 dots = 2; /* max 2 dots */
3229 left = 8; /* max length 8 for main part */
3230 break;
3231 case '.':
3232 if ( dots )
3234 /* Convert path components of the form .xxx to _xxx,
3235 but leave . and .. as they are. This allows .emacs
3236 to be read as _emacs, for example. */
3238 if (! *name ||
3239 *name == '.' ||
3240 IS_DIRECTORY_SEP (*name))
3242 *str++ = '.';
3243 dots--;
3245 else
3247 *str++ = '_';
3248 left--;
3249 dots = 0;
3252 else if ( !extn )
3254 *str++ = '.';
3255 extn = 1; /* we've got an extension */
3256 left = 3; /* 3 chars in extension */
3258 else
3260 /* any embedded dots after the first are converted to _ */
3261 *str++ = '_';
3263 break;
3264 case '~':
3265 case '#': /* don't lose these, they're important */
3266 if ( ! left )
3267 str[-1] = c; /* replace last character of part */
3268 /* FALLTHRU */
3269 default:
3270 if ( left && 'A' <= c && c <= 'Z' )
3272 *str++ = tolower (c); /* map to lower case (looks nicer) */
3273 left--;
3274 dots = 0; /* started a path component */
3276 break;
3279 *str = '\0';
3281 else
3283 strcpy (shortname, name);
3284 unixtodos_filename (shortname);
3287 if (pPath)
3288 *pPath = shortname + (path - save_name);
3290 return shortname;
3293 static int
3294 is_exec (const char * name)
3296 char * p = strrchr (name, '.');
3297 return
3298 (p != NULL
3299 && (xstrcasecmp (p, ".exe") == 0 ||
3300 xstrcasecmp (p, ".com") == 0 ||
3301 xstrcasecmp (p, ".bat") == 0 ||
3302 xstrcasecmp (p, ".cmd") == 0));
3305 /* Emulate the Unix directory procedures opendir, closedir, and
3306 readdir. We rename them to sys_* names because some versions of
3307 MinGW startup code call opendir and readdir to glob wildcards, and
3308 the code that calls them doesn't grok UTF-8 encoded file names we
3309 produce in dirent->d_name[]. */
3311 struct dirent dir_static; /* simulated directory contents */
3312 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3313 static int dir_is_fat;
3314 static char dir_pathname[MAX_UTF8_PATH];
3315 static WIN32_FIND_DATAW dir_find_data_w;
3316 static WIN32_FIND_DATAA dir_find_data_a;
3317 #define DIR_FIND_DATA_W 1
3318 #define DIR_FIND_DATA_A 2
3319 static int last_dir_find_data = -1;
3321 /* Support shares on a network resource as subdirectories of a read-only
3322 root directory. */
3323 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3324 static HANDLE open_unc_volume (const char *);
3325 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3326 static void close_unc_volume (HANDLE);
3328 DIR *
3329 sys_opendir (const char *filename)
3331 DIR *dirp;
3333 /* Opening is done by FindFirstFile. However, a read is inherent to
3334 this operation, so we defer the open until read time. */
3336 if (dir_find_handle != INVALID_HANDLE_VALUE)
3337 return NULL;
3338 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3339 return NULL;
3341 /* Note: We don't support traversal of UNC volumes via symlinks.
3342 Doing so would mean punishing 99.99% of use cases by resolving
3343 all the possible symlinks in FILENAME, recursively. */
3344 if (is_unc_volume (filename))
3346 wnet_enum_handle = open_unc_volume (filename);
3347 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3348 return NULL;
3351 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3352 return NULL;
3354 dirp->dd_fd = 0;
3355 dirp->dd_loc = 0;
3356 dirp->dd_size = 0;
3358 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3359 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3360 /* Note: We don't support symlinks to file names on FAT volumes.
3361 Doing so would mean punishing 99.99% of use cases by resolving
3362 all the possible symlinks in FILENAME, recursively. */
3363 dir_is_fat = is_fat_volume (filename, NULL);
3365 return dirp;
3368 void
3369 sys_closedir (DIR *dirp)
3371 /* If we have a find-handle open, close it. */
3372 if (dir_find_handle != INVALID_HANDLE_VALUE)
3374 FindClose (dir_find_handle);
3375 dir_find_handle = INVALID_HANDLE_VALUE;
3377 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3379 close_unc_volume (wnet_enum_handle);
3380 wnet_enum_handle = INVALID_HANDLE_VALUE;
3382 xfree ((char *) dirp);
3385 struct dirent *
3386 sys_readdir (DIR *dirp)
3388 int downcase = !NILP (Vw32_downcase_file_names);
3390 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3392 if (!read_unc_volume (wnet_enum_handle,
3393 dir_find_data_w.cFileName,
3394 dir_find_data_a.cFileName,
3395 MAX_PATH))
3396 return NULL;
3398 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3399 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3401 char filename[MAX_UTF8_PATH + 2];
3402 int ln;
3404 strcpy (filename, dir_pathname);
3405 ln = strlen (filename) - 1;
3406 if (!IS_DIRECTORY_SEP (filename[ln]))
3407 strcat (filename, "\\");
3408 strcat (filename, "*");
3410 /* Note: No need to resolve symlinks in FILENAME, because
3411 FindFirst opens the directory that is the target of a
3412 symlink. */
3413 if (w32_unicode_filenames)
3415 wchar_t fnw[MAX_PATH];
3417 filename_to_utf16 (filename, fnw);
3418 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3420 else
3422 char fna[MAX_PATH];
3424 filename_to_ansi (filename, fna);
3425 /* If FILENAME is not representable by the current ANSI
3426 codepage, we don't want FindFirstFileA to interpret the
3427 '?' characters as a wildcard. */
3428 if (_mbspbrk (fna, "?"))
3429 dir_find_handle = INVALID_HANDLE_VALUE;
3430 else
3431 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3434 if (dir_find_handle == INVALID_HANDLE_VALUE)
3436 /* Any changes in the value of errno here should be in sync
3437 with what directory_files_internal does when it calls
3438 readdir. */
3439 switch (GetLastError ())
3441 /* Windows uses this value when FindFirstFile finds no
3442 files that match the wildcard. This is not supposed
3443 to happen, since our wildcard is "*", but just in
3444 case, if there's some weird empty directory with not
3445 even "." and ".." entries... */
3446 case ERROR_FILE_NOT_FOUND:
3447 errno = 0;
3448 /* FALLTHRU */
3449 default:
3450 break;
3451 case ERROR_ACCESS_DENIED:
3452 case ERROR_NETWORK_ACCESS_DENIED:
3453 errno = EACCES;
3454 break;
3455 case ERROR_PATH_NOT_FOUND:
3456 case ERROR_INVALID_DRIVE:
3457 case ERROR_NOT_READY:
3458 case ERROR_BAD_NETPATH:
3459 case ERROR_BAD_NET_NAME:
3460 errno = ENOENT;
3461 break;
3463 return NULL;
3466 else if (w32_unicode_filenames)
3468 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3470 errno = 0;
3471 return NULL;
3474 else
3476 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3478 errno = 0;
3479 return NULL;
3483 /* Emacs never uses this value, so don't bother making it match
3484 value returned by stat(). */
3485 dir_static.d_ino = 1;
3487 if (w32_unicode_filenames)
3489 if (downcase || dir_is_fat)
3491 wchar_t tem[MAX_PATH];
3493 wcscpy (tem, dir_find_data_w.cFileName);
3494 CharLowerW (tem);
3495 filename_from_utf16 (tem, dir_static.d_name);
3497 else
3498 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3499 last_dir_find_data = DIR_FIND_DATA_W;
3501 else
3503 char tem[MAX_PATH];
3505 /* If the file name in cFileName[] includes `?' characters, it
3506 means the original file name used characters that cannot be
3507 represented by the current ANSI codepage. To avoid total
3508 lossage, retrieve the short 8+3 alias of the long file
3509 name. */
3510 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3512 strcpy (tem, dir_find_data_a.cAlternateFileName);
3513 /* 8+3 aliases are returned in all caps, which could break
3514 various alists that look at filenames' extensions. */
3515 downcase = 1;
3517 else if (downcase || dir_is_fat)
3518 strcpy (tem, dir_find_data_a.cFileName);
3519 else
3520 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3521 if (downcase || dir_is_fat)
3523 _mbslwr (tem);
3524 filename_from_ansi (tem, dir_static.d_name);
3526 last_dir_find_data = DIR_FIND_DATA_A;
3529 dir_static.d_namlen = strlen (dir_static.d_name);
3530 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3531 dir_static.d_namlen - dir_static.d_namlen % 4;
3533 return &dir_static;
3536 static HANDLE
3537 open_unc_volume (const char *path)
3539 const char *fn = map_w32_filename (path, NULL);
3540 DWORD result;
3541 HANDLE henum;
3543 if (w32_unicode_filenames)
3545 NETRESOURCEW nrw;
3546 wchar_t fnw[MAX_PATH];
3548 nrw.dwScope = RESOURCE_GLOBALNET;
3549 nrw.dwType = RESOURCETYPE_DISK;
3550 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3551 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3552 nrw.lpLocalName = NULL;
3553 filename_to_utf16 (fn, fnw);
3554 nrw.lpRemoteName = fnw;
3555 nrw.lpComment = NULL;
3556 nrw.lpProvider = NULL;
3558 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3559 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3561 else
3563 NETRESOURCEA nra;
3564 char fna[MAX_PATH];
3566 nra.dwScope = RESOURCE_GLOBALNET;
3567 nra.dwType = RESOURCETYPE_DISK;
3568 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3569 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3570 nra.lpLocalName = NULL;
3571 filename_to_ansi (fn, fna);
3572 nra.lpRemoteName = fna;
3573 nra.lpComment = NULL;
3574 nra.lpProvider = NULL;
3576 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3577 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3579 if (result == NO_ERROR)
3580 return henum;
3581 else
3583 /* Make sure directory_files_internal reports a sensible error. */
3584 errno = ENOENT;
3585 return INVALID_HANDLE_VALUE;
3589 static void *
3590 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3592 DWORD count;
3593 int result;
3594 char *buffer;
3595 DWORD bufsize = 512;
3596 void *retval;
3598 count = 1;
3599 if (w32_unicode_filenames)
3601 wchar_t *ptrw;
3603 bufsize *= 2;
3604 buffer = alloca (bufsize);
3605 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3606 if (result != NO_ERROR)
3607 return NULL;
3608 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3609 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3610 ptrw += 2;
3611 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3612 ptrw++;
3613 wcsncpy (fname_w, ptrw, size);
3614 retval = fname_w;
3616 else
3618 int dbcs_p = max_filename_mbslen () > 1;
3619 char *ptra;
3621 buffer = alloca (bufsize);
3622 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3623 if (result != NO_ERROR)
3624 return NULL;
3625 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3626 ptra += 2;
3627 if (!dbcs_p)
3628 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3629 else
3631 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3632 ptra = CharNextExA (file_name_codepage, ptra, 0);
3634 ptra++;
3635 strncpy (fname_a, ptra, size);
3636 retval = fname_a;
3639 return retval;
3642 static void
3643 close_unc_volume (HANDLE henum)
3645 if (henum != INVALID_HANDLE_VALUE)
3646 WNetCloseEnum (henum);
3649 static DWORD
3650 unc_volume_file_attributes (const char *path)
3652 HANDLE henum;
3653 DWORD attrs;
3655 henum = open_unc_volume (path);
3656 if (henum == INVALID_HANDLE_VALUE)
3657 return -1;
3659 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3661 close_unc_volume (henum);
3663 return attrs;
3666 /* Ensure a network connection is authenticated. */
3667 static void
3668 logon_network_drive (const char *path)
3670 char share[MAX_UTF8_PATH];
3671 int n_slashes;
3672 char drive[4];
3673 UINT drvtype;
3674 char *p;
3675 DWORD val;
3677 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3678 drvtype = DRIVE_REMOTE;
3679 else if (path[0] == '\0' || path[1] != ':')
3680 drvtype = GetDriveType (NULL);
3681 else
3683 drive[0] = path[0];
3684 drive[1] = ':';
3685 drive[2] = '\\';
3686 drive[3] = '\0';
3687 drvtype = GetDriveType (drive);
3690 /* Only logon to networked drives. */
3691 if (drvtype != DRIVE_REMOTE)
3692 return;
3694 n_slashes = 2;
3695 strncpy (share, path, MAX_UTF8_PATH);
3696 /* Truncate to just server and share name. */
3697 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3699 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3701 *p = '\0';
3702 break;
3706 if (w32_unicode_filenames)
3708 NETRESOURCEW resourcew;
3709 wchar_t share_w[MAX_PATH];
3711 resourcew.dwScope = RESOURCE_GLOBALNET;
3712 resourcew.dwType = RESOURCETYPE_DISK;
3713 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3714 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3715 resourcew.lpLocalName = NULL;
3716 filename_to_utf16 (share, share_w);
3717 resourcew.lpRemoteName = share_w;
3718 resourcew.lpProvider = NULL;
3720 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3722 else
3724 NETRESOURCEA resourcea;
3725 char share_a[MAX_PATH];
3727 resourcea.dwScope = RESOURCE_GLOBALNET;
3728 resourcea.dwType = RESOURCETYPE_DISK;
3729 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3730 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3731 resourcea.lpLocalName = NULL;
3732 filename_to_ansi (share, share_a);
3733 resourcea.lpRemoteName = share_a;
3734 resourcea.lpProvider = NULL;
3736 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3739 switch (val)
3741 case NO_ERROR:
3742 case ERROR_ALREADY_ASSIGNED:
3743 break;
3744 case ERROR_ACCESS_DENIED:
3745 case ERROR_LOGON_FAILURE:
3746 errno = EACCES;
3747 break;
3748 case ERROR_BUSY:
3749 errno = EAGAIN;
3750 break;
3751 case ERROR_BAD_NET_NAME:
3752 case ERROR_NO_NET_OR_BAD_PATH:
3753 case ERROR_NO_NETWORK:
3754 case ERROR_CANCELLED:
3755 default:
3756 errno = ENOENT;
3757 break;
3761 /* Emulate faccessat(2). */
3763 faccessat (int dirfd, const char * path, int mode, int flags)
3765 DWORD attributes;
3767 if (dirfd != AT_FDCWD
3768 && !(IS_DIRECTORY_SEP (path[0])
3769 || IS_DEVICE_SEP (path[1])))
3771 errno = EBADF;
3772 return -1;
3775 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3776 newer versions blow up when passed D_OK. */
3777 path = map_w32_filename (path, NULL);
3778 /* If the last element of PATH is a symlink, we need to resolve it
3779 to get the attributes of its target file. Note: any symlinks in
3780 PATH elements other than the last one are transparently resolved
3781 by GetFileAttributes below. */
3782 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3783 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3784 path = chase_symlinks (path);
3786 if (w32_unicode_filenames)
3788 wchar_t path_w[MAX_PATH];
3790 filename_to_utf16 (path, path_w);
3791 attributes = GetFileAttributesW (path_w);
3793 else
3795 char path_a[MAX_PATH];
3797 filename_to_ansi (path, path_a);
3798 attributes = GetFileAttributesA (path_a);
3801 if (attributes == -1)
3803 DWORD w32err = GetLastError ();
3805 switch (w32err)
3807 case ERROR_INVALID_NAME:
3808 case ERROR_BAD_PATHNAME:
3809 if (is_unc_volume (path))
3811 attributes = unc_volume_file_attributes (path);
3812 if (attributes == -1)
3814 errno = EACCES;
3815 return -1;
3817 break;
3819 /* FALLTHROUGH */
3820 case ERROR_FILE_NOT_FOUND:
3821 case ERROR_BAD_NETPATH:
3822 errno = ENOENT;
3823 break;
3824 default:
3825 errno = EACCES;
3826 break;
3828 return -1;
3830 if ((mode & X_OK) != 0
3831 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3833 errno = EACCES;
3834 return -1;
3836 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3838 errno = EACCES;
3839 return -1;
3841 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3843 errno = EACCES;
3844 return -1;
3846 return 0;
3849 /* A version of 'access' to be used locally with file names in
3850 locale-specific encoding. Does not resolve symlinks and does not
3851 support file names on FAT12 and FAT16 volumes, but that's OK, since
3852 we only invoke this function for files inside the Emacs source or
3853 installation tree, on directories (so any symlinks should have the
3854 directory bit set), and on short file names such as "C:/.emacs". */
3855 static int
3856 sys_access (const char *fname, int mode)
3858 char fname_copy[MAX_PATH], *p;
3859 DWORD attributes;
3861 strcpy (fname_copy, fname);
3862 /* Do the equivalent of unixtodos_filename. */
3863 for (p = fname_copy; *p; p = CharNext (p))
3864 if (*p == '/')
3865 *p = '\\';
3867 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
3869 DWORD w32err = GetLastError ();
3871 switch (w32err)
3873 case ERROR_INVALID_NAME:
3874 case ERROR_BAD_PATHNAME:
3875 case ERROR_FILE_NOT_FOUND:
3876 case ERROR_BAD_NETPATH:
3877 errno = ENOENT;
3878 break;
3879 default:
3880 errno = EACCES;
3881 break;
3883 return -1;
3885 if ((mode & X_OK) != 0
3886 && !(is_exec (fname_copy)
3887 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3889 errno = EACCES;
3890 return -1;
3892 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3894 errno = EACCES;
3895 return -1;
3897 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3899 errno = EACCES;
3900 return -1;
3902 return 0;
3905 /* Shadow some MSVC runtime functions to map requests for long filenames
3906 to reasonable short names if necessary. This was originally added to
3907 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3908 long file names. */
3911 sys_chdir (const char * path)
3913 path = map_w32_filename (path, NULL);
3914 if (w32_unicode_filenames)
3916 wchar_t newdir_w[MAX_PATH];
3918 if (filename_to_utf16 (path, newdir_w) == 0)
3919 return _wchdir (newdir_w);
3920 return -1;
3922 else
3924 char newdir_a[MAX_PATH];
3926 if (filename_to_ansi (path, newdir_a) == 0)
3927 return _chdir (newdir_a);
3928 return -1;
3933 sys_chmod (const char * path, int mode)
3935 path = chase_symlinks (map_w32_filename (path, NULL));
3936 if (w32_unicode_filenames)
3938 wchar_t path_w[MAX_PATH];
3940 filename_to_utf16 (path, path_w);
3941 return _wchmod (path_w, mode);
3943 else
3945 char path_a[MAX_PATH];
3947 filename_to_ansi (path, path_a);
3948 return _chmod (path_a, mode);
3953 sys_creat (const char * path, int mode)
3955 path = map_w32_filename (path, NULL);
3956 if (w32_unicode_filenames)
3958 wchar_t path_w[MAX_PATH];
3960 filename_to_utf16 (path, path_w);
3961 return _wcreat (path_w, mode);
3963 else
3965 char path_a[MAX_PATH];
3967 filename_to_ansi (path, path_a);
3968 return _creat (path_a, mode);
3972 FILE *
3973 sys_fopen (const char * path, const char * mode)
3975 int fd;
3976 int oflag;
3977 const char * mode_save = mode;
3979 /* Force all file handles to be non-inheritable. This is necessary to
3980 ensure child processes don't unwittingly inherit handles that might
3981 prevent future file access. */
3983 if (mode[0] == 'r')
3984 oflag = O_RDONLY;
3985 else if (mode[0] == 'w' || mode[0] == 'a')
3986 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3987 else
3988 return NULL;
3990 /* Only do simplistic option parsing. */
3991 while (*++mode)
3992 if (mode[0] == '+')
3994 oflag &= ~(O_RDONLY | O_WRONLY);
3995 oflag |= O_RDWR;
3997 else if (mode[0] == 'b')
3999 oflag &= ~O_TEXT;
4000 oflag |= O_BINARY;
4002 else if (mode[0] == 't')
4004 oflag &= ~O_BINARY;
4005 oflag |= O_TEXT;
4007 else break;
4009 path = map_w32_filename (path, NULL);
4010 if (w32_unicode_filenames)
4012 wchar_t path_w[MAX_PATH];
4014 filename_to_utf16 (path, path_w);
4015 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4017 else
4019 char path_a[MAX_PATH];
4021 filename_to_ansi (path, path_a);
4022 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4024 if (fd < 0)
4025 return NULL;
4027 return _fdopen (fd, mode_save);
4030 /* This only works on NTFS volumes, but is useful to have. */
4032 sys_link (const char * old, const char * new)
4034 HANDLE fileh;
4035 int result = -1;
4036 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4037 wchar_t oldname_w[MAX_PATH];
4038 char oldname_a[MAX_PATH];
4040 if (old == NULL || new == NULL)
4042 errno = ENOENT;
4043 return -1;
4046 strcpy (oldname, map_w32_filename (old, NULL));
4047 strcpy (newname, map_w32_filename (new, NULL));
4049 if (w32_unicode_filenames)
4051 filename_to_utf16 (oldname, oldname_w);
4052 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4053 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4055 else
4057 filename_to_ansi (oldname, oldname_a);
4058 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4059 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4061 if (fileh != INVALID_HANDLE_VALUE)
4063 int wlen;
4065 /* Confusingly, the "alternate" stream name field does not apply
4066 when restoring a hard link, and instead contains the actual
4067 stream data for the link (ie. the name of the link to create).
4068 The WIN32_STREAM_ID structure before the cStreamName field is
4069 the stream header, which is then immediately followed by the
4070 stream data. */
4072 struct {
4073 WIN32_STREAM_ID wid;
4074 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4075 } data;
4077 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4078 indicates that flag is unsupported for CP_UTF8, and OTOH says
4079 it is the default anyway. */
4080 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4081 data.wid.cStreamName, MAX_PATH);
4082 if (wlen > 0)
4084 LPVOID context = NULL;
4085 DWORD wbytes = 0;
4087 data.wid.dwStreamId = BACKUP_LINK;
4088 data.wid.dwStreamAttributes = 0;
4089 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4090 data.wid.Size.HighPart = 0;
4091 data.wid.dwStreamNameSize = 0;
4093 if (BackupWrite (fileh, (LPBYTE)&data,
4094 offsetof (WIN32_STREAM_ID, cStreamName)
4095 + data.wid.Size.LowPart,
4096 &wbytes, FALSE, FALSE, &context)
4097 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4099 /* succeeded */
4100 result = 0;
4102 else
4104 DWORD err = GetLastError ();
4105 DWORD attributes;
4107 switch (err)
4109 case ERROR_ACCESS_DENIED:
4110 /* This is what happens when OLDNAME is a directory,
4111 since Windows doesn't support hard links to
4112 directories. Posix says to set errno to EPERM in
4113 that case. */
4114 if (w32_unicode_filenames)
4115 attributes = GetFileAttributesW (oldname_w);
4116 else
4117 attributes = GetFileAttributesA (oldname_a);
4118 if (attributes != -1
4119 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4120 errno = EPERM;
4121 else if (attributes == -1
4122 && is_unc_volume (oldname)
4123 && unc_volume_file_attributes (oldname) != -1)
4124 errno = EPERM;
4125 else
4126 errno = EACCES;
4127 break;
4128 case ERROR_TOO_MANY_LINKS:
4129 errno = EMLINK;
4130 break;
4131 case ERROR_NOT_SAME_DEVICE:
4132 errno = EXDEV;
4133 break;
4134 default:
4135 errno = EINVAL;
4136 break;
4141 CloseHandle (fileh);
4143 else
4144 errno = ENOENT;
4146 return result;
4150 sys_mkdir (const char * path)
4152 path = map_w32_filename (path, NULL);
4154 if (w32_unicode_filenames)
4156 wchar_t path_w[MAX_PATH];
4158 filename_to_utf16 (path, path_w);
4159 return _wmkdir (path_w);
4161 else
4163 char path_a[MAX_PATH];
4165 filename_to_ansi (path, path_a);
4166 return _mkdir (path_a);
4171 sys_open (const char * path, int oflag, int mode)
4173 const char* mpath = map_w32_filename (path, NULL);
4174 int res = -1;
4176 if (w32_unicode_filenames)
4178 wchar_t mpath_w[MAX_PATH];
4180 filename_to_utf16 (mpath, mpath_w);
4181 /* If possible, try to open file without _O_CREAT, to be able to
4182 write to existing hidden and system files. Force all file
4183 handles to be non-inheritable. */
4184 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4185 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4186 if (res < 0)
4187 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4189 else
4191 char mpath_a[MAX_PATH];
4193 filename_to_ansi (mpath, mpath_a);
4194 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4195 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4196 if (res < 0)
4197 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4200 return res;
4203 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4204 when using mktemp.
4206 Standard algorithm for generating a temporary file name seems to be
4207 use pid or tid with a letter on the front (in place of the 6 X's)
4208 and cycle through the letters to find a unique name. We extend
4209 that to allow any reasonable character as the first of the 6 X's,
4210 so that the number of simultaneously used temporary files will be
4211 greater. */
4214 mkostemp (char * template, int flags)
4216 char * p;
4217 int i, fd = -1;
4218 unsigned uid = GetCurrentThreadId ();
4219 int save_errno = errno;
4220 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4222 errno = EINVAL;
4223 if (template == NULL)
4224 return -1;
4226 p = template + strlen (template);
4227 i = 5;
4228 /* replace up to the last 5 X's with uid in decimal */
4229 while (--p >= template && p[0] == 'X' && --i >= 0)
4231 p[0] = '0' + uid % 10;
4232 uid /= 10;
4235 if (i < 0 && p[0] == 'X')
4237 i = 0;
4240 p[0] = first_char[i];
4241 if ((fd = sys_open (template,
4242 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4243 S_IRUSR | S_IWUSR)) >= 0
4244 || errno != EEXIST)
4246 if (fd >= 0)
4247 errno = save_errno;
4248 return fd;
4251 while (++i < sizeof (first_char));
4254 /* Template is badly formed or else we can't generate a unique name. */
4255 return -1;
4259 fchmod (int fd, mode_t mode)
4261 return 0;
4265 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4267 BOOL result;
4268 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4269 int newname_dev;
4270 int oldname_dev;
4271 bool have_temp_a = false;
4273 /* MoveFile on Windows 95 doesn't correctly change the short file name
4274 alias in a number of circumstances (it is not easy to predict when
4275 just by looking at oldname and newname, unfortunately). In these
4276 cases, renaming through a temporary name avoids the problem.
4278 A second problem on Windows 95 is that renaming through a temp name when
4279 newname is uppercase fails (the final long name ends up in
4280 lowercase, although the short alias might be uppercase) UNLESS the
4281 long temp name is not 8.3.
4283 So, on Windows 95 we always rename through a temp name, and we make sure
4284 the temp name has a long extension to ensure correct renaming. */
4286 strcpy (temp, map_w32_filename (oldname, NULL));
4288 /* volume_info is set indirectly by map_w32_filename. */
4289 oldname_dev = volume_info.serialnum;
4291 if (os_subtype == OS_9X)
4293 char * o;
4294 char * p;
4295 int i = 0;
4296 char oldname_a[MAX_PATH];
4298 oldname = map_w32_filename (oldname, NULL);
4299 filename_to_ansi (oldname, oldname_a);
4300 filename_to_ansi (temp, temp_a);
4301 if ((o = strrchr (oldname_a, '\\')))
4302 o++;
4303 else
4304 o = (char *) oldname_a;
4306 if ((p = strrchr (temp_a, '\\')))
4307 p++;
4308 else
4309 p = temp_a;
4313 /* Force temp name to require a manufactured 8.3 alias - this
4314 seems to make the second rename work properly. */
4315 sprintf (p, "_.%s.%u", o, i);
4316 i++;
4317 result = rename (oldname_a, temp_a);
4319 /* This loop must surely terminate! */
4320 while (result < 0 && errno == EEXIST);
4321 if (result < 0)
4322 return -1;
4323 have_temp_a = true;
4326 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4327 (at least if it is a file; don't do this for directories).
4329 Since we mustn't do this if we are just changing the case of the
4330 file name (we would end up deleting the file we are trying to
4331 rename!), we let rename detect if the destination file already
4332 exists - that way we avoid the possible pitfalls of trying to
4333 determine ourselves whether two names really refer to the same
4334 file, which is not always possible in the general case. (Consider
4335 all the permutations of shared or subst'd drives, etc.) */
4337 newname = map_w32_filename (newname, NULL);
4339 /* volume_info is set indirectly by map_w32_filename. */
4340 newname_dev = volume_info.serialnum;
4342 if (w32_unicode_filenames)
4344 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4346 filename_to_utf16 (temp, temp_w);
4347 filename_to_utf16 (newname, newname_w);
4348 result = _wrename (temp_w, newname_w);
4349 if (result < 0 && force)
4351 DWORD w32err = GetLastError ();
4353 if (errno == EACCES
4354 && newname_dev != oldname_dev)
4356 /* The implementation of `rename' on Windows does not return
4357 errno = EXDEV when you are moving a directory to a
4358 different storage device (ex. logical disk). It returns
4359 EACCES instead. So here we handle such situations and
4360 return EXDEV. */
4361 DWORD attributes;
4363 if ((attributes = GetFileAttributesW (temp_w)) != -1
4364 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4365 errno = EXDEV;
4367 else if (errno == EEXIST)
4369 if (_wchmod (newname_w, 0666) != 0)
4370 return result;
4371 if (_wunlink (newname_w) != 0)
4372 return result;
4373 result = _wrename (temp_w, newname_w);
4375 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4376 && is_symlink (temp))
4378 /* This is Windows prohibiting the user from creating a
4379 symlink in another place, since that requires
4380 privileges. */
4381 errno = EPERM;
4385 else
4387 char newname_a[MAX_PATH];
4389 if (!have_temp_a)
4390 filename_to_ansi (temp, temp_a);
4391 filename_to_ansi (newname, newname_a);
4392 result = rename (temp_a, newname_a);
4393 if (result < 0 && force)
4395 DWORD w32err = GetLastError ();
4397 if (errno == EACCES
4398 && newname_dev != oldname_dev)
4400 DWORD attributes;
4402 if ((attributes = GetFileAttributesA (temp_a)) != -1
4403 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4404 errno = EXDEV;
4406 else if (errno == EEXIST)
4408 if (_chmod (newname_a, 0666) != 0)
4409 return result;
4410 if (_unlink (newname_a) != 0)
4411 return result;
4412 result = rename (temp_a, newname_a);
4414 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4415 && is_symlink (temp))
4416 errno = EPERM;
4420 return result;
4424 sys_rename (char const *old, char const *new)
4426 return sys_rename_replace (old, new, TRUE);
4430 sys_rmdir (const char * path)
4432 path = map_w32_filename (path, NULL);
4434 if (w32_unicode_filenames)
4436 wchar_t path_w[MAX_PATH];
4438 filename_to_utf16 (path, path_w);
4439 return _wrmdir (path_w);
4441 else
4443 char path_a[MAX_PATH];
4445 filename_to_ansi (path, path_a);
4446 return _rmdir (path_a);
4451 sys_unlink (const char * path)
4453 path = map_w32_filename (path, NULL);
4455 if (w32_unicode_filenames)
4457 wchar_t path_w[MAX_PATH];
4459 filename_to_utf16 (path, path_w);
4460 /* On Unix, unlink works without write permission. */
4461 _wchmod (path_w, 0666);
4462 return _wunlink (path_w);
4464 else
4466 char path_a[MAX_PATH];
4468 filename_to_ansi (path, path_a);
4469 _chmod (path_a, 0666);
4470 return _unlink (path_a);
4474 static FILETIME utc_base_ft;
4475 static ULONGLONG utc_base; /* In 100ns units */
4476 static int init = 0;
4478 #define FILETIME_TO_U64(result, ft) \
4479 do { \
4480 ULARGE_INTEGER uiTemp; \
4481 uiTemp.LowPart = (ft).dwLowDateTime; \
4482 uiTemp.HighPart = (ft).dwHighDateTime; \
4483 result = uiTemp.QuadPart; \
4484 } while (0)
4486 static void
4487 initialize_utc_base (void)
4489 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4490 SYSTEMTIME st;
4492 st.wYear = 1970;
4493 st.wMonth = 1;
4494 st.wDay = 1;
4495 st.wHour = 0;
4496 st.wMinute = 0;
4497 st.wSecond = 0;
4498 st.wMilliseconds = 0;
4500 SystemTimeToFileTime (&st, &utc_base_ft);
4501 FILETIME_TO_U64 (utc_base, utc_base_ft);
4504 static time_t
4505 convert_time (FILETIME ft)
4507 ULONGLONG tmp;
4509 if (!init)
4511 initialize_utc_base ();
4512 init = 1;
4515 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4516 return 0;
4518 FILETIME_TO_U64 (tmp, ft);
4519 return (time_t) ((tmp - utc_base) / 10000000L);
4522 static void
4523 convert_from_time_t (time_t time, FILETIME * pft)
4525 ULARGE_INTEGER tmp;
4527 if (!init)
4529 initialize_utc_base ();
4530 init = 1;
4533 /* time in 100ns units since 1-Jan-1601 */
4534 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4535 pft->dwHighDateTime = tmp.HighPart;
4536 pft->dwLowDateTime = tmp.LowPart;
4539 static PSECURITY_DESCRIPTOR
4540 get_file_security_desc_by_handle (HANDLE h)
4542 PSECURITY_DESCRIPTOR psd = NULL;
4543 DWORD err;
4544 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4545 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4547 err = get_security_info (h, SE_FILE_OBJECT, si,
4548 NULL, NULL, NULL, NULL, &psd);
4549 if (err != ERROR_SUCCESS)
4550 return NULL;
4552 return psd;
4555 static PSECURITY_DESCRIPTOR
4556 get_file_security_desc_by_name (const char *fname)
4558 PSECURITY_DESCRIPTOR psd = NULL;
4559 DWORD sd_len, err;
4560 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4561 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4563 if (!get_file_security (fname, si, psd, 0, &sd_len))
4565 err = GetLastError ();
4566 if (err != ERROR_INSUFFICIENT_BUFFER)
4567 return NULL;
4570 psd = xmalloc (sd_len);
4571 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4573 xfree (psd);
4574 return NULL;
4577 return psd;
4580 static DWORD
4581 get_rid (PSID sid)
4583 unsigned n_subauthorities;
4585 /* Use the last sub-authority value of the RID, the relative
4586 portion of the SID, as user/group ID. */
4587 n_subauthorities = *get_sid_sub_authority_count (sid);
4588 if (n_subauthorities < 1)
4589 return 0; /* the "World" RID */
4590 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4593 /* Caching SID and account values for faster lokup. */
4595 struct w32_id {
4596 unsigned rid;
4597 struct w32_id *next;
4598 char name[GNLEN+1];
4599 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4602 static struct w32_id *w32_idlist;
4604 static int
4605 w32_cached_id (PSID sid, unsigned *id, char *name)
4607 struct w32_id *tail, *found;
4609 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4611 if (equal_sid ((PSID)tail->sid, sid))
4613 found = tail;
4614 break;
4617 if (found)
4619 *id = found->rid;
4620 strcpy (name, found->name);
4621 return 1;
4623 else
4624 return 0;
4627 static void
4628 w32_add_to_cache (PSID sid, unsigned id, char *name)
4630 DWORD sid_len;
4631 struct w32_id *new_entry;
4633 /* We don't want to leave behind stale cache from when Emacs was
4634 dumped. */
4635 if (initialized)
4637 sid_len = get_length_sid (sid);
4638 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4639 if (new_entry)
4641 new_entry->rid = id;
4642 strcpy (new_entry->name, name);
4643 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4644 new_entry->next = w32_idlist;
4645 w32_idlist = new_entry;
4650 #define UID 1
4651 #define GID 2
4653 static int
4654 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4656 PSID sid = NULL;
4657 BOOL dflt;
4658 SID_NAME_USE ignore;
4659 char name[UNLEN+1];
4660 DWORD name_len = sizeof (name);
4661 char domain[1024];
4662 DWORD domain_len = sizeof (domain);
4663 int use_dflt = 0;
4664 int result;
4666 if (what == UID)
4667 result = get_security_descriptor_owner (psd, &sid, &dflt);
4668 else if (what == GID)
4669 result = get_security_descriptor_group (psd, &sid, &dflt);
4670 else
4671 result = 0;
4673 if (!result || !is_valid_sid (sid))
4674 use_dflt = 1;
4675 else if (!w32_cached_id (sid, id, nm))
4677 if (!lookup_account_sid (NULL, sid, name, &name_len,
4678 domain, &domain_len, &ignore)
4679 || name_len > UNLEN+1)
4680 use_dflt = 1;
4681 else
4683 *id = get_rid (sid);
4684 strcpy (nm, name);
4685 w32_add_to_cache (sid, *id, name);
4688 return use_dflt;
4691 static void
4692 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4694 int dflt_usr = 0, dflt_grp = 0;
4696 if (!psd)
4698 dflt_usr = 1;
4699 dflt_grp = 1;
4701 else
4703 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4704 dflt_usr = 1;
4705 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4706 dflt_grp = 1;
4708 /* Consider files to belong to current user/group, if we cannot get
4709 more accurate information. */
4710 if (dflt_usr)
4712 st->st_uid = dflt_passwd.pw_uid;
4713 strcpy (st->st_uname, dflt_passwd.pw_name);
4715 if (dflt_grp)
4717 st->st_gid = dflt_passwd.pw_gid;
4718 strcpy (st->st_gname, dflt_group.gr_name);
4722 /* Return non-zero if NAME is a potentially slow filesystem. */
4724 is_slow_fs (const char *name)
4726 char drive_root[4];
4727 UINT devtype;
4729 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4730 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4731 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4732 devtype = GetDriveType (NULL); /* use root of current drive */
4733 else
4735 /* GetDriveType needs the root directory of the drive. */
4736 strncpy (drive_root, name, 2);
4737 drive_root[2] = '\\';
4738 drive_root[3] = '\0';
4739 devtype = GetDriveType (drive_root);
4741 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4744 /* If this is non-zero, the caller wants accurate information about
4745 file's owner and group, which could be expensive to get. dired.c
4746 uses this flag when needed for the job at hand. */
4747 int w32_stat_get_owner_group;
4749 /* MSVC stat function can't cope with UNC names and has other bugs, so
4750 replace it with our own. This also allows us to calculate consistent
4751 inode values and owner/group without hacks in the main Emacs code,
4752 and support file names encoded in UTF-8. */
4754 static int
4755 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4757 char *name, *save_name, *r;
4758 WIN32_FIND_DATAW wfd_w;
4759 WIN32_FIND_DATAA wfd_a;
4760 HANDLE fh;
4761 unsigned __int64 fake_inode = 0;
4762 int permission;
4763 int len;
4764 int rootdir = FALSE;
4765 PSECURITY_DESCRIPTOR psd = NULL;
4766 int is_a_symlink = 0;
4767 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4768 DWORD access_rights = 0;
4769 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4770 FILETIME ctime, atime, wtime;
4771 wchar_t name_w[MAX_PATH];
4772 char name_a[MAX_PATH];
4774 if (path == NULL || buf == NULL)
4776 errno = EFAULT;
4777 return -1;
4780 save_name = name = (char *) map_w32_filename (path, &path);
4781 /* Must be valid filename, no wild cards or other invalid
4782 characters. */
4783 if (strpbrk (name, "*?|<>\""))
4785 errno = ENOENT;
4786 return -1;
4789 len = strlen (name);
4790 /* Allocate 1 extra byte so that we could append a slash to a root
4791 directory, down below. */
4792 name = strcpy (alloca (len + 2), name);
4794 /* Avoid a somewhat costly call to is_symlink if the filesystem
4795 doesn't support symlinks. */
4796 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4797 is_a_symlink = is_symlink (name);
4799 /* Plan A: Open the file and get all the necessary information via
4800 the resulting handle. This solves several issues in one blow:
4802 . retrieves attributes for the target of a symlink, if needed
4803 . gets attributes of root directories and symlinks pointing to
4804 root directories, thus avoiding the need for special-casing
4805 these and detecting them by examining the file-name format
4806 . retrieves more accurate attributes (e.g., non-zero size for
4807 some directories, esp. directories that are junction points)
4808 . correctly resolves "c:/..", "/.." and similar file names
4809 . avoids run-time penalties for 99% of use cases
4811 Plan A is always tried first, unless the user asked not to (but
4812 if the file is a symlink and we need to follow links, we try Plan
4813 A even if the user asked not to).
4815 If Plan A fails, we go to Plan B (below), where various
4816 potentially expensive techniques must be used to handle "special"
4817 files such as UNC volumes etc. */
4818 if (!(NILP (Vw32_get_true_file_attributes)
4819 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4820 /* Following symlinks requires getting the info by handle. */
4821 || (is_a_symlink && follow_symlinks))
4823 BY_HANDLE_FILE_INFORMATION info;
4825 if (is_a_symlink && !follow_symlinks)
4826 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4827 /* READ_CONTROL access rights are required to get security info
4828 by handle. But if the OS doesn't support security in the
4829 first place, we don't need to try. */
4830 if (is_windows_9x () != TRUE)
4831 access_rights |= READ_CONTROL;
4833 if (w32_unicode_filenames)
4835 filename_to_utf16 (name, name_w);
4836 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4837 file_flags, NULL);
4838 /* If CreateFile fails with READ_CONTROL, try again with
4839 zero as access rights. */
4840 if (fh == INVALID_HANDLE_VALUE && access_rights)
4841 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
4842 file_flags, NULL);
4844 else
4846 filename_to_ansi (name, name_a);
4847 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
4848 file_flags, NULL);
4849 if (fh == INVALID_HANDLE_VALUE && access_rights)
4850 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
4851 file_flags, NULL);
4853 if (fh == INVALID_HANDLE_VALUE)
4854 goto no_true_file_attributes;
4856 /* This is more accurate in terms of getting the correct number
4857 of links, but is quite slow (it is noticeable when Emacs is
4858 making a list of file name completions). */
4859 if (GetFileInformationByHandle (fh, &info))
4861 nlinks = info.nNumberOfLinks;
4862 /* Might as well use file index to fake inode values, but this
4863 is not guaranteed to be unique unless we keep a handle open
4864 all the time (even then there are situations where it is
4865 not unique). Reputedly, there are at most 48 bits of info
4866 (on NTFS, presumably less on FAT). */
4867 fake_inode = info.nFileIndexHigh;
4868 fake_inode <<= 32;
4869 fake_inode += info.nFileIndexLow;
4870 serialnum = info.dwVolumeSerialNumber;
4871 fs_high = info.nFileSizeHigh;
4872 fs_low = info.nFileSizeLow;
4873 ctime = info.ftCreationTime;
4874 atime = info.ftLastAccessTime;
4875 wtime = info.ftLastWriteTime;
4876 fattrs = info.dwFileAttributes;
4878 else
4880 /* We don't go to Plan B here, because it's not clear that
4881 it's a good idea. The only known use case where
4882 CreateFile succeeds, but GetFileInformationByHandle fails
4883 (with ERROR_INVALID_FUNCTION) is for character devices
4884 such as NUL, PRN, etc. For these, switching to Plan B is
4885 a net loss, because we lose the character device
4886 attribute returned by GetFileType below (FindFirstFile
4887 doesn't set that bit in the attributes), and the other
4888 fields don't make sense for character devices anyway.
4889 Emacs doesn't really care for non-file entities in the
4890 context of l?stat, so neither do we. */
4892 /* w32err is assigned so one could put a breakpoint here and
4893 examine its value, when GetFileInformationByHandle
4894 fails. */
4895 DWORD w32err = GetLastError ();
4897 switch (w32err)
4899 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4900 errno = ENOENT;
4901 return -1;
4905 /* Test for a symlink before testing for a directory, since
4906 symlinks to directories have the directory bit set, but we
4907 don't want them to appear as directories. */
4908 if (is_a_symlink && !follow_symlinks)
4909 buf->st_mode = S_IFLNK;
4910 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4911 buf->st_mode = S_IFDIR;
4912 else
4914 DWORD ftype = GetFileType (fh);
4916 switch (ftype)
4918 case FILE_TYPE_DISK:
4919 buf->st_mode = S_IFREG;
4920 break;
4921 case FILE_TYPE_PIPE:
4922 buf->st_mode = S_IFIFO;
4923 break;
4924 case FILE_TYPE_CHAR:
4925 case FILE_TYPE_UNKNOWN:
4926 default:
4927 buf->st_mode = S_IFCHR;
4930 /* We produce the fallback owner and group data, based on the
4931 current user that runs Emacs, in the following cases:
4933 . caller didn't request owner and group info
4934 . this is Windows 9X
4935 . getting security by handle failed, and we need to produce
4936 information for the target of a symlink (this is better
4937 than producing a potentially misleading info about the
4938 symlink itself)
4940 If getting security by handle fails, and we don't need to
4941 resolve symlinks, we try getting security by name. */
4942 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4943 get_file_owner_and_group (NULL, buf);
4944 else
4946 psd = get_file_security_desc_by_handle (fh);
4947 if (psd)
4949 get_file_owner_and_group (psd, buf);
4950 LocalFree (psd);
4952 else if (!(is_a_symlink && follow_symlinks))
4954 psd = get_file_security_desc_by_name (name);
4955 get_file_owner_and_group (psd, buf);
4956 xfree (psd);
4958 else
4959 get_file_owner_and_group (NULL, buf);
4961 CloseHandle (fh);
4963 else
4965 no_true_file_attributes:
4966 /* Plan B: Either getting a handle on the file failed, or the
4967 caller explicitly asked us to not bother making this
4968 information more accurate.
4970 Implementation note: In Plan B, we never bother to resolve
4971 symlinks, even if we got here because we tried Plan A and
4972 failed. That's because, even if the caller asked for extra
4973 precision by setting Vw32_get_true_file_attributes to t,
4974 resolving symlinks requires acquiring a file handle to the
4975 symlink, which we already know will fail. And if the user
4976 did not ask for extra precision, resolving symlinks will fly
4977 in the face of that request, since the user then wants the
4978 lightweight version of the code. */
4979 rootdir = (path >= save_name + len - 1
4980 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4982 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4983 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4984 if (IS_DIRECTORY_SEP (r[0])
4985 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4986 r[1] = r[2] = '\0';
4988 /* Note: If NAME is a symlink to the root of a UNC volume
4989 (i.e. "\\SERVER"), we will not detect that here, and we will
4990 return data about the symlink as result of FindFirst below.
4991 This is unfortunate, but that marginal use case does not
4992 justify a call to chase_symlinks which would impose a penalty
4993 on all the other use cases. (We get here for symlinks to
4994 roots of UNC volumes because CreateFile above fails for them,
4995 unlike with symlinks to root directories X:\ of drives.) */
4996 if (is_unc_volume (name))
4998 fattrs = unc_volume_file_attributes (name);
4999 if (fattrs == -1)
5000 return -1;
5002 ctime = atime = wtime = utc_base_ft;
5004 else if (rootdir)
5006 /* Make sure root directories end in a slash. */
5007 if (!IS_DIRECTORY_SEP (name[len-1]))
5008 strcat (name, "\\");
5009 if (GetDriveType (name) < 2)
5011 errno = ENOENT;
5012 return -1;
5015 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5016 ctime = atime = wtime = utc_base_ft;
5018 else
5020 int have_wfd = -1;
5022 /* Make sure non-root directories do NOT end in a slash,
5023 otherwise FindFirstFile might fail. */
5024 if (IS_DIRECTORY_SEP (name[len-1]))
5025 name[len - 1] = 0;
5027 /* (This is hacky, but helps when doing file completions on
5028 network drives.) Optimize by using information available from
5029 active readdir if possible. */
5030 len = strlen (dir_pathname);
5031 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5032 len--;
5033 if (dir_find_handle != INVALID_HANDLE_VALUE
5034 && last_dir_find_data != -1
5035 && !(is_a_symlink && follow_symlinks)
5036 /* The 2 file-name comparisons below support only ASCII
5037 characters, and will lose (compare not equal) when
5038 the file names include non-ASCII characters that are
5039 the same but for the case. However, doing this
5040 properly involves: (a) converting both file names to
5041 UTF-16, (b) lower-casing both names using CharLowerW,
5042 and (c) comparing the results; this would be quite a
5043 bit slower, whereas Plan B is for users who want
5044 lightweight albeit inaccurate version of 'stat'. */
5045 && c_strncasecmp (save_name, dir_pathname, len) == 0
5046 && IS_DIRECTORY_SEP (name[len])
5047 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5049 have_wfd = last_dir_find_data;
5050 /* This was the last entry returned by readdir. */
5051 if (last_dir_find_data == DIR_FIND_DATA_W)
5052 wfd_w = dir_find_data_w;
5053 else
5054 wfd_a = dir_find_data_a;
5056 else
5058 logon_network_drive (name);
5060 if (w32_unicode_filenames)
5062 filename_to_utf16 (name, name_w);
5063 fh = FindFirstFileW (name_w, &wfd_w);
5064 have_wfd = DIR_FIND_DATA_W;
5066 else
5068 filename_to_ansi (name, name_a);
5069 /* If NAME includes characters not representable by
5070 the current ANSI codepage, filename_to_ansi
5071 usually replaces them with a '?'. We don't want
5072 to let FindFirstFileA interpret those as wildcards,
5073 and "succeed", returning us data from some random
5074 file in the same directory. */
5075 if (_mbspbrk (name_a, "?"))
5076 fh = INVALID_HANDLE_VALUE;
5077 else
5078 fh = FindFirstFileA (name_a, &wfd_a);
5079 have_wfd = DIR_FIND_DATA_A;
5081 if (fh == INVALID_HANDLE_VALUE)
5083 errno = ENOENT;
5084 return -1;
5086 FindClose (fh);
5088 /* Note: if NAME is a symlink, the information we get from
5089 FindFirstFile is for the symlink, not its target. */
5090 if (have_wfd == DIR_FIND_DATA_W)
5092 fattrs = wfd_w.dwFileAttributes;
5093 ctime = wfd_w.ftCreationTime;
5094 atime = wfd_w.ftLastAccessTime;
5095 wtime = wfd_w.ftLastWriteTime;
5096 fs_high = wfd_w.nFileSizeHigh;
5097 fs_low = wfd_w.nFileSizeLow;
5099 else
5101 fattrs = wfd_a.dwFileAttributes;
5102 ctime = wfd_a.ftCreationTime;
5103 atime = wfd_a.ftLastAccessTime;
5104 wtime = wfd_a.ftLastWriteTime;
5105 fs_high = wfd_a.nFileSizeHigh;
5106 fs_low = wfd_a.nFileSizeLow;
5108 fake_inode = 0;
5109 nlinks = 1;
5110 serialnum = volume_info.serialnum;
5112 if (is_a_symlink && !follow_symlinks)
5113 buf->st_mode = S_IFLNK;
5114 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5115 buf->st_mode = S_IFDIR;
5116 else
5117 buf->st_mode = S_IFREG;
5119 get_file_owner_and_group (NULL, buf);
5122 buf->st_ino = fake_inode;
5124 buf->st_dev = serialnum;
5125 buf->st_rdev = serialnum;
5127 buf->st_size = fs_high;
5128 buf->st_size <<= 32;
5129 buf->st_size += fs_low;
5130 buf->st_nlink = nlinks;
5132 /* Convert timestamps to Unix format. */
5133 buf->st_mtime = convert_time (wtime);
5134 buf->st_atime = convert_time (atime);
5135 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5136 buf->st_ctime = convert_time (ctime);
5137 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5139 /* determine rwx permissions */
5140 if (is_a_symlink && !follow_symlinks)
5141 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5142 else
5144 if (fattrs & FILE_ATTRIBUTE_READONLY)
5145 permission = S_IREAD;
5146 else
5147 permission = S_IREAD | S_IWRITE;
5149 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5150 permission |= S_IEXEC;
5151 else if (is_exec (name))
5152 permission |= S_IEXEC;
5155 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5157 return 0;
5161 stat (const char * path, struct stat * buf)
5163 return stat_worker (path, buf, 1);
5167 lstat (const char * path, struct stat * buf)
5169 return stat_worker (path, buf, 0);
5173 fstatat (int fd, char const *name, struct stat *st, int flags)
5175 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5176 This is good enough for the current usage in Emacs, but is fragile.
5178 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5179 Gnulib does this and can serve as a model. */
5180 char fullname[MAX_UTF8_PATH];
5182 if (fd != AT_FDCWD)
5184 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5186 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5187 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5188 < 0)
5190 errno = ENAMETOOLONG;
5191 return -1;
5193 name = fullname;
5196 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5199 /* Provide fstat and utime as well as stat for consistent handling of
5200 file timestamps. */
5202 fstat (int desc, struct stat * buf)
5204 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5205 BY_HANDLE_FILE_INFORMATION info;
5206 unsigned __int64 fake_inode;
5207 int permission;
5209 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5211 case FILE_TYPE_DISK:
5212 buf->st_mode = S_IFREG;
5213 if (!GetFileInformationByHandle (fh, &info))
5215 errno = EACCES;
5216 return -1;
5218 break;
5219 case FILE_TYPE_PIPE:
5220 buf->st_mode = S_IFIFO;
5221 goto non_disk;
5222 case FILE_TYPE_CHAR:
5223 case FILE_TYPE_UNKNOWN:
5224 default:
5225 buf->st_mode = S_IFCHR;
5226 non_disk:
5227 memset (&info, 0, sizeof (info));
5228 info.dwFileAttributes = 0;
5229 info.ftCreationTime = utc_base_ft;
5230 info.ftLastAccessTime = utc_base_ft;
5231 info.ftLastWriteTime = utc_base_ft;
5234 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5235 buf->st_mode = S_IFDIR;
5237 buf->st_nlink = info.nNumberOfLinks;
5238 /* Might as well use file index to fake inode values, but this
5239 is not guaranteed to be unique unless we keep a handle open
5240 all the time (even then there are situations where it is
5241 not unique). Reputedly, there are at most 48 bits of info
5242 (on NTFS, presumably less on FAT). */
5243 fake_inode = info.nFileIndexHigh;
5244 fake_inode <<= 32;
5245 fake_inode += info.nFileIndexLow;
5247 /* MSVC defines _ino_t to be short; other libc's might not. */
5248 if (sizeof (buf->st_ino) == 2)
5249 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5250 else
5251 buf->st_ino = fake_inode;
5253 /* If the caller so requested, get the true file owner and group.
5254 Otherwise, consider the file to belong to the current user. */
5255 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5256 get_file_owner_and_group (NULL, buf);
5257 else
5259 PSECURITY_DESCRIPTOR psd = NULL;
5261 psd = get_file_security_desc_by_handle (fh);
5262 if (psd)
5264 get_file_owner_and_group (psd, buf);
5265 LocalFree (psd);
5267 else
5268 get_file_owner_and_group (NULL, buf);
5271 buf->st_dev = info.dwVolumeSerialNumber;
5272 buf->st_rdev = info.dwVolumeSerialNumber;
5274 buf->st_size = info.nFileSizeHigh;
5275 buf->st_size <<= 32;
5276 buf->st_size += info.nFileSizeLow;
5278 /* Convert timestamps to Unix format. */
5279 buf->st_mtime = convert_time (info.ftLastWriteTime);
5280 buf->st_atime = convert_time (info.ftLastAccessTime);
5281 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5282 buf->st_ctime = convert_time (info.ftCreationTime);
5283 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5285 /* determine rwx permissions */
5286 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5287 permission = S_IREAD;
5288 else
5289 permission = S_IREAD | S_IWRITE;
5291 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5292 permission |= S_IEXEC;
5293 else
5295 #if 0 /* no way of knowing the filename */
5296 char * p = strrchr (name, '.');
5297 if (p != NULL &&
5298 (xstrcasecmp (p, ".exe") == 0 ||
5299 xstrcasecmp (p, ".com") == 0 ||
5300 xstrcasecmp (p, ".bat") == 0 ||
5301 xstrcasecmp (p, ".cmd") == 0))
5302 permission |= S_IEXEC;
5303 #endif
5306 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5308 return 0;
5311 /* A version of 'utime' which handles directories as well as
5312 files. */
5315 utime (const char *name, struct utimbuf *times)
5317 struct utimbuf deftime;
5318 HANDLE fh;
5319 FILETIME mtime;
5320 FILETIME atime;
5322 if (times == NULL)
5324 deftime.modtime = deftime.actime = time (NULL);
5325 times = &deftime;
5328 if (w32_unicode_filenames)
5330 wchar_t name_utf16[MAX_PATH];
5332 if (filename_to_utf16 (name, name_utf16) != 0)
5333 return -1; /* errno set by filename_to_utf16 */
5335 /* Need write access to set times. */
5336 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5337 /* If NAME specifies a directory, FILE_SHARE_DELETE
5338 allows other processes to delete files inside it,
5339 while we have the directory open. */
5340 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5341 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5343 else
5345 char name_ansi[MAX_PATH];
5347 if (filename_to_ansi (name, name_ansi) != 0)
5348 return -1; /* errno set by filename_to_ansi */
5350 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5351 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5352 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5354 if (fh != INVALID_HANDLE_VALUE)
5356 convert_from_time_t (times->actime, &atime);
5357 convert_from_time_t (times->modtime, &mtime);
5358 if (!SetFileTime (fh, NULL, &atime, &mtime))
5360 CloseHandle (fh);
5361 errno = EACCES;
5362 return -1;
5364 CloseHandle (fh);
5366 else
5368 DWORD err = GetLastError ();
5370 switch (err)
5372 case ERROR_FILE_NOT_FOUND:
5373 case ERROR_PATH_NOT_FOUND:
5374 case ERROR_INVALID_DRIVE:
5375 case ERROR_BAD_NETPATH:
5376 case ERROR_DEV_NOT_EXIST:
5377 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5378 file name includes ?s, i.e. translation to ANSI failed. */
5379 case ERROR_INVALID_NAME:
5380 errno = ENOENT;
5381 break;
5382 case ERROR_TOO_MANY_OPEN_FILES:
5383 errno = ENFILE;
5384 break;
5385 case ERROR_ACCESS_DENIED:
5386 case ERROR_SHARING_VIOLATION:
5387 errno = EACCES;
5388 break;
5389 default:
5390 errno = EINVAL;
5391 break;
5393 return -1;
5395 return 0;
5399 sys_umask (int mode)
5401 static int current_mask;
5402 int retval, arg = 0;
5404 /* The only bit we really support is the write bit. Files are
5405 always readable on MS-Windows, and the execute bit does not exist
5406 at all. */
5407 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5408 to prevent access by other users on NTFS. */
5409 if ((mode & S_IWRITE) != 0)
5410 arg |= S_IWRITE;
5412 retval = _umask (arg);
5413 /* Merge into the return value the bits they've set the last time,
5414 which msvcrt.dll ignores and never returns. Emacs insists on its
5415 notion of mask being identical to what we return. */
5416 retval |= (current_mask & ~S_IWRITE);
5417 current_mask = mode;
5419 return retval;
5423 /* Symlink-related functions. */
5424 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5425 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5426 #endif
5429 symlink (char const *filename, char const *linkname)
5431 char linkfn[MAX_UTF8_PATH], *tgtfn;
5432 DWORD flags = 0;
5433 int dir_access, filename_ends_in_slash;
5435 /* Diagnostics follows Posix as much as possible. */
5436 if (filename == NULL || linkname == NULL)
5438 errno = EFAULT;
5439 return -1;
5441 if (!*filename)
5443 errno = ENOENT;
5444 return -1;
5446 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5448 errno = ENAMETOOLONG;
5449 return -1;
5452 strcpy (linkfn, map_w32_filename (linkname, NULL));
5453 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5455 errno = EPERM;
5456 return -1;
5459 /* Note: since empty FILENAME was already rejected, we can safely
5460 refer to FILENAME[1]. */
5461 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5463 /* Non-absolute FILENAME is understood as being relative to
5464 LINKNAME's directory. We need to prepend that directory to
5465 FILENAME to get correct results from faccessat below, since
5466 otherwise it will interpret FILENAME relative to the
5467 directory where the Emacs process runs. Note that
5468 make-symbolic-link always makes sure LINKNAME is a fully
5469 expanded file name. */
5470 char tem[MAX_UTF8_PATH];
5471 char *p = linkfn + strlen (linkfn);
5473 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5474 p--;
5475 if (p > linkfn)
5476 strncpy (tem, linkfn, p - linkfn);
5477 tem[p - linkfn] = '\0';
5478 strcat (tem, filename);
5479 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5481 else
5482 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5484 /* Since Windows distinguishes between symlinks to directories and
5485 to files, we provide a kludgy feature: if FILENAME doesn't
5486 exist, but ends in a slash, we create a symlink to directory. If
5487 FILENAME exists and is a directory, we always create a symlink to
5488 directory. */
5489 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5490 if (dir_access == 0 || filename_ends_in_slash)
5491 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5493 tgtfn = (char *)map_w32_filename (filename, NULL);
5494 if (filename_ends_in_slash)
5495 tgtfn[strlen (tgtfn) - 1] = '\0';
5497 errno = 0;
5498 if (!create_symbolic_link (linkfn, tgtfn, flags))
5500 /* ENOSYS is set by create_symbolic_link, when it detects that
5501 the OS doesn't support the CreateSymbolicLink API. */
5502 if (errno != ENOSYS)
5504 DWORD w32err = GetLastError ();
5506 switch (w32err)
5508 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5509 TGTFN point to the same file name, go figure. */
5510 case ERROR_SUCCESS:
5511 case ERROR_FILE_EXISTS:
5512 errno = EEXIST;
5513 break;
5514 case ERROR_ACCESS_DENIED:
5515 errno = EACCES;
5516 break;
5517 case ERROR_FILE_NOT_FOUND:
5518 case ERROR_PATH_NOT_FOUND:
5519 case ERROR_BAD_NETPATH:
5520 case ERROR_INVALID_REPARSE_DATA:
5521 errno = ENOENT;
5522 break;
5523 case ERROR_DIRECTORY:
5524 errno = EISDIR;
5525 break;
5526 case ERROR_PRIVILEGE_NOT_HELD:
5527 case ERROR_NOT_ALL_ASSIGNED:
5528 errno = EPERM;
5529 break;
5530 case ERROR_DISK_FULL:
5531 errno = ENOSPC;
5532 break;
5533 default:
5534 errno = EINVAL;
5535 break;
5538 return -1;
5540 return 0;
5543 /* A quick inexpensive test of whether FILENAME identifies a file that
5544 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5545 must already be in the normalized form returned by
5546 map_w32_filename.
5548 Note: for repeated operations on many files, it is best to test
5549 whether the underlying volume actually supports symlinks, by
5550 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5551 avoid the call to this function if it doesn't. That's because the
5552 call to GetFileAttributes takes a non-negligible time, especially
5553 on non-local or removable filesystems. See stat_worker for an
5554 example of how to do that. */
5555 static int
5556 is_symlink (const char *filename)
5558 DWORD attrs;
5559 wchar_t filename_w[MAX_PATH];
5560 char filename_a[MAX_PATH];
5561 WIN32_FIND_DATAW wfdw;
5562 WIN32_FIND_DATAA wfda;
5563 HANDLE fh;
5564 int attrs_mean_symlink;
5566 if (w32_unicode_filenames)
5568 filename_to_utf16 (filename, filename_w);
5569 attrs = GetFileAttributesW (filename_w);
5571 else
5573 filename_to_ansi (filename, filename_a);
5574 attrs = GetFileAttributesA (filename_a);
5576 if (attrs == -1)
5578 DWORD w32err = GetLastError ();
5580 switch (w32err)
5582 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5583 break;
5584 case ERROR_ACCESS_DENIED:
5585 errno = EACCES;
5586 break;
5587 case ERROR_FILE_NOT_FOUND:
5588 case ERROR_PATH_NOT_FOUND:
5589 default:
5590 errno = ENOENT;
5591 break;
5593 return 0;
5595 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5596 return 0;
5597 logon_network_drive (filename);
5598 if (w32_unicode_filenames)
5600 fh = FindFirstFileW (filename_w, &wfdw);
5601 attrs_mean_symlink =
5602 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5603 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5605 else if (_mbspbrk (filename_a, "?"))
5607 /* filename_to_ansi failed to convert the file name. */
5608 errno = ENOENT;
5609 return 0;
5611 else
5613 fh = FindFirstFileA (filename_a, &wfda);
5614 attrs_mean_symlink =
5615 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5616 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5618 if (fh == INVALID_HANDLE_VALUE)
5619 return 0;
5620 FindClose (fh);
5621 return attrs_mean_symlink;
5624 /* If NAME identifies a symbolic link, copy into BUF the file name of
5625 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5626 null-terminate the target name, even if it fits. Return the number
5627 of bytes copied, or -1 if NAME is not a symlink or any error was
5628 encountered while resolving it. The file name copied into BUF is
5629 encoded in the current ANSI codepage. */
5630 ssize_t
5631 readlink (const char *name, char *buf, size_t buf_size)
5633 const char *path;
5634 TOKEN_PRIVILEGES privs;
5635 int restore_privs = 0;
5636 HANDLE sh;
5637 ssize_t retval;
5638 char resolved[MAX_UTF8_PATH];
5640 if (name == NULL)
5642 errno = EFAULT;
5643 return -1;
5645 if (!*name)
5647 errno = ENOENT;
5648 return -1;
5651 path = map_w32_filename (name, NULL);
5653 if (strlen (path) > MAX_UTF8_PATH)
5655 errno = ENAMETOOLONG;
5656 return -1;
5659 errno = 0;
5660 if (is_windows_9x () == TRUE
5661 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5662 || !is_symlink (path))
5664 if (!errno)
5665 errno = EINVAL; /* not a symlink */
5666 return -1;
5669 /* Done with simple tests, now we're in for some _real_ work. */
5670 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5671 restore_privs = 1;
5672 /* Implementation note: From here and onward, don't return early,
5673 since that will fail to restore the original set of privileges of
5674 the calling thread. */
5676 retval = -1; /* not too optimistic, are we? */
5678 /* Note: In the next call to CreateFile, we use zero as the 2nd
5679 argument because, when the symlink is a hidden/system file,
5680 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5681 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5682 and directory symlinks. */
5683 if (w32_unicode_filenames)
5685 wchar_t path_w[MAX_PATH];
5687 filename_to_utf16 (path, path_w);
5688 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5689 FILE_FLAG_OPEN_REPARSE_POINT
5690 | FILE_FLAG_BACKUP_SEMANTICS,
5691 NULL);
5693 else
5695 char path_a[MAX_PATH];
5697 filename_to_ansi (path, path_a);
5698 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5699 FILE_FLAG_OPEN_REPARSE_POINT
5700 | FILE_FLAG_BACKUP_SEMANTICS,
5701 NULL);
5703 if (sh != INVALID_HANDLE_VALUE)
5705 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5706 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5707 DWORD retbytes;
5709 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5710 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5711 &retbytes, NULL))
5712 errno = EIO;
5713 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5714 errno = EINVAL;
5715 else
5717 /* Copy the link target name, in wide characters, from
5718 reparse_data, then convert it to multibyte encoding in
5719 the current locale's codepage. */
5720 WCHAR *lwname;
5721 size_t lname_size;
5722 USHORT lwname_len =
5723 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5724 WCHAR *lwname_src =
5725 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5726 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5727 size_t size_to_copy = buf_size;
5729 /* According to MSDN, PrintNameLength does not include the
5730 terminating null character. */
5731 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5732 memcpy (lwname, lwname_src, lwname_len);
5733 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5734 filename_from_utf16 (lwname, resolved);
5735 dostounix_filename (resolved);
5736 lname_size = strlen (resolved) + 1;
5737 if (lname_size <= buf_size)
5738 size_to_copy = lname_size;
5739 strncpy (buf, resolved, size_to_copy);
5740 /* Success! */
5741 retval = size_to_copy;
5743 CloseHandle (sh);
5745 else
5747 /* CreateFile failed. */
5748 DWORD w32err2 = GetLastError ();
5750 switch (w32err2)
5752 case ERROR_FILE_NOT_FOUND:
5753 case ERROR_PATH_NOT_FOUND:
5754 errno = ENOENT;
5755 break;
5756 case ERROR_ACCESS_DENIED:
5757 case ERROR_TOO_MANY_OPEN_FILES:
5758 errno = EACCES;
5759 break;
5760 default:
5761 errno = EPERM;
5762 break;
5765 if (restore_privs)
5767 restore_privilege (&privs);
5768 revert_to_self ();
5771 return retval;
5774 ssize_t
5775 readlinkat (int fd, char const *name, char *buffer,
5776 size_t buffer_size)
5778 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5779 as in fstatat. FIXME: Add proper support for readlinkat. */
5780 char fullname[MAX_UTF8_PATH];
5782 if (fd != AT_FDCWD)
5784 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5785 < 0)
5787 errno = ENAMETOOLONG;
5788 return -1;
5790 name = fullname;
5793 return readlink (name, buffer, buffer_size);
5796 /* If FILE is a symlink, return its target (stored in a static
5797 buffer); otherwise return FILE.
5799 This function repeatedly resolves symlinks in the last component of
5800 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5801 until it arrives at a file whose last component is not a symlink,
5802 or some error occurs. It returns the target of the last
5803 successfully resolved symlink in the chain. If it succeeds to
5804 resolve even a single symlink, the value returned is an absolute
5805 file name with backslashes (result of GetFullPathName). By
5806 contrast, if the original FILE is returned, it is unaltered.
5808 Note: This function can set errno even if it succeeds.
5810 Implementation note: we only resolve the last portion ("basename")
5811 of the argument FILE and of each following file in the chain,
5812 disregarding any possible symlinks in its leading directories.
5813 This is because Windows system calls and library functions
5814 transparently resolve symlinks in leading directories and return
5815 correct information, as long as the basename is not a symlink. */
5816 static char *
5817 chase_symlinks (const char *file)
5819 static char target[MAX_UTF8_PATH];
5820 char link[MAX_UTF8_PATH];
5821 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5822 char target_a[MAX_PATH], link_a[MAX_PATH];
5823 ssize_t res, link_len;
5824 int loop_count = 0;
5826 if (is_windows_9x () == TRUE || !is_symlink (file))
5827 return (char *)file;
5829 if (w32_unicode_filenames)
5831 wchar_t file_w[MAX_PATH];
5833 filename_to_utf16 (file, file_w);
5834 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5835 return (char *)file;
5836 filename_from_utf16 (link_w, link);
5838 else
5840 char file_a[MAX_PATH];
5842 filename_to_ansi (file, file_a);
5843 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
5844 return (char *)file;
5845 filename_from_ansi (link_a, link);
5847 link_len = strlen (link);
5849 target[0] = '\0';
5850 do {
5852 /* Remove trailing slashes, as we want to resolve the last
5853 non-trivial part of the link name. */
5854 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5855 link[link_len--] = '\0';
5857 res = readlink (link, target, MAX_UTF8_PATH);
5858 if (res > 0)
5860 target[res] = '\0';
5861 if (!(IS_DEVICE_SEP (target[1])
5862 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5864 /* Target is relative. Append it to the directory part of
5865 the symlink, then copy the result back to target. */
5866 char *p = link + link_len;
5868 while (p > link && !IS_ANY_SEP (p[-1]))
5869 p--;
5870 strcpy (p, target);
5871 strcpy (target, link);
5873 /* Resolve any "." and ".." to get a fully-qualified file name
5874 in link[] again. */
5875 if (w32_unicode_filenames)
5877 filename_to_utf16 (target, target_w);
5878 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
5879 if (link_len > 0)
5880 filename_from_utf16 (link_w, link);
5882 else
5884 filename_to_ansi (target, target_a);
5885 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
5886 if (link_len > 0)
5887 filename_from_ansi (link_a, link);
5889 link_len = strlen (link);
5891 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5893 if (loop_count > 100)
5894 errno = ELOOP;
5896 if (target[0] == '\0') /* not a single call to readlink succeeded */
5897 return (char *)file;
5898 return target;
5902 /* Posix ACL emulation. */
5905 acl_valid (acl_t acl)
5907 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5910 char *
5911 acl_to_text (acl_t acl, ssize_t *size)
5913 LPTSTR str_acl;
5914 SECURITY_INFORMATION flags =
5915 OWNER_SECURITY_INFORMATION |
5916 GROUP_SECURITY_INFORMATION |
5917 DACL_SECURITY_INFORMATION;
5918 char *retval = NULL;
5919 ULONG local_size;
5920 int e = errno;
5922 errno = 0;
5924 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5926 errno = e;
5927 /* We don't want to mix heaps, so we duplicate the string in our
5928 heap and free the one allocated by the API. */
5929 retval = xstrdup (str_acl);
5930 if (size)
5931 *size = local_size;
5932 LocalFree (str_acl);
5934 else if (errno != ENOTSUP)
5935 errno = EINVAL;
5937 return retval;
5940 acl_t
5941 acl_from_text (const char *acl_str)
5943 PSECURITY_DESCRIPTOR psd, retval = NULL;
5944 ULONG sd_size;
5945 int e = errno;
5947 errno = 0;
5949 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5951 errno = e;
5952 retval = xmalloc (sd_size);
5953 memcpy (retval, psd, sd_size);
5954 LocalFree (psd);
5956 else if (errno != ENOTSUP)
5957 errno = EINVAL;
5959 return retval;
5963 acl_free (void *ptr)
5965 xfree (ptr);
5966 return 0;
5969 acl_t
5970 acl_get_file (const char *fname, acl_type_t type)
5972 PSECURITY_DESCRIPTOR psd = NULL;
5973 const char *filename;
5975 if (type == ACL_TYPE_ACCESS)
5977 DWORD sd_len, err;
5978 SECURITY_INFORMATION si =
5979 OWNER_SECURITY_INFORMATION |
5980 GROUP_SECURITY_INFORMATION |
5981 DACL_SECURITY_INFORMATION ;
5982 int e = errno;
5984 filename = map_w32_filename (fname, NULL);
5985 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5986 fname = chase_symlinks (filename);
5987 else
5988 fname = filename;
5990 errno = 0;
5991 if (!get_file_security (fname, si, psd, 0, &sd_len)
5992 && errno != ENOTSUP)
5994 err = GetLastError ();
5995 if (err == ERROR_INSUFFICIENT_BUFFER)
5997 psd = xmalloc (sd_len);
5998 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6000 xfree (psd);
6001 errno = EIO;
6002 psd = NULL;
6005 else if (err == ERROR_FILE_NOT_FOUND
6006 || err == ERROR_PATH_NOT_FOUND
6007 /* ERROR_INVALID_NAME is what we get if
6008 w32-unicode-filenames is nil and the file cannot
6009 be encoded in the current ANSI codepage. */
6010 || err == ERROR_INVALID_NAME)
6011 errno = ENOENT;
6012 else
6013 errno = EIO;
6015 else if (!errno)
6016 errno = e;
6018 else if (type != ACL_TYPE_DEFAULT)
6019 errno = EINVAL;
6021 return psd;
6025 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6027 TOKEN_PRIVILEGES old1, old2;
6028 DWORD err;
6029 int st = 0, retval = -1;
6030 SECURITY_INFORMATION flags = 0;
6031 PSID psidOwner, psidGroup;
6032 PACL pacl;
6033 BOOL dflt;
6034 BOOL dacl_present;
6035 int e;
6036 const char *filename;
6038 if (acl_valid (acl) != 0
6039 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6041 errno = EINVAL;
6042 return -1;
6045 if (type == ACL_TYPE_DEFAULT)
6047 errno = ENOSYS;
6048 return -1;
6051 filename = map_w32_filename (fname, NULL);
6052 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6053 fname = chase_symlinks (filename);
6054 else
6055 fname = filename;
6057 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6058 &dflt)
6059 && psidOwner)
6060 flags |= OWNER_SECURITY_INFORMATION;
6061 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6062 &dflt)
6063 && psidGroup)
6064 flags |= GROUP_SECURITY_INFORMATION;
6065 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6066 &pacl, &dflt)
6067 && dacl_present)
6068 flags |= DACL_SECURITY_INFORMATION;
6069 if (!flags)
6070 return 0;
6072 /* According to KB-245153, setting the owner will succeed if either:
6073 (1) the caller is the user who will be the new owner, and has the
6074 SE_TAKE_OWNERSHIP privilege, or
6075 (2) the caller has the SE_RESTORE privilege, in which case she can
6076 set any valid user or group as the owner
6078 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6079 privileges, and disregard any failures in obtaining them. If
6080 these privileges cannot be obtained, and do not already exist in
6081 the calling thread's security token, this function could fail
6082 with EPERM. */
6083 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6084 st++;
6085 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6086 st++;
6088 e = errno;
6089 errno = 0;
6090 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6091 DACL inheritance is involved, but it seems to preserve ownership
6092 better than SetNamedSecurityInfo, which is important e.g., in
6093 copy-file. */
6094 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6096 err = GetLastError ();
6098 if (errno != ENOTSUP)
6099 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6100 psidOwner, psidGroup, pacl, NULL);
6102 else
6103 err = ERROR_SUCCESS;
6104 if (err != ERROR_SUCCESS)
6106 if (errno == ENOTSUP)
6108 else if (err == ERROR_INVALID_OWNER
6109 || err == ERROR_NOT_ALL_ASSIGNED
6110 || err == ERROR_ACCESS_DENIED)
6112 /* Maybe the requested ACL and the one the file already has
6113 are identical, in which case we can silently ignore the
6114 failure. (And no, Windows doesn't.) */
6115 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6117 errno = EPERM;
6118 if (current_acl)
6120 char *acl_from = acl_to_text (current_acl, NULL);
6121 char *acl_to = acl_to_text (acl, NULL);
6123 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6125 retval = 0;
6126 errno = e;
6128 if (acl_from)
6129 acl_free (acl_from);
6130 if (acl_to)
6131 acl_free (acl_to);
6132 acl_free (current_acl);
6135 else if (err == ERROR_FILE_NOT_FOUND
6136 || err == ERROR_PATH_NOT_FOUND
6137 /* ERROR_INVALID_NAME is what we get if
6138 w32-unicode-filenames is nil and the file cannot be
6139 encoded in the current ANSI codepage. */
6140 || err == ERROR_INVALID_NAME)
6141 errno = ENOENT;
6142 else
6143 errno = EACCES;
6145 else
6147 retval = 0;
6148 errno = e;
6151 if (st)
6153 if (st >= 2)
6154 restore_privilege (&old2);
6155 restore_privilege (&old1);
6156 revert_to_self ();
6159 return retval;
6163 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6164 have a fixed max size for file names, so we don't need the kind of
6165 alloc/malloc/realloc dance the gnulib version does. We also don't
6166 support FD-relative symlinks. */
6167 char *
6168 careadlinkat (int fd, char const *filename,
6169 char *buffer, size_t buffer_size,
6170 struct allocator const *alloc,
6171 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6173 char linkname[MAX_UTF8_PATH];
6174 ssize_t link_size;
6176 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6178 if (link_size > 0)
6180 char *retval = buffer;
6182 linkname[link_size++] = '\0';
6183 if (link_size > buffer_size)
6184 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6185 if (retval)
6186 memcpy (retval, linkname, link_size);
6188 return retval;
6190 return NULL;
6194 w32_copy_file (const char *from, const char *to,
6195 int keep_time, int preserve_ownership, int copy_acls)
6197 acl_t acl = NULL;
6198 BOOL copy_result;
6199 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6200 char from_a[MAX_PATH], to_a[MAX_PATH];
6202 /* We ignore preserve_ownership for now. */
6203 preserve_ownership = preserve_ownership;
6205 if (copy_acls)
6207 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6208 if (acl == NULL && acl_errno_valid (errno))
6209 return -2;
6211 if (w32_unicode_filenames)
6213 filename_to_utf16 (from, from_w);
6214 filename_to_utf16 (to, to_w);
6215 copy_result = CopyFileW (from_w, to_w, FALSE);
6217 else
6219 filename_to_ansi (from, from_a);
6220 filename_to_ansi (to, to_a);
6221 copy_result = CopyFileA (from_a, to_a, FALSE);
6223 if (!copy_result)
6225 /* CopyFile doesn't set errno when it fails. By far the most
6226 "popular" reason is that the target is read-only. */
6227 DWORD err = GetLastError ();
6229 switch (err)
6231 case ERROR_FILE_NOT_FOUND:
6232 errno = ENOENT;
6233 break;
6234 case ERROR_ACCESS_DENIED:
6235 errno = EACCES;
6236 break;
6237 case ERROR_ENCRYPTION_FAILED:
6238 errno = EIO;
6239 break;
6240 default:
6241 errno = EPERM;
6242 break;
6245 if (acl)
6246 acl_free (acl);
6247 return -1;
6249 /* CopyFile retains the timestamp by default. However, see
6250 "Community Additions" for CopyFile: it sounds like that is not
6251 entirely true. Testing on Windows XP confirms that modified time
6252 is copied, but creation and last-access times are not.
6253 FIXME? */
6254 else if (!keep_time)
6256 struct timespec now;
6257 DWORD attributes;
6259 if (w32_unicode_filenames)
6261 /* Ensure file is writable while its times are set. */
6262 attributes = GetFileAttributesW (to_w);
6263 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6264 now = current_timespec ();
6265 if (set_file_times (-1, to, now, now))
6267 /* Restore original attributes. */
6268 SetFileAttributesW (to_w, attributes);
6269 if (acl)
6270 acl_free (acl);
6271 return -3;
6273 /* Restore original attributes. */
6274 SetFileAttributesW (to_w, attributes);
6276 else
6278 attributes = GetFileAttributesA (to_a);
6279 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6280 now = current_timespec ();
6281 if (set_file_times (-1, to, now, now))
6283 SetFileAttributesA (to_a, attributes);
6284 if (acl)
6285 acl_free (acl);
6286 return -3;
6288 SetFileAttributesA (to_a, attributes);
6291 if (acl != NULL)
6293 bool fail =
6294 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6295 acl_free (acl);
6296 if (fail && acl_errno_valid (errno))
6297 return -4;
6300 return 0;
6304 /* Support for browsing other processes and their attributes. See
6305 process.c for the Lisp bindings. */
6307 /* Helper wrapper functions. */
6309 static HANDLE WINAPI
6310 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6312 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6314 if (g_b_init_create_toolhelp32_snapshot == 0)
6316 g_b_init_create_toolhelp32_snapshot = 1;
6317 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6318 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6319 "CreateToolhelp32Snapshot");
6321 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6323 return INVALID_HANDLE_VALUE;
6325 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6328 static BOOL WINAPI
6329 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6331 static Process32First_Proc s_pfn_Process32_First = NULL;
6333 if (g_b_init_process32_first == 0)
6335 g_b_init_process32_first = 1;
6336 s_pfn_Process32_First = (Process32First_Proc)
6337 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6338 "Process32First");
6340 if (s_pfn_Process32_First == NULL)
6342 return FALSE;
6344 return (s_pfn_Process32_First (hSnapshot, lppe));
6347 static BOOL WINAPI
6348 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6350 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6352 if (g_b_init_process32_next == 0)
6354 g_b_init_process32_next = 1;
6355 s_pfn_Process32_Next = (Process32Next_Proc)
6356 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6357 "Process32Next");
6359 if (s_pfn_Process32_Next == NULL)
6361 return FALSE;
6363 return (s_pfn_Process32_Next (hSnapshot, lppe));
6366 static BOOL WINAPI
6367 open_thread_token (HANDLE ThreadHandle,
6368 DWORD DesiredAccess,
6369 BOOL OpenAsSelf,
6370 PHANDLE TokenHandle)
6372 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6373 HMODULE hm_advapi32 = NULL;
6374 if (is_windows_9x () == TRUE)
6376 SetLastError (ERROR_NOT_SUPPORTED);
6377 return FALSE;
6379 if (g_b_init_open_thread_token == 0)
6381 g_b_init_open_thread_token = 1;
6382 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6383 s_pfn_Open_Thread_Token =
6384 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6386 if (s_pfn_Open_Thread_Token == NULL)
6388 SetLastError (ERROR_NOT_SUPPORTED);
6389 return FALSE;
6391 return (
6392 s_pfn_Open_Thread_Token (
6393 ThreadHandle,
6394 DesiredAccess,
6395 OpenAsSelf,
6396 TokenHandle)
6400 static BOOL WINAPI
6401 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6403 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6404 HMODULE hm_advapi32 = NULL;
6405 if (is_windows_9x () == TRUE)
6407 return FALSE;
6409 if (g_b_init_impersonate_self == 0)
6411 g_b_init_impersonate_self = 1;
6412 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6413 s_pfn_Impersonate_Self =
6414 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6416 if (s_pfn_Impersonate_Self == NULL)
6418 return FALSE;
6420 return s_pfn_Impersonate_Self (ImpersonationLevel);
6423 static BOOL WINAPI
6424 revert_to_self (void)
6426 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6427 HMODULE hm_advapi32 = NULL;
6428 if (is_windows_9x () == TRUE)
6430 return FALSE;
6432 if (g_b_init_revert_to_self == 0)
6434 g_b_init_revert_to_self = 1;
6435 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6436 s_pfn_Revert_To_Self =
6437 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6439 if (s_pfn_Revert_To_Self == NULL)
6441 return FALSE;
6443 return s_pfn_Revert_To_Self ();
6446 static BOOL WINAPI
6447 get_process_memory_info (HANDLE h_proc,
6448 PPROCESS_MEMORY_COUNTERS mem_counters,
6449 DWORD bufsize)
6451 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6452 HMODULE hm_psapi = NULL;
6453 if (is_windows_9x () == TRUE)
6455 return FALSE;
6457 if (g_b_init_get_process_memory_info == 0)
6459 g_b_init_get_process_memory_info = 1;
6460 hm_psapi = LoadLibrary ("Psapi.dll");
6461 if (hm_psapi)
6462 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6463 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6465 if (s_pfn_Get_Process_Memory_Info == NULL)
6467 return FALSE;
6469 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6472 static BOOL WINAPI
6473 get_process_working_set_size (HANDLE h_proc,
6474 PSIZE_T minrss,
6475 PSIZE_T maxrss)
6477 static GetProcessWorkingSetSize_Proc
6478 s_pfn_Get_Process_Working_Set_Size = NULL;
6480 if (is_windows_9x () == TRUE)
6482 return FALSE;
6484 if (g_b_init_get_process_working_set_size == 0)
6486 g_b_init_get_process_working_set_size = 1;
6487 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6488 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6489 "GetProcessWorkingSetSize");
6491 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6493 return FALSE;
6495 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6498 static BOOL WINAPI
6499 global_memory_status (MEMORYSTATUS *buf)
6501 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6503 if (is_windows_9x () == TRUE)
6505 return FALSE;
6507 if (g_b_init_global_memory_status == 0)
6509 g_b_init_global_memory_status = 1;
6510 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6511 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6512 "GlobalMemoryStatus");
6514 if (s_pfn_Global_Memory_Status == NULL)
6516 return FALSE;
6518 return s_pfn_Global_Memory_Status (buf);
6521 static BOOL WINAPI
6522 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6524 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6526 if (is_windows_9x () == TRUE)
6528 return FALSE;
6530 if (g_b_init_global_memory_status_ex == 0)
6532 g_b_init_global_memory_status_ex = 1;
6533 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6534 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6535 "GlobalMemoryStatusEx");
6537 if (s_pfn_Global_Memory_Status_Ex == NULL)
6539 return FALSE;
6541 return s_pfn_Global_Memory_Status_Ex (buf);
6544 Lisp_Object
6545 list_system_processes (void)
6547 struct gcpro gcpro1;
6548 Lisp_Object proclist = Qnil;
6549 HANDLE h_snapshot;
6551 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6553 if (h_snapshot != INVALID_HANDLE_VALUE)
6555 PROCESSENTRY32 proc_entry;
6556 DWORD proc_id;
6557 BOOL res;
6559 GCPRO1 (proclist);
6561 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6562 for (res = process32_first (h_snapshot, &proc_entry); res;
6563 res = process32_next (h_snapshot, &proc_entry))
6565 proc_id = proc_entry.th32ProcessID;
6566 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6569 CloseHandle (h_snapshot);
6570 UNGCPRO;
6571 proclist = Fnreverse (proclist);
6574 return proclist;
6577 static int
6578 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6580 TOKEN_PRIVILEGES priv;
6581 DWORD priv_size = sizeof (priv);
6582 DWORD opriv_size = sizeof (*old_priv);
6583 HANDLE h_token = NULL;
6584 HANDLE h_thread = GetCurrentThread ();
6585 int ret_val = 0;
6586 BOOL res;
6588 res = open_thread_token (h_thread,
6589 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6590 FALSE, &h_token);
6591 if (!res && GetLastError () == ERROR_NO_TOKEN)
6593 if (impersonate_self (SecurityImpersonation))
6594 res = open_thread_token (h_thread,
6595 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6596 FALSE, &h_token);
6598 if (res)
6600 priv.PrivilegeCount = 1;
6601 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6602 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6603 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6604 old_priv, &opriv_size)
6605 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6606 ret_val = 1;
6608 if (h_token)
6609 CloseHandle (h_token);
6611 return ret_val;
6614 static int
6615 restore_privilege (TOKEN_PRIVILEGES *priv)
6617 DWORD priv_size = sizeof (*priv);
6618 HANDLE h_token = NULL;
6619 int ret_val = 0;
6621 if (open_thread_token (GetCurrentThread (),
6622 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6623 FALSE, &h_token))
6625 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6626 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6627 ret_val = 1;
6629 if (h_token)
6630 CloseHandle (h_token);
6632 return ret_val;
6635 static Lisp_Object
6636 ltime (ULONGLONG time_100ns)
6638 ULONGLONG time_sec = time_100ns / 10000000;
6639 int subsec = time_100ns % 10000000;
6640 return list4i (time_sec >> 16, time_sec & 0xffff,
6641 subsec / 10, subsec % 10 * 100000);
6644 #define U64_TO_LISP_TIME(time) ltime (time)
6646 static int
6647 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6648 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6649 double *pcpu)
6651 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6652 ULONGLONG tem1, tem2, tem3, tem;
6654 if (!h_proc
6655 || !get_process_times_fn
6656 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6657 &ft_kernel, &ft_user))
6658 return 0;
6660 GetSystemTimeAsFileTime (&ft_current);
6662 FILETIME_TO_U64 (tem1, ft_kernel);
6663 *stime = U64_TO_LISP_TIME (tem1);
6665 FILETIME_TO_U64 (tem2, ft_user);
6666 *utime = U64_TO_LISP_TIME (tem2);
6668 tem3 = tem1 + tem2;
6669 *ttime = U64_TO_LISP_TIME (tem3);
6671 FILETIME_TO_U64 (tem, ft_creation);
6672 /* Process no 4 (System) returns zero creation time. */
6673 if (tem)
6674 tem -= utc_base;
6675 *ctime = U64_TO_LISP_TIME (tem);
6677 if (tem)
6679 FILETIME_TO_U64 (tem3, ft_current);
6680 tem = (tem3 - utc_base) - tem;
6682 *etime = U64_TO_LISP_TIME (tem);
6684 if (tem)
6686 *pcpu = 100.0 * (tem1 + tem2) / tem;
6687 if (*pcpu > 100)
6688 *pcpu = 100.0;
6690 else
6691 *pcpu = 0;
6693 return 1;
6696 Lisp_Object
6697 system_process_attributes (Lisp_Object pid)
6699 struct gcpro gcpro1, gcpro2, gcpro3;
6700 Lisp_Object attrs = Qnil;
6701 Lisp_Object cmd_str, decoded_cmd, tem;
6702 HANDLE h_snapshot, h_proc;
6703 DWORD proc_id;
6704 int found_proc = 0;
6705 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6706 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6707 DWORD glength = sizeof (gname);
6708 HANDLE token = NULL;
6709 SID_NAME_USE user_type;
6710 unsigned char *buf = NULL;
6711 DWORD blen = 0;
6712 TOKEN_USER user_token;
6713 TOKEN_PRIMARY_GROUP group_token;
6714 unsigned euid;
6715 unsigned egid;
6716 PROCESS_MEMORY_COUNTERS mem;
6717 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6718 SIZE_T minrss, maxrss;
6719 MEMORYSTATUS memst;
6720 MEMORY_STATUS_EX memstex;
6721 double totphys = 0.0;
6722 Lisp_Object ctime, stime, utime, etime, ttime;
6723 double pcpu;
6724 BOOL result = FALSE;
6726 CHECK_NUMBER_OR_FLOAT (pid);
6727 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6729 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6731 GCPRO3 (attrs, decoded_cmd, tem);
6733 if (h_snapshot != INVALID_HANDLE_VALUE)
6735 PROCESSENTRY32 pe;
6736 BOOL res;
6738 pe.dwSize = sizeof (PROCESSENTRY32);
6739 for (res = process32_first (h_snapshot, &pe); res;
6740 res = process32_next (h_snapshot, &pe))
6742 if (proc_id == pe.th32ProcessID)
6744 if (proc_id == 0)
6745 decoded_cmd = build_string ("Idle");
6746 else
6748 /* Decode the command name from locale-specific
6749 encoding. */
6750 cmd_str = build_unibyte_string (pe.szExeFile);
6752 decoded_cmd =
6753 code_convert_string_norecord (cmd_str,
6754 Vlocale_coding_system, 0);
6756 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6757 attrs = Fcons (Fcons (Qppid,
6758 make_fixnum_or_float (pe.th32ParentProcessID)),
6759 attrs);
6760 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6761 attrs);
6762 attrs = Fcons (Fcons (Qthcount,
6763 make_fixnum_or_float (pe.cntThreads)),
6764 attrs);
6765 found_proc = 1;
6766 break;
6770 CloseHandle (h_snapshot);
6773 if (!found_proc)
6775 UNGCPRO;
6776 return Qnil;
6779 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6780 FALSE, proc_id);
6781 /* If we were denied a handle to the process, try again after
6782 enabling the SeDebugPrivilege in our process. */
6783 if (!h_proc)
6785 TOKEN_PRIVILEGES priv_current;
6787 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6789 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6790 FALSE, proc_id);
6791 restore_privilege (&priv_current);
6792 revert_to_self ();
6795 if (h_proc)
6797 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6798 if (result)
6800 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6801 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6803 buf = xmalloc (blen);
6804 result = get_token_information (token, TokenUser,
6805 (LPVOID)buf, blen, &needed);
6806 if (result)
6808 memcpy (&user_token, buf, sizeof (user_token));
6809 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6811 euid = get_rid (user_token.User.Sid);
6812 result = lookup_account_sid (NULL, user_token.User.Sid,
6813 uname, &ulength,
6814 domain, &dlength,
6815 &user_type);
6816 if (result)
6817 w32_add_to_cache (user_token.User.Sid, euid, uname);
6818 else
6820 strcpy (uname, "unknown");
6821 result = TRUE;
6824 ulength = strlen (uname);
6828 if (result)
6830 /* Determine a reasonable euid and gid values. */
6831 if (xstrcasecmp ("administrator", uname) == 0)
6833 euid = 500; /* well-known Administrator uid */
6834 egid = 513; /* well-known None gid */
6836 else
6838 /* Get group id and name. */
6839 result = get_token_information (token, TokenPrimaryGroup,
6840 (LPVOID)buf, blen, &needed);
6841 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6843 buf = xrealloc (buf, blen = needed);
6844 result = get_token_information (token, TokenPrimaryGroup,
6845 (LPVOID)buf, blen, &needed);
6847 if (result)
6849 memcpy (&group_token, buf, sizeof (group_token));
6850 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6852 egid = get_rid (group_token.PrimaryGroup);
6853 dlength = sizeof (domain);
6854 result =
6855 lookup_account_sid (NULL, group_token.PrimaryGroup,
6856 gname, &glength, NULL, &dlength,
6857 &user_type);
6858 if (result)
6859 w32_add_to_cache (group_token.PrimaryGroup,
6860 egid, gname);
6861 else
6863 strcpy (gname, "None");
6864 result = TRUE;
6867 glength = strlen (gname);
6871 xfree (buf);
6873 if (!result)
6875 if (!is_windows_9x ())
6877 /* We couldn't open the process token, presumably because of
6878 insufficient access rights. Assume this process is run
6879 by the system. */
6880 strcpy (uname, "SYSTEM");
6881 strcpy (gname, "None");
6882 euid = 18; /* SYSTEM */
6883 egid = 513; /* None */
6884 glength = strlen (gname);
6885 ulength = strlen (uname);
6887 /* If we are running under Windows 9X, where security calls are
6888 not supported, we assume all processes are run by the current
6889 user. */
6890 else if (GetUserName (uname, &ulength))
6892 if (xstrcasecmp ("administrator", uname) == 0)
6893 euid = 0;
6894 else
6895 euid = 123;
6896 egid = euid;
6897 strcpy (gname, "None");
6898 glength = strlen (gname);
6899 ulength = strlen (uname);
6901 else
6903 euid = 123;
6904 egid = 123;
6905 strcpy (uname, "administrator");
6906 ulength = strlen (uname);
6907 strcpy (gname, "None");
6908 glength = strlen (gname);
6910 if (token)
6911 CloseHandle (token);
6914 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
6915 tem = make_unibyte_string (uname, ulength);
6916 attrs = Fcons (Fcons (Quser,
6917 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6918 attrs);
6919 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
6920 tem = make_unibyte_string (gname, glength);
6921 attrs = Fcons (Fcons (Qgroup,
6922 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6923 attrs);
6925 if (global_memory_status_ex (&memstex))
6926 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6927 totphys = memstex.ullTotalPhys / 1024.0;
6928 #else
6929 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6930 double, so we need to do this for it... */
6932 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6933 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6934 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6936 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6938 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6939 else if (global_memory_status (&memst))
6940 totphys = memst.dwTotalPhys / 1024.0;
6942 if (h_proc
6943 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6944 sizeof (mem_ex)))
6946 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6948 attrs = Fcons (Fcons (Qmajflt,
6949 make_fixnum_or_float (mem_ex.PageFaultCount)),
6950 attrs);
6951 attrs = Fcons (Fcons (Qvsize,
6952 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6953 attrs);
6954 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6955 if (totphys)
6956 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6958 else if (h_proc
6959 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6961 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6963 attrs = Fcons (Fcons (Qmajflt,
6964 make_fixnum_or_float (mem.PageFaultCount)),
6965 attrs);
6966 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6967 if (totphys)
6968 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6970 else if (h_proc
6971 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6973 DWORD rss = maxrss / 1024;
6975 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6976 if (totphys)
6977 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6980 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6982 attrs = Fcons (Fcons (Qutime, utime), attrs);
6983 attrs = Fcons (Fcons (Qstime, stime), attrs);
6984 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6985 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6986 attrs = Fcons (Fcons (Qetime, etime), attrs);
6987 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6990 /* FIXME: Retrieve command line by walking the PEB of the process. */
6992 if (h_proc)
6993 CloseHandle (h_proc);
6994 UNGCPRO;
6995 return attrs;
6999 /* Wrappers for winsock functions to map between our file descriptors
7000 and winsock's handles; also set h_errno for convenience.
7002 To allow Emacs to run on systems which don't have winsock support
7003 installed, we dynamically link to winsock on startup if present, and
7004 otherwise provide the minimum necessary functionality
7005 (eg. gethostname). */
7007 /* function pointers for relevant socket functions */
7008 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7009 void (PASCAL *pfn_WSASetLastError) (int iError);
7010 int (PASCAL *pfn_WSAGetLastError) (void);
7011 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7012 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7013 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7014 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7015 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7016 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7017 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7018 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7019 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7020 int (PASCAL *pfn_closesocket) (SOCKET s);
7021 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7022 int (PASCAL *pfn_WSACleanup) (void);
7024 u_short (PASCAL *pfn_htons) (u_short hostshort);
7025 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7026 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7027 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7028 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7029 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7030 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7031 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7032 const char * optval, int optlen);
7033 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7034 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7035 int * namelen);
7036 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7037 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7038 struct sockaddr * from, int * fromlen);
7039 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7040 const struct sockaddr * to, int tolen);
7042 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7043 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7044 #ifndef HANDLE_FLAG_INHERIT
7045 #define HANDLE_FLAG_INHERIT 1
7046 #endif
7048 HANDLE winsock_lib;
7049 static int winsock_inuse;
7051 BOOL
7052 term_winsock (void)
7054 if (winsock_lib != NULL && winsock_inuse == 0)
7056 release_listen_threads ();
7057 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7058 after WSAStartup returns successfully, but it seems reasonable
7059 to allow unloading winsock anyway in that case. */
7060 if (pfn_WSACleanup () == 0 ||
7061 pfn_WSAGetLastError () == WSAENETDOWN)
7063 if (FreeLibrary (winsock_lib))
7064 winsock_lib = NULL;
7065 return TRUE;
7068 return FALSE;
7071 BOOL
7072 init_winsock (int load_now)
7074 WSADATA winsockData;
7076 if (winsock_lib != NULL)
7077 return TRUE;
7079 pfn_SetHandleInformation
7080 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7081 "SetHandleInformation");
7083 winsock_lib = LoadLibrary ("Ws2_32.dll");
7085 if (winsock_lib != NULL)
7087 /* dynamically link to socket functions */
7089 #define LOAD_PROC(fn) \
7090 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7091 goto fail;
7093 LOAD_PROC (WSAStartup);
7094 LOAD_PROC (WSASetLastError);
7095 LOAD_PROC (WSAGetLastError);
7096 LOAD_PROC (WSAEventSelect);
7097 LOAD_PROC (WSACreateEvent);
7098 LOAD_PROC (WSACloseEvent);
7099 LOAD_PROC (socket);
7100 LOAD_PROC (bind);
7101 LOAD_PROC (connect);
7102 LOAD_PROC (ioctlsocket);
7103 LOAD_PROC (recv);
7104 LOAD_PROC (send);
7105 LOAD_PROC (closesocket);
7106 LOAD_PROC (shutdown);
7107 LOAD_PROC (htons);
7108 LOAD_PROC (ntohs);
7109 LOAD_PROC (inet_addr);
7110 LOAD_PROC (gethostname);
7111 LOAD_PROC (gethostbyname);
7112 LOAD_PROC (getservbyname);
7113 LOAD_PROC (getpeername);
7114 LOAD_PROC (WSACleanup);
7115 LOAD_PROC (setsockopt);
7116 LOAD_PROC (listen);
7117 LOAD_PROC (getsockname);
7118 LOAD_PROC (accept);
7119 LOAD_PROC (recvfrom);
7120 LOAD_PROC (sendto);
7121 #undef LOAD_PROC
7123 /* specify version 1.1 of winsock */
7124 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7126 if (winsockData.wVersion != 0x101)
7127 goto fail;
7129 if (!load_now)
7131 /* Report that winsock exists and is usable, but leave
7132 socket functions disabled. I am assuming that calling
7133 WSAStartup does not require any network interaction,
7134 and in particular does not cause or require a dial-up
7135 connection to be established. */
7137 pfn_WSACleanup ();
7138 FreeLibrary (winsock_lib);
7139 winsock_lib = NULL;
7141 winsock_inuse = 0;
7142 return TRUE;
7145 fail:
7146 FreeLibrary (winsock_lib);
7147 winsock_lib = NULL;
7150 return FALSE;
7154 int h_errno = 0;
7156 /* Function to map winsock error codes to errno codes for those errno
7157 code defined in errno.h (errno values not defined by errno.h are
7158 already in nt/inc/sys/socket.h). */
7159 static void
7160 set_errno (void)
7162 int wsa_err;
7164 h_errno = 0;
7165 if (winsock_lib == NULL)
7166 wsa_err = EINVAL;
7167 else
7168 wsa_err = pfn_WSAGetLastError ();
7170 switch (wsa_err)
7172 case WSAEACCES: errno = EACCES; break;
7173 case WSAEBADF: errno = EBADF; break;
7174 case WSAEFAULT: errno = EFAULT; break;
7175 case WSAEINTR: errno = EINTR; break;
7176 case WSAEINVAL: errno = EINVAL; break;
7177 case WSAEMFILE: errno = EMFILE; break;
7178 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7179 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7180 default: errno = wsa_err; break;
7184 static void
7185 check_errno (void)
7187 h_errno = 0;
7188 if (winsock_lib != NULL)
7189 pfn_WSASetLastError (0);
7192 /* Extend strerror to handle the winsock-specific error codes. */
7193 struct {
7194 int errnum;
7195 char * msg;
7196 } _wsa_errlist[] = {
7197 {WSAEINTR , "Interrupted function call"},
7198 {WSAEBADF , "Bad file descriptor"},
7199 {WSAEACCES , "Permission denied"},
7200 {WSAEFAULT , "Bad address"},
7201 {WSAEINVAL , "Invalid argument"},
7202 {WSAEMFILE , "Too many open files"},
7204 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7205 {WSAEINPROGRESS , "Operation now in progress"},
7206 {WSAEALREADY , "Operation already in progress"},
7207 {WSAENOTSOCK , "Socket operation on non-socket"},
7208 {WSAEDESTADDRREQ , "Destination address required"},
7209 {WSAEMSGSIZE , "Message too long"},
7210 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7211 {WSAENOPROTOOPT , "Bad protocol option"},
7212 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7213 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7214 {WSAEOPNOTSUPP , "Operation not supported"},
7215 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7216 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7217 {WSAEADDRINUSE , "Address already in use"},
7218 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7219 {WSAENETDOWN , "Network is down"},
7220 {WSAENETUNREACH , "Network is unreachable"},
7221 {WSAENETRESET , "Network dropped connection on reset"},
7222 {WSAECONNABORTED , "Software caused connection abort"},
7223 {WSAECONNRESET , "Connection reset by peer"},
7224 {WSAENOBUFS , "No buffer space available"},
7225 {WSAEISCONN , "Socket is already connected"},
7226 {WSAENOTCONN , "Socket is not connected"},
7227 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7228 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7229 {WSAETIMEDOUT , "Connection timed out"},
7230 {WSAECONNREFUSED , "Connection refused"},
7231 {WSAELOOP , "Network loop"}, /* not sure */
7232 {WSAENAMETOOLONG , "Name is too long"},
7233 {WSAEHOSTDOWN , "Host is down"},
7234 {WSAEHOSTUNREACH , "No route to host"},
7235 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7236 {WSAEPROCLIM , "Too many processes"},
7237 {WSAEUSERS , "Too many users"}, /* not sure */
7238 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7239 {WSAESTALE , "Data is stale"}, /* not sure */
7240 {WSAEREMOTE , "Remote error"}, /* not sure */
7242 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7243 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7244 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7245 {WSAEDISCON , "Graceful shutdown in progress"},
7246 #ifdef WSAENOMORE
7247 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7248 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7249 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7250 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7251 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7252 {WSASYSCALLFAILURE , "System call failure"},
7253 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7254 {WSATYPE_NOT_FOUND , "Class type not found"},
7255 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7256 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7257 {WSAEREFUSED , "Operation refused"}, /* not sure */
7258 #endif
7260 {WSAHOST_NOT_FOUND , "Host not found"},
7261 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7262 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7263 {WSANO_DATA , "Valid name, no data record of requested type"},
7265 {-1, NULL}
7268 char *
7269 sys_strerror (int error_no)
7271 int i;
7272 static char unknown_msg[40];
7274 if (error_no >= 0 && error_no < sys_nerr)
7275 return sys_errlist[error_no];
7277 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7278 if (_wsa_errlist[i].errnum == error_no)
7279 return _wsa_errlist[i].msg;
7281 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7282 return unknown_msg;
7285 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7286 but I believe the method of keeping the socket handle separate (and
7287 insuring it is not inheritable) is the correct one. */
7289 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7291 static int socket_to_fd (SOCKET s);
7294 sys_socket (int af, int type, int protocol)
7296 SOCKET s;
7298 if (winsock_lib == NULL)
7300 errno = ENETDOWN;
7301 return INVALID_SOCKET;
7304 check_errno ();
7306 /* call the real socket function */
7307 s = pfn_socket (af, type, protocol);
7309 if (s != INVALID_SOCKET)
7310 return socket_to_fd (s);
7312 set_errno ();
7313 return -1;
7316 /* Convert a SOCKET to a file descriptor. */
7317 static int
7318 socket_to_fd (SOCKET s)
7320 int fd;
7321 child_process * cp;
7323 /* Although under NT 3.5 _open_osfhandle will accept a socket
7324 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7325 that does not work under NT 3.1. However, we can get the same
7326 effect by using a backdoor function to replace an existing
7327 descriptor handle with the one we want. */
7329 /* allocate a file descriptor (with appropriate flags) */
7330 fd = _open ("NUL:", _O_RDWR);
7331 if (fd >= 0)
7333 /* Make a non-inheritable copy of the socket handle. Note
7334 that it is possible that sockets aren't actually kernel
7335 handles, which appears to be the case on Windows 9x when
7336 the MS Proxy winsock client is installed. */
7338 /* Apparently there is a bug in NT 3.51 with some service
7339 packs, which prevents using DuplicateHandle to make a
7340 socket handle non-inheritable (causes WSACleanup to
7341 hang). The work-around is to use SetHandleInformation
7342 instead if it is available and implemented. */
7343 if (pfn_SetHandleInformation)
7345 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7347 else
7349 HANDLE parent = GetCurrentProcess ();
7350 HANDLE new_s = INVALID_HANDLE_VALUE;
7352 if (DuplicateHandle (parent,
7353 (HANDLE) s,
7354 parent,
7355 &new_s,
7357 FALSE,
7358 DUPLICATE_SAME_ACCESS))
7360 /* It is possible that DuplicateHandle succeeds even
7361 though the socket wasn't really a kernel handle,
7362 because a real handle has the same value. So
7363 test whether the new handle really is a socket. */
7364 long nonblocking = 0;
7365 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7367 pfn_closesocket (s);
7368 s = (SOCKET) new_s;
7370 else
7372 CloseHandle (new_s);
7377 eassert (fd < MAXDESC);
7378 fd_info[fd].hnd = (HANDLE) s;
7380 /* set our own internal flags */
7381 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7383 cp = new_child ();
7384 if (cp)
7386 cp->fd = fd;
7387 cp->status = STATUS_READ_ACKNOWLEDGED;
7389 /* attach child_process to fd_info */
7390 if (fd_info[ fd ].cp != NULL)
7392 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7393 emacs_abort ();
7396 fd_info[ fd ].cp = cp;
7398 /* success! */
7399 winsock_inuse++; /* count open sockets */
7400 return fd;
7403 /* clean up */
7404 _close (fd);
7406 else
7407 pfn_closesocket (s);
7408 errno = EMFILE;
7409 return -1;
7413 sys_bind (int s, const struct sockaddr * addr, int namelen)
7415 if (winsock_lib == NULL)
7417 errno = ENOTSOCK;
7418 return SOCKET_ERROR;
7421 check_errno ();
7422 if (fd_info[s].flags & FILE_SOCKET)
7424 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7425 if (rc == SOCKET_ERROR)
7426 set_errno ();
7427 return rc;
7429 errno = ENOTSOCK;
7430 return SOCKET_ERROR;
7434 sys_connect (int s, const struct sockaddr * name, int namelen)
7436 if (winsock_lib == NULL)
7438 errno = ENOTSOCK;
7439 return SOCKET_ERROR;
7442 check_errno ();
7443 if (fd_info[s].flags & FILE_SOCKET)
7445 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7446 if (rc == SOCKET_ERROR)
7447 set_errno ();
7448 return rc;
7450 errno = ENOTSOCK;
7451 return SOCKET_ERROR;
7454 u_short
7455 sys_htons (u_short hostshort)
7457 return (winsock_lib != NULL) ?
7458 pfn_htons (hostshort) : hostshort;
7461 u_short
7462 sys_ntohs (u_short netshort)
7464 return (winsock_lib != NULL) ?
7465 pfn_ntohs (netshort) : netshort;
7468 unsigned long
7469 sys_inet_addr (const char * cp)
7471 return (winsock_lib != NULL) ?
7472 pfn_inet_addr (cp) : INADDR_NONE;
7476 sys_gethostname (char * name, int namelen)
7478 if (winsock_lib != NULL)
7480 int retval;
7482 check_errno ();
7483 retval = pfn_gethostname (name, namelen);
7484 if (retval == SOCKET_ERROR)
7485 set_errno ();
7486 return retval;
7489 if (namelen > MAX_COMPUTERNAME_LENGTH)
7490 return !GetComputerName (name, (DWORD *)&namelen);
7492 errno = EFAULT;
7493 return SOCKET_ERROR;
7496 struct hostent *
7497 sys_gethostbyname (const char * name)
7499 struct hostent * host;
7500 int h_err = h_errno;
7502 if (winsock_lib == NULL)
7504 h_errno = NO_RECOVERY;
7505 errno = ENETDOWN;
7506 return NULL;
7509 check_errno ();
7510 host = pfn_gethostbyname (name);
7511 if (!host)
7513 set_errno ();
7514 h_errno = errno;
7516 else
7517 h_errno = h_err;
7518 return host;
7521 struct servent *
7522 sys_getservbyname (const char * name, const char * proto)
7524 struct servent * serv;
7526 if (winsock_lib == NULL)
7528 errno = ENETDOWN;
7529 return NULL;
7532 check_errno ();
7533 serv = pfn_getservbyname (name, proto);
7534 if (!serv)
7535 set_errno ();
7536 return serv;
7540 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7542 if (winsock_lib == NULL)
7544 errno = ENETDOWN;
7545 return SOCKET_ERROR;
7548 check_errno ();
7549 if (fd_info[s].flags & FILE_SOCKET)
7551 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7552 if (rc == SOCKET_ERROR)
7553 set_errno ();
7554 return rc;
7556 errno = ENOTSOCK;
7557 return SOCKET_ERROR;
7561 sys_shutdown (int s, int how)
7563 if (winsock_lib == NULL)
7565 errno = ENETDOWN;
7566 return SOCKET_ERROR;
7569 check_errno ();
7570 if (fd_info[s].flags & FILE_SOCKET)
7572 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7573 if (rc == SOCKET_ERROR)
7574 set_errno ();
7575 return rc;
7577 errno = ENOTSOCK;
7578 return SOCKET_ERROR;
7582 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7584 if (winsock_lib == NULL)
7586 errno = ENETDOWN;
7587 return SOCKET_ERROR;
7590 check_errno ();
7591 if (fd_info[s].flags & FILE_SOCKET)
7593 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7594 (const char *)optval, optlen);
7595 if (rc == SOCKET_ERROR)
7596 set_errno ();
7597 return rc;
7599 errno = ENOTSOCK;
7600 return SOCKET_ERROR;
7604 sys_listen (int s, int backlog)
7606 if (winsock_lib == NULL)
7608 errno = ENETDOWN;
7609 return SOCKET_ERROR;
7612 check_errno ();
7613 if (fd_info[s].flags & FILE_SOCKET)
7615 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7616 if (rc == SOCKET_ERROR)
7617 set_errno ();
7618 else
7619 fd_info[s].flags |= FILE_LISTEN;
7620 return rc;
7622 errno = ENOTSOCK;
7623 return SOCKET_ERROR;
7627 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7629 if (winsock_lib == NULL)
7631 errno = ENETDOWN;
7632 return SOCKET_ERROR;
7635 check_errno ();
7636 if (fd_info[s].flags & FILE_SOCKET)
7638 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7639 if (rc == SOCKET_ERROR)
7640 set_errno ();
7641 return rc;
7643 errno = ENOTSOCK;
7644 return SOCKET_ERROR;
7648 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7650 if (winsock_lib == NULL)
7652 errno = ENETDOWN;
7653 return -1;
7656 check_errno ();
7657 if (fd_info[s].flags & FILE_LISTEN)
7659 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7660 int fd = -1;
7661 if (t == INVALID_SOCKET)
7662 set_errno ();
7663 else
7664 fd = socket_to_fd (t);
7666 if (fd >= 0)
7668 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7669 ResetEvent (fd_info[s].cp->char_avail);
7671 return fd;
7673 errno = ENOTSOCK;
7674 return -1;
7678 sys_recvfrom (int s, char * buf, int len, int flags,
7679 struct sockaddr * from, int * fromlen)
7681 if (winsock_lib == NULL)
7683 errno = ENETDOWN;
7684 return SOCKET_ERROR;
7687 check_errno ();
7688 if (fd_info[s].flags & FILE_SOCKET)
7690 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7691 if (rc == SOCKET_ERROR)
7692 set_errno ();
7693 return rc;
7695 errno = ENOTSOCK;
7696 return SOCKET_ERROR;
7700 sys_sendto (int s, const char * buf, int len, int flags,
7701 const struct sockaddr * to, int tolen)
7703 if (winsock_lib == NULL)
7705 errno = ENETDOWN;
7706 return SOCKET_ERROR;
7709 check_errno ();
7710 if (fd_info[s].flags & FILE_SOCKET)
7712 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7713 if (rc == SOCKET_ERROR)
7714 set_errno ();
7715 return rc;
7717 errno = ENOTSOCK;
7718 return SOCKET_ERROR;
7721 /* Windows does not have an fcntl function. Provide an implementation
7722 good enough for Emacs. */
7724 fcntl (int s, int cmd, int options)
7726 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7727 invoked in a context where fd1 is closed and all descriptors less
7728 than fd1 are open, so sys_dup is an adequate implementation. */
7729 if (cmd == F_DUPFD_CLOEXEC)
7730 return sys_dup (s);
7732 check_errno ();
7733 if (fd_info[s].flags & FILE_SOCKET)
7735 if (winsock_lib == NULL)
7737 errno = ENETDOWN;
7738 return -1;
7741 if (cmd == F_SETFL && options == O_NONBLOCK)
7743 unsigned long nblock = 1;
7744 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7745 if (rc == SOCKET_ERROR)
7746 set_errno ();
7747 /* Keep track of the fact that we set this to non-blocking. */
7748 fd_info[s].flags |= FILE_NDELAY;
7749 return rc;
7751 else
7753 errno = EINVAL;
7754 return SOCKET_ERROR;
7757 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7758 == (FILE_PIPE | FILE_WRITE))
7760 /* Force our writes to pipes be non-blocking. */
7761 if (cmd == F_SETFL && options == O_NONBLOCK)
7763 HANDLE h = (HANDLE)_get_osfhandle (s);
7764 DWORD pipe_mode = PIPE_NOWAIT;
7766 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7768 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7769 return SOCKET_ERROR;
7771 fd_info[s].flags |= FILE_NDELAY;
7772 return 0;
7774 else
7776 errno = EINVAL;
7777 return SOCKET_ERROR;
7780 errno = ENOTSOCK;
7781 return SOCKET_ERROR;
7785 /* Shadow main io functions: we need to handle pipes and sockets more
7786 intelligently. */
7789 sys_close (int fd)
7791 int rc;
7793 if (fd < 0)
7795 errno = EBADF;
7796 return -1;
7799 if (fd < MAXDESC && fd_info[fd].cp)
7801 child_process * cp = fd_info[fd].cp;
7803 fd_info[fd].cp = NULL;
7805 if (CHILD_ACTIVE (cp))
7807 /* if last descriptor to active child_process then cleanup */
7808 int i;
7809 for (i = 0; i < MAXDESC; i++)
7811 if (i == fd)
7812 continue;
7813 if (fd_info[i].cp == cp)
7814 break;
7816 if (i == MAXDESC)
7818 if (fd_info[fd].flags & FILE_SOCKET)
7820 if (winsock_lib == NULL) emacs_abort ();
7822 pfn_shutdown (SOCK_HANDLE (fd), 2);
7823 rc = pfn_closesocket (SOCK_HANDLE (fd));
7825 winsock_inuse--; /* count open sockets */
7827 /* If the process handle is NULL, it's either a socket
7828 or serial connection, or a subprocess that was
7829 already reaped by reap_subprocess, but whose
7830 resources were not yet freed, because its output was
7831 not fully read yet by the time it was reaped. (This
7832 usually happens with async subprocesses whose output
7833 is being read by Emacs.) Otherwise, this process was
7834 not reaped yet, so we set its FD to a negative value
7835 to make sure sys_select will eventually get to
7836 calling the SIGCHLD handler for it, which will then
7837 invoke waitpid and reap_subprocess. */
7838 if (cp->procinfo.hProcess == NULL)
7839 delete_child (cp);
7840 else
7841 cp->fd = -1;
7846 if (fd >= 0 && fd < MAXDESC)
7847 fd_info[fd].flags = 0;
7849 /* Note that sockets do not need special treatment here (at least on
7850 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7851 closesocket is equivalent to CloseHandle, which is to be expected
7852 because socket handles are fully fledged kernel handles. */
7853 rc = _close (fd);
7855 return rc;
7859 sys_dup (int fd)
7861 int new_fd;
7863 new_fd = _dup (fd);
7864 if (new_fd >= 0 && new_fd < MAXDESC)
7866 /* duplicate our internal info as well */
7867 fd_info[new_fd] = fd_info[fd];
7869 return new_fd;
7873 sys_dup2 (int src, int dst)
7875 int rc;
7877 if (dst < 0 || dst >= MAXDESC)
7879 errno = EBADF;
7880 return -1;
7883 /* make sure we close the destination first if it's a pipe or socket */
7884 if (src != dst && fd_info[dst].flags != 0)
7885 sys_close (dst);
7887 rc = _dup2 (src, dst);
7888 if (rc == 0)
7890 /* duplicate our internal info as well */
7891 fd_info[dst] = fd_info[src];
7893 return rc;
7897 pipe2 (int * phandles, int pipe2_flags)
7899 int rc;
7900 unsigned flags;
7902 eassert (pipe2_flags == O_CLOEXEC);
7904 /* make pipe handles non-inheritable; when we spawn a child, we
7905 replace the relevant handle with an inheritable one. Also put
7906 pipes into binary mode; we will do text mode translation ourselves
7907 if required. */
7908 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
7910 if (rc == 0)
7912 /* Protect against overflow, since Windows can open more handles than
7913 our fd_info array has room for. */
7914 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
7916 _close (phandles[0]);
7917 _close (phandles[1]);
7918 errno = EMFILE;
7919 rc = -1;
7921 else
7923 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
7924 fd_info[phandles[0]].flags = flags;
7926 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
7927 fd_info[phandles[1]].flags = flags;
7931 return rc;
7934 /* Function to do blocking read of one byte, needed to implement
7935 select. It is only allowed on communication ports, sockets, or
7936 pipes. */
7938 _sys_read_ahead (int fd)
7940 child_process * cp;
7941 int rc;
7943 if (fd < 0 || fd >= MAXDESC)
7944 return STATUS_READ_ERROR;
7946 cp = fd_info[fd].cp;
7948 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7949 return STATUS_READ_ERROR;
7951 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
7952 || (fd_info[fd].flags & FILE_READ) == 0)
7954 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
7955 emacs_abort ();
7958 cp->status = STATUS_READ_IN_PROGRESS;
7960 if (fd_info[fd].flags & FILE_PIPE)
7962 rc = _read (fd, &cp->chr, sizeof (char));
7964 /* Give subprocess time to buffer some more output for us before
7965 reporting that input is available; we need this because Windows 95
7966 connects DOS programs to pipes by making the pipe appear to be
7967 the normal console stdout - as a result most DOS programs will
7968 write to stdout without buffering, ie. one character at a
7969 time. Even some W32 programs do this - "dir" in a command
7970 shell on NT is very slow if we don't do this. */
7971 if (rc > 0)
7973 int wait = w32_pipe_read_delay;
7975 if (wait > 0)
7976 Sleep (wait);
7977 else if (wait < 0)
7978 while (++wait <= 0)
7979 /* Yield remainder of our time slice, effectively giving a
7980 temporary priority boost to the child process. */
7981 Sleep (0);
7984 else if (fd_info[fd].flags & FILE_SERIAL)
7986 HANDLE hnd = fd_info[fd].hnd;
7987 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7988 COMMTIMEOUTS ct;
7990 /* Configure timeouts for blocking read. */
7991 if (!GetCommTimeouts (hnd, &ct))
7993 cp->status = STATUS_READ_ERROR;
7994 return STATUS_READ_ERROR;
7996 ct.ReadIntervalTimeout = 0;
7997 ct.ReadTotalTimeoutMultiplier = 0;
7998 ct.ReadTotalTimeoutConstant = 0;
7999 if (!SetCommTimeouts (hnd, &ct))
8001 cp->status = STATUS_READ_ERROR;
8002 return STATUS_READ_ERROR;
8005 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8007 if (GetLastError () != ERROR_IO_PENDING)
8009 cp->status = STATUS_READ_ERROR;
8010 return STATUS_READ_ERROR;
8012 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8014 cp->status = STATUS_READ_ERROR;
8015 return STATUS_READ_ERROR;
8019 else if (fd_info[fd].flags & FILE_SOCKET)
8021 unsigned long nblock = 0;
8022 /* We always want this to block, so temporarily disable NDELAY. */
8023 if (fd_info[fd].flags & FILE_NDELAY)
8024 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8026 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8028 if (fd_info[fd].flags & FILE_NDELAY)
8030 nblock = 1;
8031 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8035 if (rc == sizeof (char))
8036 cp->status = STATUS_READ_SUCCEEDED;
8037 else
8038 cp->status = STATUS_READ_FAILED;
8040 return cp->status;
8044 _sys_wait_accept (int fd)
8046 HANDLE hEv;
8047 child_process * cp;
8048 int rc;
8050 if (fd < 0 || fd >= MAXDESC)
8051 return STATUS_READ_ERROR;
8053 cp = fd_info[fd].cp;
8055 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8056 return STATUS_READ_ERROR;
8058 cp->status = STATUS_READ_FAILED;
8060 hEv = pfn_WSACreateEvent ();
8061 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8062 if (rc != SOCKET_ERROR)
8064 do {
8065 rc = WaitForSingleObject (hEv, 500);
8066 Sleep (5);
8067 } while (rc == WAIT_TIMEOUT
8068 && cp->status != STATUS_READ_ERROR
8069 && cp->char_avail);
8070 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8071 if (rc == WAIT_OBJECT_0)
8072 cp->status = STATUS_READ_SUCCEEDED;
8074 pfn_WSACloseEvent (hEv);
8076 return cp->status;
8080 sys_read (int fd, char * buffer, unsigned int count)
8082 int nchars;
8083 int to_read;
8084 DWORD waiting;
8085 char * orig_buffer = buffer;
8087 if (fd < 0)
8089 errno = EBADF;
8090 return -1;
8093 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8095 child_process *cp = fd_info[fd].cp;
8097 if ((fd_info[fd].flags & FILE_READ) == 0)
8099 errno = EBADF;
8100 return -1;
8103 nchars = 0;
8105 /* re-read CR carried over from last read */
8106 if (fd_info[fd].flags & FILE_LAST_CR)
8108 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8109 *buffer++ = 0x0d;
8110 count--;
8111 nchars++;
8112 fd_info[fd].flags &= ~FILE_LAST_CR;
8115 /* presence of a child_process structure means we are operating in
8116 non-blocking mode - otherwise we just call _read directly.
8117 Note that the child_process structure might be missing because
8118 reap_subprocess has been called; in this case the pipe is
8119 already broken, so calling _read on it is okay. */
8120 if (cp)
8122 int current_status = cp->status;
8124 switch (current_status)
8126 case STATUS_READ_FAILED:
8127 case STATUS_READ_ERROR:
8128 /* report normal EOF if nothing in buffer */
8129 if (nchars <= 0)
8130 fd_info[fd].flags |= FILE_AT_EOF;
8131 return nchars;
8133 case STATUS_READ_READY:
8134 case STATUS_READ_IN_PROGRESS:
8135 DebPrint (("sys_read called when read is in progress\n"));
8136 errno = EWOULDBLOCK;
8137 return -1;
8139 case STATUS_READ_SUCCEEDED:
8140 /* consume read-ahead char */
8141 *buffer++ = cp->chr;
8142 count--;
8143 nchars++;
8144 cp->status = STATUS_READ_ACKNOWLEDGED;
8145 ResetEvent (cp->char_avail);
8147 case STATUS_READ_ACKNOWLEDGED:
8148 break;
8150 default:
8151 DebPrint (("sys_read: bad status %d\n", current_status));
8152 errno = EBADF;
8153 return -1;
8156 if (fd_info[fd].flags & FILE_PIPE)
8158 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8159 to_read = min (waiting, (DWORD) count);
8161 if (to_read > 0)
8162 nchars += _read (fd, buffer, to_read);
8164 else if (fd_info[fd].flags & FILE_SERIAL)
8166 HANDLE hnd = fd_info[fd].hnd;
8167 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8168 int rc = 0;
8169 COMMTIMEOUTS ct;
8171 if (count > 0)
8173 /* Configure timeouts for non-blocking read. */
8174 if (!GetCommTimeouts (hnd, &ct))
8176 errno = EIO;
8177 return -1;
8179 ct.ReadIntervalTimeout = MAXDWORD;
8180 ct.ReadTotalTimeoutMultiplier = 0;
8181 ct.ReadTotalTimeoutConstant = 0;
8182 if (!SetCommTimeouts (hnd, &ct))
8184 errno = EIO;
8185 return -1;
8188 if (!ResetEvent (ovl->hEvent))
8190 errno = EIO;
8191 return -1;
8193 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8195 if (GetLastError () != ERROR_IO_PENDING)
8197 errno = EIO;
8198 return -1;
8200 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8202 errno = EIO;
8203 return -1;
8206 nchars += rc;
8209 else /* FILE_SOCKET */
8211 if (winsock_lib == NULL) emacs_abort ();
8213 /* do the equivalent of a non-blocking read */
8214 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8215 if (waiting == 0 && nchars == 0)
8217 errno = EWOULDBLOCK;
8218 return -1;
8221 if (waiting)
8223 /* always use binary mode for sockets */
8224 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8225 if (res == SOCKET_ERROR)
8227 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8228 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8229 set_errno ();
8230 return -1;
8232 nchars += res;
8236 else
8238 int nread = _read (fd, buffer, count);
8239 if (nread >= 0)
8240 nchars += nread;
8241 else if (nchars == 0)
8242 nchars = nread;
8245 if (nchars <= 0)
8246 fd_info[fd].flags |= FILE_AT_EOF;
8247 /* Perform text mode translation if required. */
8248 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8250 nchars = crlf_to_lf (nchars, orig_buffer);
8251 /* If buffer contains only CR, return that. To be absolutely
8252 sure we should attempt to read the next char, but in
8253 practice a CR to be followed by LF would not appear by
8254 itself in the buffer. */
8255 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8257 fd_info[fd].flags |= FILE_LAST_CR;
8258 nchars--;
8262 else
8263 nchars = _read (fd, buffer, count);
8265 return nchars;
8268 /* From w32xfns.c */
8269 extern HANDLE interrupt_handle;
8272 sys_write (int fd, const void * buffer, unsigned int count)
8274 int nchars;
8276 if (fd < 0)
8278 errno = EBADF;
8279 return -1;
8282 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8284 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8286 errno = EBADF;
8287 return -1;
8290 /* Perform text mode translation if required. */
8291 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8293 char * tmpbuf = alloca (count * 2);
8294 unsigned char * src = (void *)buffer;
8295 unsigned char * dst = tmpbuf;
8296 int nbytes = count;
8298 while (1)
8300 unsigned char *next;
8301 /* copy next line or remaining bytes */
8302 next = _memccpy (dst, src, '\n', nbytes);
8303 if (next)
8305 /* copied one line ending with '\n' */
8306 int copied = next - dst;
8307 nbytes -= copied;
8308 src += copied;
8309 /* insert '\r' before '\n' */
8310 next[-1] = '\r';
8311 next[0] = '\n';
8312 dst = next + 1;
8313 count++;
8315 else
8316 /* copied remaining partial line -> now finished */
8317 break;
8319 buffer = tmpbuf;
8323 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8325 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8326 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8327 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8328 DWORD active = 0;
8330 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8332 if (GetLastError () != ERROR_IO_PENDING)
8334 errno = EIO;
8335 return -1;
8337 if (detect_input_pending ())
8338 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
8339 QS_ALLINPUT);
8340 else
8341 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8342 if (active == WAIT_OBJECT_0)
8343 { /* User pressed C-g, cancel write, then leave. Don't bother
8344 cleaning up as we may only get stuck in buggy drivers. */
8345 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8346 CancelIo (hnd);
8347 errno = EIO;
8348 return -1;
8350 if (active == WAIT_OBJECT_0 + 1
8351 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8353 errno = EIO;
8354 return -1;
8358 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8360 unsigned long nblock = 0;
8361 if (winsock_lib == NULL) emacs_abort ();
8363 /* TODO: implement select() properly so non-blocking I/O works. */
8364 /* For now, make sure the write blocks. */
8365 if (fd_info[fd].flags & FILE_NDELAY)
8366 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8368 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8370 /* Set the socket back to non-blocking if it was before,
8371 for other operations that support it. */
8372 if (fd_info[fd].flags & FILE_NDELAY)
8374 nblock = 1;
8375 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8378 if (nchars == SOCKET_ERROR)
8380 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8381 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8382 set_errno ();
8385 else
8387 /* Some networked filesystems don't like too large writes, so
8388 break them into smaller chunks. See the Comments section of
8389 the MSDN documentation of WriteFile for details behind the
8390 choice of the value of CHUNK below. See also the thread
8391 http://thread.gmane.org/gmane.comp.version-control.git/145294
8392 in the git mailing list. */
8393 const unsigned char *p = buffer;
8394 const unsigned chunk = 30 * 1024 * 1024;
8396 nchars = 0;
8397 while (count > 0)
8399 unsigned this_chunk = count < chunk ? count : chunk;
8400 int n = _write (fd, p, this_chunk);
8402 nchars += n;
8403 if (n < 0)
8405 /* When there's no buffer space in a pipe that is in the
8406 non-blocking mode, _write returns ENOSPC. We return
8407 EAGAIN instead, which should trigger the logic in
8408 send_process that enters waiting loop and calls
8409 wait_reading_process_output to allow process input to
8410 be accepted during the wait. Those calls to
8411 wait_reading_process_output allow sys_select to
8412 notice when process input becomes available, thus
8413 avoiding deadlock whereby each side of the pipe is
8414 blocked on write, waiting for the other party to read
8415 its end of the pipe. */
8416 if (errno == ENOSPC
8417 && fd < MAXDESC
8418 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8419 == (FILE_PIPE | FILE_NDELAY)))
8420 errno = EAGAIN;
8421 nchars = n;
8422 break;
8424 else if (n < this_chunk)
8425 break;
8426 count -= n;
8427 p += n;
8431 return nchars;
8435 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8437 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8439 /* Return information about network interface IFNAME, or about all
8440 interfaces (if IFNAME is nil). */
8441 static Lisp_Object
8442 network_interface_get_info (Lisp_Object ifname)
8444 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8445 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8446 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8447 Lisp_Object res = Qnil;
8449 if (retval == ERROR_BUFFER_OVERFLOW)
8451 ainfo = xrealloc (ainfo, ainfo_len);
8452 retval = get_adapters_info (ainfo, &ainfo_len);
8455 if (retval == ERROR_SUCCESS)
8457 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8458 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8459 int if_num;
8460 struct sockaddr_in sa;
8462 /* For the below, we need some winsock functions, so make sure
8463 the winsock DLL is loaded. If we cannot successfully load
8464 it, they will have no use of the information we provide,
8465 anyway, so punt. */
8466 if (!winsock_lib && !init_winsock (1))
8467 goto done;
8469 for (adapter = ainfo; adapter; adapter = adapter->Next)
8471 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8472 u_long ip_addr;
8473 /* Present Unix-compatible interface names, instead of the
8474 Windows names, which are really GUIDs not readable by
8475 humans. */
8476 static const char *ifmt[] = {
8477 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8478 "lo", "ifx%d"
8480 enum {
8481 NONE = -1,
8482 ETHERNET = 0,
8483 TOKENRING = 1,
8484 FDDI = 2,
8485 PPP = 3,
8486 SLIP = 4,
8487 WLAN = 5,
8488 LOOPBACK = 6,
8489 OTHER_IF = 7
8490 } ifmt_idx;
8492 switch (adapter->Type)
8494 case MIB_IF_TYPE_ETHERNET:
8495 /* Windows before Vista reports wireless adapters as
8496 Ethernet. Work around by looking at the Description
8497 string. */
8498 if (strstr (adapter->Description, "Wireless "))
8500 ifmt_idx = WLAN;
8501 if_num = wlan_count++;
8503 else
8505 ifmt_idx = ETHERNET;
8506 if_num = eth_count++;
8508 break;
8509 case MIB_IF_TYPE_TOKENRING:
8510 ifmt_idx = TOKENRING;
8511 if_num = tr_count++;
8512 break;
8513 case MIB_IF_TYPE_FDDI:
8514 ifmt_idx = FDDI;
8515 if_num = fddi_count++;
8516 break;
8517 case MIB_IF_TYPE_PPP:
8518 ifmt_idx = PPP;
8519 if_num = ppp_count++;
8520 break;
8521 case MIB_IF_TYPE_SLIP:
8522 ifmt_idx = SLIP;
8523 if_num = sl_count++;
8524 break;
8525 case IF_TYPE_IEEE80211:
8526 ifmt_idx = WLAN;
8527 if_num = wlan_count++;
8528 break;
8529 case MIB_IF_TYPE_LOOPBACK:
8530 if (lo_count < 0)
8532 ifmt_idx = LOOPBACK;
8533 if_num = lo_count++;
8535 else
8536 ifmt_idx = NONE;
8537 break;
8538 default:
8539 ifmt_idx = OTHER_IF;
8540 if_num = ifx_count++;
8541 break;
8543 if (ifmt_idx == NONE)
8544 continue;
8545 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8547 sa.sin_family = AF_INET;
8548 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8549 if (ip_addr == INADDR_NONE)
8551 /* Bogus address, skip this interface. */
8552 continue;
8554 sa.sin_addr.s_addr = ip_addr;
8555 sa.sin_port = 0;
8556 if (NILP (ifname))
8557 res = Fcons (Fcons (build_string (namebuf),
8558 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8559 sizeof (struct sockaddr))),
8560 res);
8561 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8563 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8564 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8565 Lisp_Object flags = Qnil;
8566 int n;
8567 u_long net_mask;
8569 /* Flags. We guess most of them by type, since the
8570 Windows flags are different and hard to get by. */
8571 flags = Fcons (intern ("up"), flags);
8572 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8574 flags = Fcons (intern ("broadcast"), flags);
8575 flags = Fcons (intern ("multicast"), flags);
8577 flags = Fcons (intern ("running"), flags);
8578 if (ifmt_idx == PPP)
8580 flags = Fcons (intern ("pointopoint"), flags);
8581 flags = Fcons (intern ("noarp"), flags);
8583 if (adapter->HaveWins)
8584 flags = Fcons (intern ("WINS"), flags);
8585 if (adapter->DhcpEnabled)
8586 flags = Fcons (intern ("dynamic"), flags);
8588 res = Fcons (flags, res);
8590 /* Hardware address and its family. */
8591 for (n = 0; n < adapter->AddressLength; n++)
8592 p->contents[n] = make_number ((int) adapter->Address[n]);
8593 /* Windows does not support AF_LINK or AF_PACKET family
8594 of addresses. Use an arbitrary family number that is
8595 identical to what GNU/Linux returns. */
8596 res = Fcons (Fcons (make_number (1), hwaddr), res);
8598 /* Network mask. */
8599 sa.sin_family = AF_INET;
8600 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8601 if (net_mask != INADDR_NONE)
8603 sa.sin_addr.s_addr = net_mask;
8604 sa.sin_port = 0;
8605 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8606 sizeof (struct sockaddr)),
8607 res);
8609 else
8610 res = Fcons (Qnil, res);
8612 sa.sin_family = AF_INET;
8613 if (ip_addr != INADDR_NONE)
8615 /* Broadcast address is only reported by
8616 GetAdaptersAddresses, which is of limited
8617 availability. Generate it on our own. */
8618 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8620 sa.sin_addr.s_addr = bcast_addr;
8621 sa.sin_port = 0;
8622 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8623 sizeof (struct sockaddr)),
8624 res);
8626 /* IP address. */
8627 sa.sin_addr.s_addr = ip_addr;
8628 sa.sin_port = 0;
8629 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8630 sizeof (struct sockaddr)),
8631 res);
8633 else
8634 res = Fcons (Qnil, Fcons (Qnil, res));
8637 /* GetAdaptersInfo is documented to not report loopback
8638 interfaces, so we generate one out of thin air. */
8639 if (!lo_count)
8641 sa.sin_family = AF_INET;
8642 sa.sin_port = 0;
8643 if (NILP (ifname))
8645 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8646 res = Fcons (Fcons (build_string ("lo"),
8647 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8648 sizeof (struct sockaddr))),
8649 res);
8651 else if (strcmp (SSDATA (ifname), "lo") == 0)
8653 res = Fcons (Fcons (intern ("running"),
8654 Fcons (intern ("loopback"),
8655 Fcons (intern ("up"), Qnil))), Qnil);
8656 /* 772 is what 3 different GNU/Linux systems report for
8657 the loopback interface. */
8658 res = Fcons (Fcons (make_number (772),
8659 Fmake_vector (make_number (6),
8660 make_number (0))),
8661 res);
8662 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8663 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8664 sizeof (struct sockaddr)),
8665 res);
8666 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8667 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8668 sizeof (struct sockaddr)),
8669 res);
8670 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8671 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8672 sizeof (struct sockaddr)),
8673 res);
8679 done:
8680 xfree (ainfo);
8681 return res;
8684 Lisp_Object
8685 network_interface_list (void)
8687 return network_interface_get_info (Qnil);
8690 Lisp_Object
8691 network_interface_info (Lisp_Object ifname)
8693 CHECK_STRING (ifname);
8694 return network_interface_get_info (ifname);
8698 /* The Windows CRT functions are "optimized for speed", so they don't
8699 check for timezone and DST changes if they were last called less
8700 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8701 all Emacs features that repeatedly call time functions (e.g.,
8702 display-time) are in real danger of missing timezone and DST
8703 changes. Calling tzset before each localtime call fixes that. */
8704 struct tm *
8705 sys_localtime (const time_t *t)
8707 tzset ();
8708 return localtime (t);
8713 /* Try loading LIBRARY_ID from the file(s) specified in
8714 Vdynamic_library_alist. If the library is loaded successfully,
8715 return the handle of the DLL, and record the filename in the
8716 property :loaded-from of LIBRARY_ID. If the library could not be
8717 found, or when it was already loaded (because the handle is not
8718 recorded anywhere, and so is lost after use), return NULL.
8720 We could also save the handle in :loaded-from, but currently
8721 there's no use case for it. */
8722 HMODULE
8723 w32_delayed_load (Lisp_Object library_id)
8725 HMODULE dll_handle = NULL;
8727 CHECK_SYMBOL (library_id);
8729 if (CONSP (Vdynamic_library_alist)
8730 && NILP (Fassq (library_id, Vlibrary_cache)))
8732 Lisp_Object found = Qnil;
8733 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
8735 if (CONSP (dlls))
8736 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
8738 Lisp_Object dll = XCAR (dlls);
8739 char name[MAX_UTF8_PATH];
8740 DWORD res = -1;
8742 CHECK_STRING (dll);
8743 dll = ENCODE_FILE (dll);
8744 if (w32_unicode_filenames)
8746 wchar_t name_w[MAX_PATH];
8748 filename_to_utf16 (SSDATA (dll), name_w);
8749 dll_handle = LoadLibraryW (name_w);
8750 if (dll_handle)
8752 res = GetModuleFileNameW (dll_handle, name_w,
8753 sizeof (name_w));
8754 if (res > 0)
8755 filename_from_utf16 (name_w, name);
8758 else
8760 char name_a[MAX_PATH];
8762 filename_to_ansi (SSDATA (dll), name_a);
8763 dll_handle = LoadLibraryA (name_a);
8764 if (dll_handle)
8766 res = GetModuleFileNameA (dll_handle, name_a,
8767 sizeof (name_a));
8768 if (res > 0)
8769 filename_from_ansi (name_a, name);
8772 if (dll_handle)
8774 ptrdiff_t len = strlen (name);
8775 found = Fcons (dll,
8776 (res > 0)
8777 /* Possibly truncated */
8778 ? make_specified_string (name, -1, len, 1)
8779 : Qnil);
8780 break;
8784 Fput (library_id, QCloaded_from, found);
8787 return dll_handle;
8791 void
8792 check_windows_init_file (void)
8794 /* A common indication that Emacs is not installed properly is when
8795 it cannot find the Windows installation file. If this file does
8796 not exist in the expected place, tell the user. */
8798 if (!noninteractive && !inhibit_window_system
8799 /* Vload_path is not yet initialized when we are loading
8800 loadup.el. */
8801 && NILP (Vpurify_flag))
8803 Lisp_Object init_file;
8804 int fd;
8806 /* Implementation note: this function runs early during Emacs
8807 startup, before startup.el is run. So Vload_path is still in
8808 its initial unibyte form, but it holds UTF-8 encoded file
8809 names, since init_callproc was already called. So we do not
8810 need to ENCODE_FILE here, but we do need to convert the file
8811 names from UTF-8 to ANSI. */
8812 init_file = build_string ("term/w32-win");
8813 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
8814 if (fd < 0)
8816 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
8817 char *init_file_name = SDATA (init_file);
8818 char *load_path = SDATA (load_path_print);
8819 char *buffer = alloca (1024
8820 + strlen (init_file_name)
8821 + strlen (load_path));
8822 char *msg = buffer;
8823 int needed;
8825 sprintf (buffer,
8826 "The Emacs Windows initialization file \"%s.el\" "
8827 "could not be found in your Emacs installation. "
8828 "Emacs checked the following directories for this file:\n"
8829 "\n%s\n\n"
8830 "When Emacs cannot find this file, it usually means that it "
8831 "was not installed properly, or its distribution file was "
8832 "not unpacked properly.\nSee the README.W32 file in the "
8833 "top-level Emacs directory for more information.",
8834 init_file_name, load_path);
8835 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer,
8836 -1, NULL, 0);
8837 if (needed > 0)
8839 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
8841 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer, -1,
8842 msg_w, needed);
8843 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
8844 NULL, 0, NULL, NULL);
8845 if (needed > 0)
8847 char *msg_a = alloca (needed + 1);
8849 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
8850 NULL, NULL);
8851 msg = msg_a;
8854 MessageBox (NULL,
8855 msg,
8856 "Emacs Abort Dialog",
8857 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
8858 /* Use the low-level system abort. */
8859 abort ();
8861 else
8863 _close (fd);
8868 void
8869 term_ntproc (int ignored)
8871 (void)ignored;
8873 term_timers ();
8875 /* shutdown the socket interface if necessary */
8876 term_winsock ();
8878 term_w32select ();
8881 void
8882 init_ntproc (int dumping)
8884 sigset_t initial_mask = 0;
8886 /* Initialize the socket interface now if available and requested by
8887 the user by defining PRELOAD_WINSOCK; otherwise loading will be
8888 delayed until open-network-stream is called (w32-has-winsock can
8889 also be used to dynamically load or reload winsock).
8891 Conveniently, init_environment is called before us, so
8892 PRELOAD_WINSOCK can be set in the registry. */
8894 /* Always initialize this correctly. */
8895 winsock_lib = NULL;
8897 if (getenv ("PRELOAD_WINSOCK") != NULL)
8898 init_winsock (TRUE);
8900 /* Initial preparation for subprocess support: replace our standard
8901 handles with non-inheritable versions. */
8903 HANDLE parent;
8904 HANDLE stdin_save = INVALID_HANDLE_VALUE;
8905 HANDLE stdout_save = INVALID_HANDLE_VALUE;
8906 HANDLE stderr_save = INVALID_HANDLE_VALUE;
8908 parent = GetCurrentProcess ();
8910 /* ignore errors when duplicating and closing; typically the
8911 handles will be invalid when running as a gui program. */
8912 DuplicateHandle (parent,
8913 GetStdHandle (STD_INPUT_HANDLE),
8914 parent,
8915 &stdin_save,
8917 FALSE,
8918 DUPLICATE_SAME_ACCESS);
8920 DuplicateHandle (parent,
8921 GetStdHandle (STD_OUTPUT_HANDLE),
8922 parent,
8923 &stdout_save,
8925 FALSE,
8926 DUPLICATE_SAME_ACCESS);
8928 DuplicateHandle (parent,
8929 GetStdHandle (STD_ERROR_HANDLE),
8930 parent,
8931 &stderr_save,
8933 FALSE,
8934 DUPLICATE_SAME_ACCESS);
8936 fclose (stdin);
8937 fclose (stdout);
8938 fclose (stderr);
8940 if (stdin_save != INVALID_HANDLE_VALUE)
8941 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
8942 else
8943 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
8944 _fdopen (0, "r");
8946 if (stdout_save != INVALID_HANDLE_VALUE)
8947 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
8948 else
8949 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8950 _fdopen (1, "w");
8952 if (stderr_save != INVALID_HANDLE_VALUE)
8953 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
8954 else
8955 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8956 _fdopen (2, "w");
8959 /* unfortunately, atexit depends on implementation of malloc */
8960 /* atexit (term_ntproc); */
8961 if (!dumping)
8963 /* Make sure we start with all signals unblocked. */
8964 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
8965 signal (SIGABRT, term_ntproc);
8967 init_timers ();
8969 /* determine which drives are fixed, for GetCachedVolumeInformation */
8971 /* GetDriveType must have trailing backslash. */
8972 char drive[] = "A:\\";
8974 /* Loop over all possible drive letters */
8975 while (*drive <= 'Z')
8977 /* Record if this drive letter refers to a fixed drive. */
8978 fixed_drives[DRIVE_INDEX (*drive)] =
8979 (GetDriveType (drive) == DRIVE_FIXED);
8981 (*drive)++;
8984 /* Reset the volume info cache. */
8985 volume_cache = NULL;
8990 shutdown_handler ensures that buffers' autosave files are
8991 up to date when the user logs off, or the system shuts down.
8993 static BOOL WINAPI
8994 shutdown_handler (DWORD type)
8996 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
8997 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
8998 || type == CTRL_LOGOFF_EVENT /* User logs off. */
8999 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9001 /* Shut down cleanly, making sure autosave files are up to date. */
9002 shut_down_emacs (0, Qnil);
9005 /* Allow other handlers to handle this signal. */
9006 return FALSE;
9009 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9010 NT, return a handle to GDI32.DLL. */
9011 HANDLE
9012 maybe_load_unicows_dll (void)
9014 if (os_subtype == OS_9X)
9016 HANDLE ret = LoadLibrary ("Unicows.dll");
9017 if (ret)
9019 /* These two functions are present on Windows 9X as stubs
9020 that always fail. We need the real implementations from
9021 UNICOWS.DLL, so we must call these functions through
9022 pointers, and assign the correct addresses to these
9023 pointers at program startup (see emacs.c, which calls
9024 this function early on). */
9025 pMultiByteToWideChar = GetProcAddress (ret, "MultiByteToWideChar");
9026 pWideCharToMultiByte = GetProcAddress (ret, "WideCharToMultiByte");
9027 return ret;
9029 else
9031 int button;
9033 button = MessageBox (NULL,
9034 "Emacs cannot load the UNICOWS.DLL library.\n"
9035 "This library is essential for using Emacs\n"
9036 "on this system. You need to install it.\n\n"
9037 "Emacs will exit when you click OK.",
9038 "Emacs cannot load UNICOWS.DLL",
9039 MB_ICONERROR | MB_TASKMODAL
9040 | MB_SETFOREGROUND | MB_OK);
9041 switch (button)
9043 case IDOK:
9044 default:
9045 exit (1);
9049 else
9051 /* On NT family of Windows, these two functions are always
9052 linked in, so we just assign their addresses to the 2
9053 pointers; no need for the LoadLibrary dance. */
9054 pMultiByteToWideChar = MultiByteToWideChar;
9055 pWideCharToMultiByte = WideCharToMultiByte;
9056 return LoadLibrary ("Gdi32.dll");
9061 globals_of_w32 is used to initialize those global variables that
9062 must always be initialized on startup even when the global variable
9063 initialized is non zero (see the function main in emacs.c).
9065 void
9066 globals_of_w32 (void)
9068 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9070 get_process_times_fn = (GetProcessTimes_Proc)
9071 GetProcAddress (kernel32, "GetProcessTimes");
9073 DEFSYM (QCloaded_from, ":loaded-from");
9075 g_b_init_is_windows_9x = 0;
9076 g_b_init_open_process_token = 0;
9077 g_b_init_get_token_information = 0;
9078 g_b_init_lookup_account_sid = 0;
9079 g_b_init_get_sid_sub_authority = 0;
9080 g_b_init_get_sid_sub_authority_count = 0;
9081 g_b_init_get_security_info = 0;
9082 g_b_init_get_file_security_w = 0;
9083 g_b_init_get_file_security_a = 0;
9084 g_b_init_get_security_descriptor_owner = 0;
9085 g_b_init_get_security_descriptor_group = 0;
9086 g_b_init_is_valid_sid = 0;
9087 g_b_init_create_toolhelp32_snapshot = 0;
9088 g_b_init_process32_first = 0;
9089 g_b_init_process32_next = 0;
9090 g_b_init_open_thread_token = 0;
9091 g_b_init_impersonate_self = 0;
9092 g_b_init_revert_to_self = 0;
9093 g_b_init_get_process_memory_info = 0;
9094 g_b_init_get_process_working_set_size = 0;
9095 g_b_init_global_memory_status = 0;
9096 g_b_init_global_memory_status_ex = 0;
9097 g_b_init_equal_sid = 0;
9098 g_b_init_copy_sid = 0;
9099 g_b_init_get_length_sid = 0;
9100 g_b_init_get_native_system_info = 0;
9101 g_b_init_get_system_times = 0;
9102 g_b_init_create_symbolic_link_w = 0;
9103 g_b_init_create_symbolic_link_a = 0;
9104 g_b_init_get_security_descriptor_dacl = 0;
9105 g_b_init_convert_sd_to_sddl = 0;
9106 g_b_init_convert_sddl_to_sd = 0;
9107 g_b_init_is_valid_security_descriptor = 0;
9108 g_b_init_set_file_security_w = 0;
9109 g_b_init_set_file_security_a = 0;
9110 g_b_init_set_named_security_info_w = 0;
9111 g_b_init_set_named_security_info_a = 0;
9112 g_b_init_get_adapters_info = 0;
9113 num_of_processors = 0;
9114 /* The following sets a handler for shutdown notifications for
9115 console apps. This actually applies to Emacs in both console and
9116 GUI modes, since we had to fool windows into thinking emacs is a
9117 console application to get console mode to work. */
9118 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9120 /* "None" is the default group name on standalone workstations. */
9121 strcpy (dflt_group_name, "None");
9123 /* Reset, in case it has some value inherited from dump time. */
9124 w32_stat_get_owner_group = 0;
9126 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9127 (a.k.a. "wide") APIs to invoke functions that accept file
9128 names. */
9129 if (is_windows_9x ())
9130 w32_unicode_filenames = 0;
9131 else
9132 w32_unicode_filenames = 1;
9135 /* For make-serial-process */
9137 serial_open (Lisp_Object port_obj)
9139 char *port = SSDATA (port_obj);
9140 HANDLE hnd;
9141 child_process *cp;
9142 int fd = -1;
9144 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9145 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9146 if (hnd == INVALID_HANDLE_VALUE)
9147 error ("Could not open %s", port);
9148 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9149 if (fd == -1)
9150 error ("Could not open %s", port);
9152 cp = new_child ();
9153 if (!cp)
9154 error ("Could not create child process");
9155 cp->fd = fd;
9156 cp->status = STATUS_READ_ACKNOWLEDGED;
9157 fd_info[ fd ].hnd = hnd;
9158 fd_info[ fd ].flags |=
9159 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9160 if (fd_info[ fd ].cp != NULL)
9162 error ("fd_info[fd = %d] is already in use", fd);
9164 fd_info[ fd ].cp = cp;
9165 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9166 if (cp->ovl_read.hEvent == NULL)
9167 error ("Could not create read event");
9168 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9169 if (cp->ovl_write.hEvent == NULL)
9170 error ("Could not create write event");
9172 return fd;
9175 /* For serial-process-configure */
9176 void
9177 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9179 Lisp_Object childp2 = Qnil;
9180 Lisp_Object tem = Qnil;
9181 HANDLE hnd;
9182 DCB dcb;
9183 COMMTIMEOUTS ct;
9184 char summary[4] = "???"; /* This usually becomes "8N1". */
9186 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9187 error ("Not a serial process");
9188 hnd = fd_info[ p->outfd ].hnd;
9190 childp2 = Fcopy_sequence (p->childp);
9192 /* Initialize timeouts for blocking read and blocking write. */
9193 if (!GetCommTimeouts (hnd, &ct))
9194 error ("GetCommTimeouts() failed");
9195 ct.ReadIntervalTimeout = 0;
9196 ct.ReadTotalTimeoutMultiplier = 0;
9197 ct.ReadTotalTimeoutConstant = 0;
9198 ct.WriteTotalTimeoutMultiplier = 0;
9199 ct.WriteTotalTimeoutConstant = 0;
9200 if (!SetCommTimeouts (hnd, &ct))
9201 error ("SetCommTimeouts() failed");
9202 /* Read port attributes and prepare default configuration. */
9203 memset (&dcb, 0, sizeof (dcb));
9204 dcb.DCBlength = sizeof (DCB);
9205 if (!GetCommState (hnd, &dcb))
9206 error ("GetCommState() failed");
9207 dcb.fBinary = TRUE;
9208 dcb.fNull = FALSE;
9209 dcb.fAbortOnError = FALSE;
9210 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9211 dcb.ErrorChar = 0;
9212 dcb.EofChar = 0;
9213 dcb.EvtChar = 0;
9215 /* Configure speed. */
9216 if (!NILP (Fplist_member (contact, QCspeed)))
9217 tem = Fplist_get (contact, QCspeed);
9218 else
9219 tem = Fplist_get (p->childp, QCspeed);
9220 CHECK_NUMBER (tem);
9221 dcb.BaudRate = XINT (tem);
9222 childp2 = Fplist_put (childp2, QCspeed, tem);
9224 /* Configure bytesize. */
9225 if (!NILP (Fplist_member (contact, QCbytesize)))
9226 tem = Fplist_get (contact, QCbytesize);
9227 else
9228 tem = Fplist_get (p->childp, QCbytesize);
9229 if (NILP (tem))
9230 tem = make_number (8);
9231 CHECK_NUMBER (tem);
9232 if (XINT (tem) != 7 && XINT (tem) != 8)
9233 error (":bytesize must be nil (8), 7, or 8");
9234 dcb.ByteSize = XINT (tem);
9235 summary[0] = XINT (tem) + '0';
9236 childp2 = Fplist_put (childp2, QCbytesize, tem);
9238 /* Configure parity. */
9239 if (!NILP (Fplist_member (contact, QCparity)))
9240 tem = Fplist_get (contact, QCparity);
9241 else
9242 tem = Fplist_get (p->childp, QCparity);
9243 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9244 error (":parity must be nil (no parity), `even', or `odd'");
9245 dcb.fParity = FALSE;
9246 dcb.Parity = NOPARITY;
9247 dcb.fErrorChar = FALSE;
9248 if (NILP (tem))
9250 summary[1] = 'N';
9252 else if (EQ (tem, Qeven))
9254 summary[1] = 'E';
9255 dcb.fParity = TRUE;
9256 dcb.Parity = EVENPARITY;
9257 dcb.fErrorChar = TRUE;
9259 else if (EQ (tem, Qodd))
9261 summary[1] = 'O';
9262 dcb.fParity = TRUE;
9263 dcb.Parity = ODDPARITY;
9264 dcb.fErrorChar = TRUE;
9266 childp2 = Fplist_put (childp2, QCparity, tem);
9268 /* Configure stopbits. */
9269 if (!NILP (Fplist_member (contact, QCstopbits)))
9270 tem = Fplist_get (contact, QCstopbits);
9271 else
9272 tem = Fplist_get (p->childp, QCstopbits);
9273 if (NILP (tem))
9274 tem = make_number (1);
9275 CHECK_NUMBER (tem);
9276 if (XINT (tem) != 1 && XINT (tem) != 2)
9277 error (":stopbits must be nil (1 stopbit), 1, or 2");
9278 summary[2] = XINT (tem) + '0';
9279 if (XINT (tem) == 1)
9280 dcb.StopBits = ONESTOPBIT;
9281 else if (XINT (tem) == 2)
9282 dcb.StopBits = TWOSTOPBITS;
9283 childp2 = Fplist_put (childp2, QCstopbits, tem);
9285 /* Configure flowcontrol. */
9286 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9287 tem = Fplist_get (contact, QCflowcontrol);
9288 else
9289 tem = Fplist_get (p->childp, QCflowcontrol);
9290 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9291 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9292 dcb.fOutxCtsFlow = FALSE;
9293 dcb.fOutxDsrFlow = FALSE;
9294 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9295 dcb.fDsrSensitivity = FALSE;
9296 dcb.fTXContinueOnXoff = FALSE;
9297 dcb.fOutX = FALSE;
9298 dcb.fInX = FALSE;
9299 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9300 dcb.XonChar = 17; /* Control-Q */
9301 dcb.XoffChar = 19; /* Control-S */
9302 if (NILP (tem))
9304 /* Already configured. */
9306 else if (EQ (tem, Qhw))
9308 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9309 dcb.fOutxCtsFlow = TRUE;
9311 else if (EQ (tem, Qsw))
9313 dcb.fOutX = TRUE;
9314 dcb.fInX = TRUE;
9316 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9318 /* Activate configuration. */
9319 if (!SetCommState (hnd, &dcb))
9320 error ("SetCommState() failed");
9322 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9323 pset_childp (p, childp2);
9326 #ifdef HAVE_GNUTLS
9328 ssize_t
9329 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9331 int n, err;
9332 SELECT_TYPE fdset;
9333 struct timespec timeout;
9334 struct Lisp_Process *process = (struct Lisp_Process *)p;
9335 int fd = process->infd;
9337 n = sys_read (fd, (char*)buf, sz);
9339 if (n >= 0)
9340 return n;
9342 err = errno;
9344 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9345 if (err == EWOULDBLOCK)
9346 err = EAGAIN;
9348 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9350 return -1;
9353 ssize_t
9354 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9356 struct Lisp_Process *process = (struct Lisp_Process *)p;
9357 int fd = process->outfd;
9358 ssize_t n = sys_write (fd, buf, sz);
9360 /* 0 or more bytes written means everything went fine. */
9361 if (n >= 0)
9362 return n;
9364 /* Negative bytes written means we got an error in errno.
9365 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9366 emacs_gnutls_transport_set_errno (process->gnutls_state,
9367 errno == EWOULDBLOCK ? EAGAIN : errno);
9369 return -1;
9371 #endif /* HAVE_GNUTLS */
9373 /* end of w32.c */