Ibuffer: 'w' and 'B' default to buffer at current line
[emacs.git] / src / w32.c
blobf9110853799f25a99730f6e64ad57f1b517e6121
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #define DEFER_MS_W32_H
25 #include <config.h>
27 #include <mingw_time.h>
28 #include <stddef.h> /* for offsetof */
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <float.h> /* for DBL_EPSILON */
32 #include <io.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <sys/file.h>
38 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
39 #include <sys/time.h>
40 #include <sys/utime.h>
41 #include <math.h>
43 /* Include (most) CRT headers *before* ms-w32.h. */
44 #include <ms-w32.h>
46 #include <string.h> /* for strerror, needed by sys_strerror */
47 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
49 #undef access
50 #undef chdir
51 #undef chmod
52 #undef creat
53 #undef ctime
54 #undef fopen
55 #undef link
56 #undef mkdir
57 #undef open
58 #undef rename
59 #undef rmdir
60 #undef unlink
62 #undef close
63 #undef dup
64 #undef dup2
65 #undef pipe
66 #undef read
67 #undef write
69 #undef strerror
71 #undef localtime
73 char *sys_ctime (const time_t *);
74 int sys_chdir (const char *);
75 int sys_creat (const char *, int);
76 FILE *sys_fopen (const char *, const char *);
77 int sys_mkdir (const char *);
78 int sys_open (const char *, int, int);
79 int sys_rename (char const *, char const *);
80 int sys_rmdir (const char *);
81 int sys_close (int);
82 int sys_dup2 (int, int);
83 int sys_read (int, char *, unsigned int);
84 int sys_write (int, const void *, unsigned int);
85 struct tm *sys_localtime (const time_t *);
87 #ifdef HAVE_MODULES
88 extern void dynlib_reset_last_error (void);
89 #endif
91 #include "lisp.h"
92 #include "epaths.h" /* for PATH_EXEC */
94 #include <pwd.h>
95 #include <grp.h>
97 /* MinGW64 defines these in its _mingw.h. */
98 #ifndef _ANONYMOUS_UNION
99 # define _ANONYMOUS_UNION
100 #endif
101 #ifndef _ANONYMOUS_STRUCT
102 # define _ANONYMOUS_STRUCT
103 #endif
104 #include <windows.h>
105 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
106 use a different name to avoid compilation problems. */
107 typedef struct _MEMORY_STATUS_EX {
108 DWORD dwLength;
109 DWORD dwMemoryLoad;
110 DWORDLONG ullTotalPhys;
111 DWORDLONG ullAvailPhys;
112 DWORDLONG ullTotalPageFile;
113 DWORDLONG ullAvailPageFile;
114 DWORDLONG ullTotalVirtual;
115 DWORDLONG ullAvailVirtual;
116 DWORDLONG ullAvailExtendedVirtual;
117 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
119 /* These are here so that GDB would know about these data types. This
120 allows attaching GDB to Emacs when a fatal exception is triggered
121 and Windows pops up the "application needs to be closed" dialog.
122 At that point, _gnu_exception_handler, the top-level exception
123 handler installed by the MinGW startup code, is somewhere on the
124 call-stack of the main thread, so going to that call frame and
125 looking at the argument to _gnu_exception_handler, which is a
126 PEXCEPTION_POINTERS pointer, can reveal the exception code
127 (excptr->ExceptionRecord->ExceptionCode) and the address where the
128 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
129 well as some additional information specific to the exception. */
130 PEXCEPTION_POINTERS excptr;
131 PEXCEPTION_RECORD excprec;
132 PCONTEXT ctxrec;
134 #include <lmcons.h>
135 #include <shlobj.h>
137 #include <tlhelp32.h>
138 #include <psapi.h>
139 #ifndef _MSC_VER
140 #include <w32api.h>
141 #endif
142 #if _WIN32_WINNT < 0x0500
143 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
144 /* This either is not in psapi.h or guarded by higher value of
145 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
146 defines it in psapi.h */
147 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
148 DWORD cb;
149 DWORD PageFaultCount;
150 SIZE_T PeakWorkingSetSize;
151 SIZE_T WorkingSetSize;
152 SIZE_T QuotaPeakPagedPoolUsage;
153 SIZE_T QuotaPagedPoolUsage;
154 SIZE_T QuotaPeakNonPagedPoolUsage;
155 SIZE_T QuotaNonPagedPoolUsage;
156 SIZE_T PagefileUsage;
157 SIZE_T PeakPagefileUsage;
158 SIZE_T PrivateUsage;
159 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
160 #endif
161 #endif
163 #include <winioctl.h>
164 #include <aclapi.h>
165 #include <sddl.h>
167 #include <sys/acl.h>
168 #include <acl.h>
170 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
171 define them by hand if not already defined. */
172 #ifndef SDDL_REVISION_1
173 #define SDDL_REVISION_1 1
174 #endif /* SDDL_REVISION_1 */
176 #if defined(_MSC_VER) || defined(MINGW_W64)
177 /* MSVC and MinGW64 don't provide the definition of
178 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
179 which cannot be included because it triggers conflicts with other
180 Windows API headers. So we define it here by hand. */
182 typedef struct _REPARSE_DATA_BUFFER {
183 ULONG ReparseTag;
184 USHORT ReparseDataLength;
185 USHORT Reserved;
186 union {
187 struct {
188 USHORT SubstituteNameOffset;
189 USHORT SubstituteNameLength;
190 USHORT PrintNameOffset;
191 USHORT PrintNameLength;
192 ULONG Flags;
193 WCHAR PathBuffer[1];
194 } SymbolicLinkReparseBuffer;
195 struct {
196 USHORT SubstituteNameOffset;
197 USHORT SubstituteNameLength;
198 USHORT PrintNameOffset;
199 USHORT PrintNameLength;
200 WCHAR PathBuffer[1];
201 } MountPointReparseBuffer;
202 struct {
203 UCHAR DataBuffer[1];
204 } GenericReparseBuffer;
205 } DUMMYUNIONNAME;
206 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
208 #ifndef FILE_DEVICE_FILE_SYSTEM
209 #define FILE_DEVICE_FILE_SYSTEM 9
210 #endif
211 #ifndef METHOD_BUFFERED
212 #define METHOD_BUFFERED 0
213 #endif
214 #ifndef FILE_ANY_ACCESS
215 #define FILE_ANY_ACCESS 0x00000000
216 #endif
217 #ifndef CTL_CODE
218 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
219 #endif
220 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
221 #ifndef FSCTL_GET_REPARSE_POINT
222 #define FSCTL_GET_REPARSE_POINT \
223 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
224 #endif
225 #endif
227 /* TCP connection support. */
228 #include <sys/socket.h>
229 #undef socket
230 #undef bind
231 #undef connect
232 #undef htons
233 #undef ntohs
234 #undef inet_addr
235 #undef gethostname
236 #undef gethostbyname
237 #undef getservbyname
238 #undef getpeername
239 #undef shutdown
240 #undef setsockopt
241 #undef listen
242 #undef getsockname
243 #undef accept
244 #undef recvfrom
245 #undef sendto
247 #include <iphlpapi.h> /* should be after winsock2.h */
249 #include <wincrypt.h>
251 #include <c-strcase.h>
252 #include <utimens.h> /* for fdutimens */
254 #include "w32.h"
255 #include <dirent.h>
256 #include "w32common.h"
257 #include "w32select.h"
258 #include "systime.h" /* for current_timespec, struct timespec */
259 #include "dispextern.h" /* for xstrcasecmp */
260 #include "coding.h" /* for Vlocale_coding_system */
262 #include "careadlinkat.h"
263 #include "allocator.h"
265 /* For Lisp_Process, serial_configure and serial_open. */
266 #include "process.h"
267 #include "systty.h"
269 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
270 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
272 static DWORD get_rid (PSID);
273 static int is_symlink (const char *);
274 static char * chase_symlinks (const char *);
275 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
276 static int restore_privilege (TOKEN_PRIVILEGES *);
277 static BOOL WINAPI revert_to_self (void);
279 static int sys_access (const char *, int);
280 extern void *e_malloc (size_t);
281 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
282 struct timespec *, void *);
283 extern int sys_dup (int);
288 /* Initialization states.
290 WARNING: If you add any more such variables for additional APIs,
291 you MUST add initialization for them to globals_of_w32
292 below. This is because these variables might get set
293 to non-NULL values during dumping, but the dumped Emacs
294 cannot reuse those values, because it could be run on a
295 different version of the OS, where API addresses are
296 different. */
297 static BOOL g_b_init_is_windows_9x;
298 static BOOL g_b_init_open_process_token;
299 static BOOL g_b_init_get_token_information;
300 static BOOL g_b_init_lookup_account_sid;
301 static BOOL g_b_init_get_sid_sub_authority;
302 static BOOL g_b_init_get_sid_sub_authority_count;
303 static BOOL g_b_init_get_security_info;
304 static BOOL g_b_init_get_file_security_w;
305 static BOOL g_b_init_get_file_security_a;
306 static BOOL g_b_init_get_security_descriptor_owner;
307 static BOOL g_b_init_get_security_descriptor_group;
308 static BOOL g_b_init_is_valid_sid;
309 static BOOL g_b_init_create_toolhelp32_snapshot;
310 static BOOL g_b_init_process32_first;
311 static BOOL g_b_init_process32_next;
312 static BOOL g_b_init_open_thread_token;
313 static BOOL g_b_init_impersonate_self;
314 static BOOL g_b_init_revert_to_self;
315 static BOOL g_b_init_get_process_memory_info;
316 static BOOL g_b_init_get_process_working_set_size;
317 static BOOL g_b_init_global_memory_status;
318 static BOOL g_b_init_global_memory_status_ex;
319 static BOOL g_b_init_get_length_sid;
320 static BOOL g_b_init_equal_sid;
321 static BOOL g_b_init_copy_sid;
322 static BOOL g_b_init_get_native_system_info;
323 static BOOL g_b_init_get_system_times;
324 static BOOL g_b_init_create_symbolic_link_w;
325 static BOOL g_b_init_create_symbolic_link_a;
326 static BOOL g_b_init_get_security_descriptor_dacl;
327 static BOOL g_b_init_convert_sd_to_sddl;
328 static BOOL g_b_init_convert_sddl_to_sd;
329 static BOOL g_b_init_is_valid_security_descriptor;
330 static BOOL g_b_init_set_file_security_w;
331 static BOOL g_b_init_set_file_security_a;
332 static BOOL g_b_init_set_named_security_info_w;
333 static BOOL g_b_init_set_named_security_info_a;
334 static BOOL g_b_init_get_adapters_info;
336 BOOL g_b_init_compare_string_w;
339 BEGIN: Wrapper functions around OpenProcessToken
340 and other functions in advapi32.dll that are only
341 supported in Windows NT / 2k / XP
343 /* ** Function pointer typedefs ** */
344 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
345 HANDLE ProcessHandle,
346 DWORD DesiredAccess,
347 PHANDLE TokenHandle);
348 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
349 HANDLE TokenHandle,
350 TOKEN_INFORMATION_CLASS TokenInformationClass,
351 LPVOID TokenInformation,
352 DWORD TokenInformationLength,
353 PDWORD ReturnLength);
354 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
355 HANDLE process_handle,
356 LPFILETIME creation_time,
357 LPFILETIME exit_time,
358 LPFILETIME kernel_time,
359 LPFILETIME user_time);
361 GetProcessTimes_Proc get_process_times_fn = NULL;
363 #ifdef _UNICODE
364 const char * const LookupAccountSid_Name = "LookupAccountSidW";
365 #else
366 const char * const LookupAccountSid_Name = "LookupAccountSidA";
367 #endif
368 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
369 LPCTSTR lpSystemName,
370 PSID Sid,
371 LPTSTR Name,
372 LPDWORD cbName,
373 LPTSTR DomainName,
374 LPDWORD cbDomainName,
375 PSID_NAME_USE peUse);
376 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
377 PSID pSid,
378 DWORD n);
379 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
380 PSID pSid);
381 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
382 HANDLE handle,
383 SE_OBJECT_TYPE ObjectType,
384 SECURITY_INFORMATION SecurityInfo,
385 PSID *ppsidOwner,
386 PSID *ppsidGroup,
387 PACL *ppDacl,
388 PACL *ppSacl,
389 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
390 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
391 LPCWSTR lpFileName,
392 SECURITY_INFORMATION RequestedInformation,
393 PSECURITY_DESCRIPTOR pSecurityDescriptor,
394 DWORD nLength,
395 LPDWORD lpnLengthNeeded);
396 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
397 LPCSTR lpFileName,
398 SECURITY_INFORMATION RequestedInformation,
399 PSECURITY_DESCRIPTOR pSecurityDescriptor,
400 DWORD nLength,
401 LPDWORD lpnLengthNeeded);
402 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
403 LPCWSTR lpFileName,
404 SECURITY_INFORMATION SecurityInformation,
405 PSECURITY_DESCRIPTOR pSecurityDescriptor);
406 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
407 LPCSTR lpFileName,
408 SECURITY_INFORMATION SecurityInformation,
409 PSECURITY_DESCRIPTOR pSecurityDescriptor);
410 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
411 LPCWSTR lpObjectName,
412 SE_OBJECT_TYPE ObjectType,
413 SECURITY_INFORMATION SecurityInformation,
414 PSID psidOwner,
415 PSID psidGroup,
416 PACL pDacl,
417 PACL pSacl);
418 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
419 LPCSTR lpObjectName,
420 SE_OBJECT_TYPE ObjectType,
421 SECURITY_INFORMATION SecurityInformation,
422 PSID psidOwner,
423 PSID psidGroup,
424 PACL pDacl,
425 PACL pSacl);
426 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
427 PSECURITY_DESCRIPTOR pSecurityDescriptor,
428 PSID *pOwner,
429 LPBOOL lpbOwnerDefaulted);
430 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
431 PSECURITY_DESCRIPTOR pSecurityDescriptor,
432 PSID *pGroup,
433 LPBOOL lpbGroupDefaulted);
434 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
435 PSECURITY_DESCRIPTOR pSecurityDescriptor,
436 LPBOOL lpbDaclPresent,
437 PACL *pDacl,
438 LPBOOL lpbDaclDefaulted);
439 typedef BOOL (WINAPI * IsValidSid_Proc) (
440 PSID sid);
441 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
442 DWORD dwFlags,
443 DWORD th32ProcessID);
444 typedef BOOL (WINAPI * Process32First_Proc) (
445 HANDLE hSnapshot,
446 LPPROCESSENTRY32 lppe);
447 typedef BOOL (WINAPI * Process32Next_Proc) (
448 HANDLE hSnapshot,
449 LPPROCESSENTRY32 lppe);
450 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
451 HANDLE ThreadHandle,
452 DWORD DesiredAccess,
453 BOOL OpenAsSelf,
454 PHANDLE TokenHandle);
455 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
456 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
457 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
458 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
459 HANDLE Process,
460 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
461 DWORD cb);
462 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
463 HANDLE hProcess,
464 PSIZE_T lpMinimumWorkingSetSize,
465 PSIZE_T lpMaximumWorkingSetSize);
466 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
467 LPMEMORYSTATUS lpBuffer);
468 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
469 LPMEMORY_STATUS_EX lpBuffer);
470 typedef BOOL (WINAPI * CopySid_Proc) (
471 DWORD nDestinationSidLength,
472 PSID pDestinationSid,
473 PSID pSourceSid);
474 typedef BOOL (WINAPI * EqualSid_Proc) (
475 PSID pSid1,
476 PSID pSid2);
477 typedef DWORD (WINAPI * GetLengthSid_Proc) (
478 PSID pSid);
479 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
480 LPSYSTEM_INFO lpSystemInfo);
481 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
482 LPFILETIME lpIdleTime,
483 LPFILETIME lpKernelTime,
484 LPFILETIME lpUserTime);
485 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
486 LPCWSTR lpSymlinkFileName,
487 LPCWSTR lpTargetFileName,
488 DWORD dwFlags);
489 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
490 LPCSTR lpSymlinkFileName,
491 LPCSTR lpTargetFileName,
492 DWORD dwFlags);
493 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
494 LPCTSTR StringSecurityDescriptor,
495 DWORD StringSDRevision,
496 PSECURITY_DESCRIPTOR *SecurityDescriptor,
497 PULONG SecurityDescriptorSize);
498 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
499 PSECURITY_DESCRIPTOR SecurityDescriptor,
500 DWORD RequestedStringSDRevision,
501 SECURITY_INFORMATION SecurityInformation,
502 LPTSTR *StringSecurityDescriptor,
503 PULONG StringSecurityDescriptorLen);
504 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
505 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
506 PIP_ADAPTER_INFO pAdapterInfo,
507 PULONG pOutBufLen);
509 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
510 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
511 DWORD multiByteToWideCharFlags;
513 /* ** A utility function ** */
514 static BOOL
515 is_windows_9x (void)
517 static BOOL s_b_ret = 0;
518 OSVERSIONINFO os_ver;
519 if (g_b_init_is_windows_9x == 0)
521 g_b_init_is_windows_9x = 1;
522 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
523 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
524 if (GetVersionEx (&os_ver))
526 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
529 return s_b_ret;
532 static Lisp_Object ltime (ULONGLONG);
534 /* Get total user and system times for get-internal-run-time.
535 Returns a list of integers if the times are provided by the OS
536 (NT derivatives), otherwise it returns the result of current-time. */
537 Lisp_Object w32_get_internal_run_time (void);
539 Lisp_Object
540 w32_get_internal_run_time (void)
542 if (get_process_times_fn)
544 FILETIME create, exit, kernel, user;
545 HANDLE proc = GetCurrentProcess ();
546 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
548 LARGE_INTEGER user_int, kernel_int, total;
549 user_int.LowPart = user.dwLowDateTime;
550 user_int.HighPart = user.dwHighDateTime;
551 kernel_int.LowPart = kernel.dwLowDateTime;
552 kernel_int.HighPart = kernel.dwHighDateTime;
553 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
554 return ltime (total.QuadPart);
558 return Fcurrent_time ();
561 /* ** The wrapper functions ** */
563 static BOOL WINAPI
564 open_process_token (HANDLE ProcessHandle,
565 DWORD DesiredAccess,
566 PHANDLE TokenHandle)
568 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
569 HMODULE hm_advapi32 = NULL;
570 if (is_windows_9x () == TRUE)
572 return FALSE;
574 if (g_b_init_open_process_token == 0)
576 g_b_init_open_process_token = 1;
577 hm_advapi32 = LoadLibrary ("Advapi32.dll");
578 s_pfn_Open_Process_Token =
579 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
581 if (s_pfn_Open_Process_Token == NULL)
583 return FALSE;
585 return (
586 s_pfn_Open_Process_Token (
587 ProcessHandle,
588 DesiredAccess,
589 TokenHandle)
593 static BOOL WINAPI
594 get_token_information (HANDLE TokenHandle,
595 TOKEN_INFORMATION_CLASS TokenInformationClass,
596 LPVOID TokenInformation,
597 DWORD TokenInformationLength,
598 PDWORD ReturnLength)
600 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
601 HMODULE hm_advapi32 = NULL;
602 if (is_windows_9x () == TRUE)
604 return FALSE;
606 if (g_b_init_get_token_information == 0)
608 g_b_init_get_token_information = 1;
609 hm_advapi32 = LoadLibrary ("Advapi32.dll");
610 s_pfn_Get_Token_Information =
611 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
613 if (s_pfn_Get_Token_Information == NULL)
615 return FALSE;
617 return (
618 s_pfn_Get_Token_Information (
619 TokenHandle,
620 TokenInformationClass,
621 TokenInformation,
622 TokenInformationLength,
623 ReturnLength)
627 static BOOL WINAPI
628 lookup_account_sid (LPCTSTR lpSystemName,
629 PSID Sid,
630 LPTSTR Name,
631 LPDWORD cbName,
632 LPTSTR DomainName,
633 LPDWORD cbDomainName,
634 PSID_NAME_USE peUse)
636 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
637 HMODULE hm_advapi32 = NULL;
638 if (is_windows_9x () == TRUE)
640 return FALSE;
642 if (g_b_init_lookup_account_sid == 0)
644 g_b_init_lookup_account_sid = 1;
645 hm_advapi32 = LoadLibrary ("Advapi32.dll");
646 s_pfn_Lookup_Account_Sid =
647 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
649 if (s_pfn_Lookup_Account_Sid == NULL)
651 return FALSE;
653 return (
654 s_pfn_Lookup_Account_Sid (
655 lpSystemName,
656 Sid,
657 Name,
658 cbName,
659 DomainName,
660 cbDomainName,
661 peUse)
665 static PDWORD WINAPI
666 get_sid_sub_authority (PSID pSid, DWORD n)
668 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
669 static DWORD zero = 0U;
670 HMODULE hm_advapi32 = NULL;
671 if (is_windows_9x () == TRUE)
673 return &zero;
675 if (g_b_init_get_sid_sub_authority == 0)
677 g_b_init_get_sid_sub_authority = 1;
678 hm_advapi32 = LoadLibrary ("Advapi32.dll");
679 s_pfn_Get_Sid_Sub_Authority =
680 (GetSidSubAuthority_Proc) GetProcAddress (
681 hm_advapi32, "GetSidSubAuthority");
683 if (s_pfn_Get_Sid_Sub_Authority == NULL)
685 return &zero;
687 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
690 static PUCHAR WINAPI
691 get_sid_sub_authority_count (PSID pSid)
693 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
694 static UCHAR zero = 0U;
695 HMODULE hm_advapi32 = NULL;
696 if (is_windows_9x () == TRUE)
698 return &zero;
700 if (g_b_init_get_sid_sub_authority_count == 0)
702 g_b_init_get_sid_sub_authority_count = 1;
703 hm_advapi32 = LoadLibrary ("Advapi32.dll");
704 s_pfn_Get_Sid_Sub_Authority_Count =
705 (GetSidSubAuthorityCount_Proc) GetProcAddress (
706 hm_advapi32, "GetSidSubAuthorityCount");
708 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
710 return &zero;
712 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
715 static DWORD WINAPI
716 get_security_info (HANDLE handle,
717 SE_OBJECT_TYPE ObjectType,
718 SECURITY_INFORMATION SecurityInfo,
719 PSID *ppsidOwner,
720 PSID *ppsidGroup,
721 PACL *ppDacl,
722 PACL *ppSacl,
723 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
725 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
726 HMODULE hm_advapi32 = NULL;
727 if (is_windows_9x () == TRUE)
729 return FALSE;
731 if (g_b_init_get_security_info == 0)
733 g_b_init_get_security_info = 1;
734 hm_advapi32 = LoadLibrary ("Advapi32.dll");
735 s_pfn_Get_Security_Info =
736 (GetSecurityInfo_Proc) GetProcAddress (
737 hm_advapi32, "GetSecurityInfo");
739 if (s_pfn_Get_Security_Info == NULL)
741 return FALSE;
743 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
744 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
745 ppSecurityDescriptor));
748 static BOOL WINAPI
749 get_file_security (const char *lpFileName,
750 SECURITY_INFORMATION RequestedInformation,
751 PSECURITY_DESCRIPTOR pSecurityDescriptor,
752 DWORD nLength,
753 LPDWORD lpnLengthNeeded)
755 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
756 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
757 HMODULE hm_advapi32 = NULL;
758 if (is_windows_9x () == TRUE)
760 errno = ENOTSUP;
761 return FALSE;
763 if (w32_unicode_filenames)
765 wchar_t filename_w[MAX_PATH];
767 if (g_b_init_get_file_security_w == 0)
769 g_b_init_get_file_security_w = 1;
770 hm_advapi32 = LoadLibrary ("Advapi32.dll");
771 s_pfn_Get_File_SecurityW =
772 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
773 "GetFileSecurityW");
775 if (s_pfn_Get_File_SecurityW == NULL)
777 errno = ENOTSUP;
778 return FALSE;
780 filename_to_utf16 (lpFileName, filename_w);
781 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
782 pSecurityDescriptor, nLength,
783 lpnLengthNeeded));
785 else
787 char filename_a[MAX_PATH];
789 if (g_b_init_get_file_security_a == 0)
791 g_b_init_get_file_security_a = 1;
792 hm_advapi32 = LoadLibrary ("Advapi32.dll");
793 s_pfn_Get_File_SecurityA =
794 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
795 "GetFileSecurityA");
797 if (s_pfn_Get_File_SecurityA == NULL)
799 errno = ENOTSUP;
800 return FALSE;
802 filename_to_ansi (lpFileName, filename_a);
803 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
804 pSecurityDescriptor, nLength,
805 lpnLengthNeeded));
809 static BOOL WINAPI
810 set_file_security (const char *lpFileName,
811 SECURITY_INFORMATION SecurityInformation,
812 PSECURITY_DESCRIPTOR pSecurityDescriptor)
814 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
815 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
816 HMODULE hm_advapi32 = NULL;
817 if (is_windows_9x () == TRUE)
819 errno = ENOTSUP;
820 return FALSE;
822 if (w32_unicode_filenames)
824 wchar_t filename_w[MAX_PATH];
826 if (g_b_init_set_file_security_w == 0)
828 g_b_init_set_file_security_w = 1;
829 hm_advapi32 = LoadLibrary ("Advapi32.dll");
830 s_pfn_Set_File_SecurityW =
831 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
832 "SetFileSecurityW");
834 if (s_pfn_Set_File_SecurityW == NULL)
836 errno = ENOTSUP;
837 return FALSE;
839 filename_to_utf16 (lpFileName, filename_w);
840 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
841 pSecurityDescriptor));
843 else
845 char filename_a[MAX_PATH];
847 if (g_b_init_set_file_security_a == 0)
849 g_b_init_set_file_security_a = 1;
850 hm_advapi32 = LoadLibrary ("Advapi32.dll");
851 s_pfn_Set_File_SecurityA =
852 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
853 "SetFileSecurityA");
855 if (s_pfn_Set_File_SecurityA == NULL)
857 errno = ENOTSUP;
858 return FALSE;
860 filename_to_ansi (lpFileName, filename_a);
861 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
862 pSecurityDescriptor));
866 static DWORD WINAPI
867 set_named_security_info (LPCTSTR lpObjectName,
868 SE_OBJECT_TYPE ObjectType,
869 SECURITY_INFORMATION SecurityInformation,
870 PSID psidOwner,
871 PSID psidGroup,
872 PACL pDacl,
873 PACL pSacl)
875 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
876 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
877 HMODULE hm_advapi32 = NULL;
878 if (is_windows_9x () == TRUE)
880 errno = ENOTSUP;
881 return ENOTSUP;
883 if (w32_unicode_filenames)
885 wchar_t filename_w[MAX_PATH];
887 if (g_b_init_set_named_security_info_w == 0)
889 g_b_init_set_named_security_info_w = 1;
890 hm_advapi32 = LoadLibrary ("Advapi32.dll");
891 s_pfn_Set_Named_Security_InfoW =
892 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
893 "SetNamedSecurityInfoW");
895 if (s_pfn_Set_Named_Security_InfoW == NULL)
897 errno = ENOTSUP;
898 return ENOTSUP;
900 filename_to_utf16 (lpObjectName, filename_w);
901 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
902 SecurityInformation, psidOwner,
903 psidGroup, pDacl, pSacl));
905 else
907 char filename_a[MAX_PATH];
909 if (g_b_init_set_named_security_info_a == 0)
911 g_b_init_set_named_security_info_a = 1;
912 hm_advapi32 = LoadLibrary ("Advapi32.dll");
913 s_pfn_Set_Named_Security_InfoA =
914 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
915 "SetNamedSecurityInfoA");
917 if (s_pfn_Set_Named_Security_InfoA == NULL)
919 errno = ENOTSUP;
920 return ENOTSUP;
922 filename_to_ansi (lpObjectName, filename_a);
923 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
924 SecurityInformation, psidOwner,
925 psidGroup, pDacl, pSacl));
929 static BOOL WINAPI
930 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
931 PSID *pOwner,
932 LPBOOL lpbOwnerDefaulted)
934 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
935 HMODULE hm_advapi32 = NULL;
936 if (is_windows_9x () == TRUE)
938 errno = ENOTSUP;
939 return FALSE;
941 if (g_b_init_get_security_descriptor_owner == 0)
943 g_b_init_get_security_descriptor_owner = 1;
944 hm_advapi32 = LoadLibrary ("Advapi32.dll");
945 s_pfn_Get_Security_Descriptor_Owner =
946 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
947 hm_advapi32, "GetSecurityDescriptorOwner");
949 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
951 errno = ENOTSUP;
952 return FALSE;
954 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
955 lpbOwnerDefaulted));
958 static BOOL WINAPI
959 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
960 PSID *pGroup,
961 LPBOOL lpbGroupDefaulted)
963 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
964 HMODULE hm_advapi32 = NULL;
965 if (is_windows_9x () == TRUE)
967 errno = ENOTSUP;
968 return FALSE;
970 if (g_b_init_get_security_descriptor_group == 0)
972 g_b_init_get_security_descriptor_group = 1;
973 hm_advapi32 = LoadLibrary ("Advapi32.dll");
974 s_pfn_Get_Security_Descriptor_Group =
975 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
976 hm_advapi32, "GetSecurityDescriptorGroup");
978 if (s_pfn_Get_Security_Descriptor_Group == NULL)
980 errno = ENOTSUP;
981 return FALSE;
983 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
984 lpbGroupDefaulted));
987 static BOOL WINAPI
988 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
989 LPBOOL lpbDaclPresent,
990 PACL *pDacl,
991 LPBOOL lpbDaclDefaulted)
993 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
994 HMODULE hm_advapi32 = NULL;
995 if (is_windows_9x () == TRUE)
997 errno = ENOTSUP;
998 return FALSE;
1000 if (g_b_init_get_security_descriptor_dacl == 0)
1002 g_b_init_get_security_descriptor_dacl = 1;
1003 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1004 s_pfn_Get_Security_Descriptor_Dacl =
1005 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
1006 hm_advapi32, "GetSecurityDescriptorDacl");
1008 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
1010 errno = ENOTSUP;
1011 return FALSE;
1013 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
1014 lpbDaclPresent, pDacl,
1015 lpbDaclDefaulted));
1018 static BOOL WINAPI
1019 is_valid_sid (PSID sid)
1021 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
1022 HMODULE hm_advapi32 = NULL;
1023 if (is_windows_9x () == TRUE)
1025 return FALSE;
1027 if (g_b_init_is_valid_sid == 0)
1029 g_b_init_is_valid_sid = 1;
1030 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1031 s_pfn_Is_Valid_Sid =
1032 (IsValidSid_Proc) GetProcAddress (
1033 hm_advapi32, "IsValidSid");
1035 if (s_pfn_Is_Valid_Sid == NULL)
1037 return FALSE;
1039 return (s_pfn_Is_Valid_Sid (sid));
1042 static BOOL WINAPI
1043 equal_sid (PSID sid1, PSID sid2)
1045 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1046 HMODULE hm_advapi32 = NULL;
1047 if (is_windows_9x () == TRUE)
1049 return FALSE;
1051 if (g_b_init_equal_sid == 0)
1053 g_b_init_equal_sid = 1;
1054 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1055 s_pfn_Equal_Sid =
1056 (EqualSid_Proc) GetProcAddress (
1057 hm_advapi32, "EqualSid");
1059 if (s_pfn_Equal_Sid == NULL)
1061 return FALSE;
1063 return (s_pfn_Equal_Sid (sid1, sid2));
1066 static DWORD WINAPI
1067 get_length_sid (PSID sid)
1069 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1070 HMODULE hm_advapi32 = NULL;
1071 if (is_windows_9x () == TRUE)
1073 return 0;
1075 if (g_b_init_get_length_sid == 0)
1077 g_b_init_get_length_sid = 1;
1078 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1079 s_pfn_Get_Length_Sid =
1080 (GetLengthSid_Proc) GetProcAddress (
1081 hm_advapi32, "GetLengthSid");
1083 if (s_pfn_Get_Length_Sid == NULL)
1085 return 0;
1087 return (s_pfn_Get_Length_Sid (sid));
1090 static BOOL WINAPI
1091 copy_sid (DWORD destlen, PSID dest, PSID src)
1093 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1094 HMODULE hm_advapi32 = NULL;
1095 if (is_windows_9x () == TRUE)
1097 return FALSE;
1099 if (g_b_init_copy_sid == 0)
1101 g_b_init_copy_sid = 1;
1102 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1103 s_pfn_Copy_Sid =
1104 (CopySid_Proc) GetProcAddress (
1105 hm_advapi32, "CopySid");
1107 if (s_pfn_Copy_Sid == NULL)
1109 return FALSE;
1111 return (s_pfn_Copy_Sid (destlen, dest, src));
1115 END: Wrapper functions around OpenProcessToken
1116 and other functions in advapi32.dll that are only
1117 supported in Windows NT / 2k / XP
1120 static void WINAPI
1121 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1123 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1124 if (is_windows_9x () != TRUE)
1126 if (g_b_init_get_native_system_info == 0)
1128 g_b_init_get_native_system_info = 1;
1129 s_pfn_Get_Native_System_Info =
1130 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1131 "GetNativeSystemInfo");
1133 if (s_pfn_Get_Native_System_Info != NULL)
1134 s_pfn_Get_Native_System_Info (lpSystemInfo);
1136 else
1137 lpSystemInfo->dwNumberOfProcessors = -1;
1140 static BOOL WINAPI
1141 get_system_times (LPFILETIME lpIdleTime,
1142 LPFILETIME lpKernelTime,
1143 LPFILETIME lpUserTime)
1145 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1146 if (is_windows_9x () == TRUE)
1148 return FALSE;
1150 if (g_b_init_get_system_times == 0)
1152 g_b_init_get_system_times = 1;
1153 s_pfn_Get_System_times =
1154 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1155 "GetSystemTimes");
1157 if (s_pfn_Get_System_times == NULL)
1158 return FALSE;
1159 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1162 static BOOLEAN WINAPI
1163 create_symbolic_link (LPCSTR lpSymlinkFilename,
1164 LPCSTR lpTargetFileName,
1165 DWORD dwFlags)
1167 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1168 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1169 BOOLEAN retval;
1171 if (is_windows_9x () == TRUE)
1173 errno = ENOSYS;
1174 return 0;
1176 if (w32_unicode_filenames)
1178 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1180 if (g_b_init_create_symbolic_link_w == 0)
1182 g_b_init_create_symbolic_link_w = 1;
1183 s_pfn_Create_Symbolic_LinkW =
1184 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1185 "CreateSymbolicLinkW");
1187 if (s_pfn_Create_Symbolic_LinkW == NULL)
1189 errno = ENOSYS;
1190 return 0;
1193 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1194 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1195 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1196 /* If we were denied creation of the symlink, try again after
1197 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1198 if (!retval)
1200 TOKEN_PRIVILEGES priv_current;
1202 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1203 &priv_current))
1205 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1206 restore_privilege (&priv_current);
1207 revert_to_self ();
1211 else
1213 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1215 if (g_b_init_create_symbolic_link_a == 0)
1217 g_b_init_create_symbolic_link_a = 1;
1218 s_pfn_Create_Symbolic_LinkA =
1219 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1220 "CreateSymbolicLinkA");
1222 if (s_pfn_Create_Symbolic_LinkA == NULL)
1224 errno = ENOSYS;
1225 return 0;
1228 filename_to_ansi (lpSymlinkFilename, symfn_a);
1229 filename_to_ansi (lpTargetFileName, tgtfn_a);
1230 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1231 /* If we were denied creation of the symlink, try again after
1232 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1233 if (!retval)
1235 TOKEN_PRIVILEGES priv_current;
1237 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1238 &priv_current))
1240 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1241 restore_privilege (&priv_current);
1242 revert_to_self ();
1246 return retval;
1249 static BOOL WINAPI
1250 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1252 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1254 if (is_windows_9x () == TRUE)
1256 errno = ENOTSUP;
1257 return FALSE;
1260 if (g_b_init_is_valid_security_descriptor == 0)
1262 g_b_init_is_valid_security_descriptor = 1;
1263 s_pfn_Is_Valid_Security_Descriptor_Proc =
1264 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1265 "IsValidSecurityDescriptor");
1267 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1269 errno = ENOTSUP;
1270 return FALSE;
1273 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1276 static BOOL WINAPI
1277 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1278 DWORD RequestedStringSDRevision,
1279 SECURITY_INFORMATION SecurityInformation,
1280 LPTSTR *StringSecurityDescriptor,
1281 PULONG StringSecurityDescriptorLen)
1283 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1284 BOOL retval;
1286 if (is_windows_9x () == TRUE)
1288 errno = ENOTSUP;
1289 return FALSE;
1292 if (g_b_init_convert_sd_to_sddl == 0)
1294 g_b_init_convert_sd_to_sddl = 1;
1295 #ifdef _UNICODE
1296 s_pfn_Convert_SD_To_SDDL =
1297 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1298 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1299 #else
1300 s_pfn_Convert_SD_To_SDDL =
1301 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1302 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1303 #endif
1305 if (s_pfn_Convert_SD_To_SDDL == NULL)
1307 errno = ENOTSUP;
1308 return FALSE;
1311 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1312 RequestedStringSDRevision,
1313 SecurityInformation,
1314 StringSecurityDescriptor,
1315 StringSecurityDescriptorLen);
1317 return retval;
1320 static BOOL WINAPI
1321 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1322 DWORD StringSDRevision,
1323 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1324 PULONG SecurityDescriptorSize)
1326 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1327 BOOL retval;
1329 if (is_windows_9x () == TRUE)
1331 errno = ENOTSUP;
1332 return FALSE;
1335 if (g_b_init_convert_sddl_to_sd == 0)
1337 g_b_init_convert_sddl_to_sd = 1;
1338 #ifdef _UNICODE
1339 s_pfn_Convert_SDDL_To_SD =
1340 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1341 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1342 #else
1343 s_pfn_Convert_SDDL_To_SD =
1344 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1345 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1346 #endif
1348 if (s_pfn_Convert_SDDL_To_SD == NULL)
1350 errno = ENOTSUP;
1351 return FALSE;
1354 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1355 StringSDRevision,
1356 SecurityDescriptor,
1357 SecurityDescriptorSize);
1359 return retval;
1362 static DWORD WINAPI
1363 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1365 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1366 HMODULE hm_iphlpapi = NULL;
1368 if (is_windows_9x () == TRUE)
1369 return ERROR_NOT_SUPPORTED;
1371 if (g_b_init_get_adapters_info == 0)
1373 g_b_init_get_adapters_info = 1;
1374 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1375 if (hm_iphlpapi)
1376 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1377 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1379 if (s_pfn_Get_Adapters_Info == NULL)
1380 return ERROR_NOT_SUPPORTED;
1381 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1386 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1387 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1389 This is called from alloc.c:valid_pointer_p. */
1391 w32_valid_pointer_p (void *p, int size)
1393 SIZE_T done;
1394 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1396 if (h)
1398 unsigned char *buf = alloca (size);
1399 int retval = ReadProcessMemory (h, p, buf, size, &done);
1401 CloseHandle (h);
1402 return retval;
1404 else
1405 return -1;
1410 /* Here's an overview of how the Windows build supports file names
1411 that cannot be encoded by the current system codepage.
1413 From the POV of Lisp and layers of C code above the functions here,
1414 Emacs on Windows pretends that its file names are encoded in UTF-8;
1415 see encode_file and decode_file on coding.c. Any file name that is
1416 passed as a unibyte string to C functions defined here is assumed
1417 to be in UTF-8 encoding. Any file name returned by functions
1418 defined here must be in UTF-8 encoding, with only a few exceptions
1419 reserved for a couple of special cases. (Be sure to use
1420 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1421 as they can be much longer than MAX_PATH!)
1423 The UTF-8 encoded file names cannot be passed to system APIs, as
1424 Windows does not support that. Therefore, they are converted
1425 either to UTF-16 or to the ANSI codepage, depending on the value of
1426 w32-unicode-filenames, before calling any system APIs or CRT library
1427 functions. The default value of that variable is determined by the
1428 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1429 user can change that default (although I don't see why would she
1430 want to).
1432 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1433 filename_from_utf16, and filename_from_ansi, are the workhorses of
1434 these conversions. They rely on Windows native APIs
1435 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1436 functions from coding.c here, because they allocate memory, which
1437 is a bad idea on the level of libc, which is what the functions
1438 here emulate. (If you worry about performance due to constant
1439 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1440 it was measured to take only a few microseconds on a not-so-fast
1441 machine, and second, that's exactly what the ANSI APIs we used
1442 before did anyway, because they are just thin wrappers around the
1443 Unicode APIs.)
1445 The variables file-name-coding-system and default-file-name-coding-system
1446 still exist, but are actually used only when a file name needs to
1447 be converted to the ANSI codepage. This happens all the time when
1448 w32-unicode-filenames is nil, but can also happen from time to time
1449 when it is t. Otherwise, these variables have no effect on file-name
1450 encoding when w32-unicode-filenames is t; this is similar to
1451 selection-coding-system.
1453 This arrangement works very well, but it has a few gotchas and
1454 limitations:
1456 . Lisp code that encodes or decodes file names manually should
1457 normally use 'utf-8' as the coding-system on Windows,
1458 disregarding file-name-coding-system. This is a somewhat
1459 unpleasant consequence, but it cannot be avoided. Fortunately,
1460 very few Lisp packages need to do that.
1462 More generally, passing to library functions (e.g., fopen or
1463 opendir) file names already encoded in the ANSI codepage is
1464 explicitly *verboten*, as all those functions, as shadowed and
1465 emulated here, assume they will receive UTF-8 encoded file names.
1467 For the same reasons, no CRT function or Win32 API can be called
1468 directly in Emacs sources, without either converting the file
1469 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1470 some shadowing function defined here.
1472 . Environment variables stored in Vprocess_environment are encoded
1473 in the ANSI codepage, so if getenv/egetenv is used for a variable
1474 whose value is a file name or a list of directories, it needs to
1475 be converted to UTF-8, before it is used as argument to functions
1476 or decoded into a Lisp string.
1478 . File names passed to external libraries, like the image libraries
1479 and GnuTLS, need special handling. These libraries generally
1480 don't support UTF-16 or UTF-8 file names, so they must get file
1481 names encoded in the ANSI codepage. To facilitate using these
1482 libraries with file names that are not encodable in the ANSI
1483 codepage, use the function ansi_encode_filename, which will try
1484 to use the short 8+3 alias of a file name if that file name is
1485 not encodable in the ANSI codepage. See image.c and gnutls.c for
1486 examples of how this should be done.
1488 . Running subprocesses in non-ASCII directories and with non-ASCII
1489 file arguments is limited to the current codepage (even though
1490 Emacs is perfectly capable of finding an executable program file
1491 in a directory whose name cannot be encoded in the current
1492 codepage). This is because the command-line arguments are
1493 encoded _before_ they get to the w32-specific level, and the
1494 encoding is not known in advance (it doesn't have to be the
1495 current ANSI codepage), so w32proc.c functions cannot re-encode
1496 them in UTF-16. This should be fixed, but will also require
1497 changes in cmdproxy. The current limitation is not terribly bad
1498 anyway, since very few, if any, Windows console programs that are
1499 likely to be invoked by Emacs support UTF-16 encoded command
1500 lines.
1502 . For similar reasons, server.el and emacsclient are also limited
1503 to the current ANSI codepage for now.
1505 . Emacs itself can only handle command-line arguments encoded in
1506 the current codepage.
1508 . Turning on w32-unicode-filename on Windows 9X (if it at all
1509 works) requires UNICOWS.DLL, which is thus a requirement even in
1510 non-GUI sessions, something the we previously avoided. */
1514 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1515 codepage defined by file-name-coding-system. */
1517 /* Current codepage for encoding file names. */
1518 static int file_name_codepage;
1520 /* Produce a Windows ANSI codepage suitable for encoding file names.
1521 Return the information about that codepage in CP_INFO. */
1523 codepage_for_filenames (CPINFO *cp_info)
1525 /* A simple cache to avoid calling GetCPInfo every time we need to
1526 encode/decode a file name. The file-name encoding is not
1527 supposed to be changed too frequently, if ever. */
1528 static Lisp_Object last_file_name_encoding;
1529 static CPINFO cp;
1530 Lisp_Object current_encoding;
1532 current_encoding = Vfile_name_coding_system;
1533 if (NILP (current_encoding))
1534 current_encoding = Vdefault_file_name_coding_system;
1536 if (!EQ (last_file_name_encoding, current_encoding))
1538 /* Default to the current ANSI codepage. */
1539 file_name_codepage = w32_ansi_code_page;
1541 if (NILP (current_encoding))
1543 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1544 char *cp = NULL, *end;
1545 int cpnum;
1547 if (strncmp (cpname, "cp", 2) == 0)
1548 cp = cpname + 2;
1549 else if (strncmp (cpname, "windows-", 8) == 0)
1550 cp = cpname + 8;
1552 if (cp)
1554 end = cp;
1555 cpnum = strtol (cp, &end, 10);
1556 if (cpnum && *end == '\0' && end - cp >= 2)
1557 file_name_codepage = cpnum;
1561 if (!file_name_codepage)
1562 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1564 if (!GetCPInfo (file_name_codepage, &cp))
1566 file_name_codepage = CP_ACP;
1567 if (!GetCPInfo (file_name_codepage, &cp))
1568 emacs_abort ();
1571 if (cp_info)
1572 *cp_info = cp;
1574 return file_name_codepage;
1578 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1580 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1581 -1, fn_out, MAX_PATH);
1583 if (!result)
1585 DWORD err = GetLastError ();
1587 switch (err)
1589 case ERROR_INVALID_FLAGS:
1590 case ERROR_INVALID_PARAMETER:
1591 errno = EINVAL;
1592 break;
1593 case ERROR_INSUFFICIENT_BUFFER:
1594 case ERROR_NO_UNICODE_TRANSLATION:
1595 default:
1596 errno = ENOENT;
1597 break;
1599 return -1;
1601 return 0;
1605 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1607 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1608 fn_out, MAX_UTF8_PATH, NULL, NULL);
1610 if (!result)
1612 DWORD err = GetLastError ();
1614 switch (err)
1616 case ERROR_INVALID_FLAGS:
1617 case ERROR_INVALID_PARAMETER:
1618 errno = EINVAL;
1619 break;
1620 case ERROR_INSUFFICIENT_BUFFER:
1621 case ERROR_NO_UNICODE_TRANSLATION:
1622 default:
1623 errno = ENOENT;
1624 break;
1626 return -1;
1628 return 0;
1632 filename_to_ansi (const char *fn_in, char *fn_out)
1634 wchar_t fn_utf16[MAX_PATH];
1636 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1638 int result;
1639 int codepage = codepage_for_filenames (NULL);
1641 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1642 fn_out, MAX_PATH, NULL, NULL);
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 0;
1663 return -1;
1667 filename_from_ansi (const char *fn_in, char *fn_out)
1669 wchar_t fn_utf16[MAX_PATH];
1670 int codepage = codepage_for_filenames (NULL);
1671 int result = pMultiByteToWideChar (codepage, multiByteToWideCharFlags, fn_in,
1672 -1, fn_utf16, MAX_PATH);
1674 if (!result)
1676 DWORD err = GetLastError ();
1678 switch (err)
1680 case ERROR_INVALID_FLAGS:
1681 case ERROR_INVALID_PARAMETER:
1682 errno = EINVAL;
1683 break;
1684 case ERROR_INSUFFICIENT_BUFFER:
1685 case ERROR_NO_UNICODE_TRANSLATION:
1686 default:
1687 errno = ENOENT;
1688 break;
1690 return -1;
1692 return filename_from_utf16 (fn_utf16, fn_out);
1697 /* The directory where we started, in UTF-8. */
1698 static char startup_dir[MAX_UTF8_PATH];
1700 /* Get the current working directory. */
1701 char *
1702 getcwd (char *dir, int dirsize)
1704 if (!dirsize)
1706 errno = EINVAL;
1707 return NULL;
1709 if (dirsize <= strlen (startup_dir))
1711 errno = ERANGE;
1712 return NULL;
1714 #if 0
1715 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1716 return dir;
1717 return NULL;
1718 #else
1719 /* Emacs doesn't actually change directory itself, it stays in the
1720 same directory where it was started. */
1721 strcpy (dir, startup_dir);
1722 return dir;
1723 #endif
1726 /* Emulate getloadavg. */
1728 struct load_sample {
1729 time_t sample_time;
1730 ULONGLONG idle;
1731 ULONGLONG kernel;
1732 ULONGLONG user;
1735 /* Number of processors on this machine. */
1736 static unsigned num_of_processors;
1738 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1739 static struct load_sample samples[16*60];
1740 static int first_idx = -1, last_idx = -1;
1741 static int max_idx = ARRAYELTS (samples);
1743 static int
1744 buf_next (int from)
1746 int next_idx = from + 1;
1748 if (next_idx >= max_idx)
1749 next_idx = 0;
1751 return next_idx;
1754 static int
1755 buf_prev (int from)
1757 int prev_idx = from - 1;
1759 if (prev_idx < 0)
1760 prev_idx = max_idx - 1;
1762 return prev_idx;
1765 static void
1766 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1768 SYSTEM_INFO sysinfo;
1769 FILETIME ft_idle, ft_user, ft_kernel;
1771 /* Initialize the number of processors on this machine. */
1772 if (num_of_processors <= 0)
1774 get_native_system_info (&sysinfo);
1775 num_of_processors = sysinfo.dwNumberOfProcessors;
1776 if (num_of_processors <= 0)
1778 GetSystemInfo (&sysinfo);
1779 num_of_processors = sysinfo.dwNumberOfProcessors;
1781 if (num_of_processors <= 0)
1782 num_of_processors = 1;
1785 /* TODO: Take into account threads that are ready to run, by
1786 sampling the "\System\Processor Queue Length" performance
1787 counter. The code below accounts only for threads that are
1788 actually running. */
1790 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1792 ULARGE_INTEGER uidle, ukernel, uuser;
1794 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1795 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1796 memcpy (&uuser, &ft_user, sizeof (ft_user));
1797 *idle = uidle.QuadPart;
1798 *kernel = ukernel.QuadPart;
1799 *user = uuser.QuadPart;
1801 else
1803 *idle = 0;
1804 *kernel = 0;
1805 *user = 0;
1809 /* Produce the load average for a given time interval, using the
1810 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1811 1-minute, 5-minute, or 15-minute average, respectively. */
1812 static double
1813 getavg (int which)
1815 double retval = -1.0;
1816 double tdiff;
1817 int idx;
1818 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1819 time_t now = samples[last_idx].sample_time;
1821 if (first_idx != last_idx)
1823 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1825 tdiff = difftime (now, samples[idx].sample_time);
1826 if (tdiff >= span - 2*DBL_EPSILON*now)
1828 long double sys =
1829 samples[last_idx].kernel + samples[last_idx].user
1830 - (samples[idx].kernel + samples[idx].user);
1831 long double idl = samples[last_idx].idle - samples[idx].idle;
1833 retval = (1.0 - idl / sys) * num_of_processors;
1834 break;
1836 if (idx == first_idx)
1837 break;
1841 return retval;
1845 getloadavg (double loadavg[], int nelem)
1847 int elem;
1848 ULONGLONG idle, kernel, user;
1849 time_t now = time (NULL);
1851 /* If system time jumped back for some reason, delete all samples
1852 whose time is later than the current wall-clock time. This
1853 prevents load average figures from becoming frozen for prolonged
1854 periods of time, when system time is reset backwards. */
1855 if (last_idx >= 0)
1857 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1859 if (last_idx == first_idx)
1861 first_idx = last_idx = -1;
1862 break;
1864 last_idx = buf_prev (last_idx);
1868 /* Store another sample. We ignore samples that are less than 1 sec
1869 apart. */
1870 if (last_idx < 0
1871 || (difftime (now, samples[last_idx].sample_time)
1872 >= 1.0 - 2*DBL_EPSILON*now))
1874 sample_system_load (&idle, &kernel, &user);
1875 last_idx = buf_next (last_idx);
1876 samples[last_idx].sample_time = now;
1877 samples[last_idx].idle = idle;
1878 samples[last_idx].kernel = kernel;
1879 samples[last_idx].user = user;
1880 /* If the buffer has more that 15 min worth of samples, discard
1881 the old ones. */
1882 if (first_idx == -1)
1883 first_idx = last_idx;
1884 while (first_idx != last_idx
1885 && (difftime (now, samples[first_idx].sample_time)
1886 >= 15.0*60 + 2*DBL_EPSILON*now))
1887 first_idx = buf_next (first_idx);
1890 for (elem = 0; elem < nelem; elem++)
1892 double avg = getavg (elem);
1894 if (avg < 0)
1895 break;
1896 loadavg[elem] = avg;
1899 return elem;
1902 /* Emulate getpwuid, getpwnam and others. */
1904 #define PASSWD_FIELD_SIZE 256
1906 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1907 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1908 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1909 static char dflt_passwd_dir[MAX_UTF8_PATH];
1910 static char dflt_passwd_shell[MAX_UTF8_PATH];
1912 static struct passwd dflt_passwd =
1914 dflt_passwd_name,
1915 dflt_passwd_passwd,
1919 dflt_passwd_gecos,
1920 dflt_passwd_dir,
1921 dflt_passwd_shell,
1924 static char dflt_group_name[GNLEN+1];
1926 static struct group dflt_group =
1928 /* When group information is not available, we return this as the
1929 group for all files. */
1930 dflt_group_name,
1934 unsigned
1935 getuid (void)
1937 return dflt_passwd.pw_uid;
1940 unsigned
1941 geteuid (void)
1943 /* I could imagine arguing for checking to see whether the user is
1944 in the Administrators group and returning a UID of 0 for that
1945 case, but I don't know how wise that would be in the long run. */
1946 return getuid ();
1949 unsigned
1950 getgid (void)
1952 return dflt_passwd.pw_gid;
1955 unsigned
1956 getegid (void)
1958 return getgid ();
1961 struct passwd *
1962 getpwuid (unsigned uid)
1964 if (uid == dflt_passwd.pw_uid)
1965 return &dflt_passwd;
1966 return NULL;
1969 struct group *
1970 getgrgid (gid_t gid)
1972 return &dflt_group;
1975 struct passwd *
1976 getpwnam (char *name)
1978 struct passwd *pw;
1980 pw = getpwuid (getuid ());
1981 if (!pw)
1982 return pw;
1984 if (xstrcasecmp (name, pw->pw_name))
1985 return NULL;
1987 return pw;
1990 static void
1991 init_user_info (void)
1993 /* Find the user's real name by opening the process token and
1994 looking up the name associated with the user-sid in that token.
1996 Use the relative portion of the identifier authority value from
1997 the user-sid as the user id value (same for group id using the
1998 primary group sid from the process token). */
2000 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
2001 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
2002 DWORD glength = sizeof (gname);
2003 HANDLE token = NULL;
2004 SID_NAME_USE user_type;
2005 unsigned char *buf = NULL;
2006 DWORD blen = 0;
2007 TOKEN_USER user_token;
2008 TOKEN_PRIMARY_GROUP group_token;
2009 BOOL result;
2011 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
2012 if (result)
2014 result = get_token_information (token, TokenUser, NULL, 0, &blen);
2015 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2017 buf = xmalloc (blen);
2018 result = get_token_information (token, TokenUser,
2019 (LPVOID)buf, blen, &needed);
2020 if (result)
2022 memcpy (&user_token, buf, sizeof (user_token));
2023 result = lookup_account_sid (NULL, user_token.User.Sid,
2024 uname, &ulength,
2025 domain, &dlength, &user_type);
2028 else
2029 result = FALSE;
2031 if (result)
2033 strcpy (dflt_passwd.pw_name, uname);
2034 /* Determine a reasonable uid value. */
2035 if (xstrcasecmp ("administrator", uname) == 0)
2037 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2038 dflt_passwd.pw_gid = 513; /* well-known None gid */
2040 else
2042 /* Use the last sub-authority value of the RID, the relative
2043 portion of the SID, as user/group ID. */
2044 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2046 /* Get group id and name. */
2047 result = get_token_information (token, TokenPrimaryGroup,
2048 (LPVOID)buf, blen, &needed);
2049 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2051 buf = xrealloc (buf, blen = needed);
2052 result = get_token_information (token, TokenPrimaryGroup,
2053 (LPVOID)buf, blen, &needed);
2055 if (result)
2057 memcpy (&group_token, buf, sizeof (group_token));
2058 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2059 dlength = sizeof (domain);
2060 /* If we can get at the real Primary Group name, use that.
2061 Otherwise, the default group name was already set to
2062 "None" in globals_of_w32. */
2063 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2064 gname, &glength, NULL, &dlength,
2065 &user_type))
2066 strcpy (dflt_group_name, gname);
2068 else
2069 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2072 /* If security calls are not supported (presumably because we
2073 are running under Windows 9X), fallback to this: */
2074 else if (GetUserName (uname, &ulength))
2076 strcpy (dflt_passwd.pw_name, uname);
2077 if (xstrcasecmp ("administrator", uname) == 0)
2078 dflt_passwd.pw_uid = 0;
2079 else
2080 dflt_passwd.pw_uid = 123;
2081 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2083 else
2085 strcpy (dflt_passwd.pw_name, "unknown");
2086 dflt_passwd.pw_uid = 123;
2087 dflt_passwd.pw_gid = 123;
2089 dflt_group.gr_gid = dflt_passwd.pw_gid;
2091 /* Set dir and shell from environment variables. */
2092 if (w32_unicode_filenames)
2094 wchar_t *home = _wgetenv (L"HOME");
2095 wchar_t *shell = _wgetenv (L"SHELL");
2097 /* Ensure HOME and SHELL are defined. */
2098 if (home == NULL)
2099 emacs_abort ();
2100 if (shell == NULL)
2101 emacs_abort ();
2102 filename_from_utf16 (home, dflt_passwd.pw_dir);
2103 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2105 else
2107 char *home = getenv ("HOME");
2108 char *shell = getenv ("SHELL");
2110 if (home == NULL)
2111 emacs_abort ();
2112 if (shell == NULL)
2113 emacs_abort ();
2114 filename_from_ansi (home, dflt_passwd.pw_dir);
2115 filename_from_ansi (shell, dflt_passwd.pw_shell);
2118 xfree (buf);
2119 if (token)
2120 CloseHandle (token);
2123 static HCRYPTPROV w32_crypto_hprov;
2124 static int
2125 w32_init_crypt_random (void)
2127 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2128 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2130 DebPrint (("CryptAcquireContext failed with error %x\n",
2131 GetLastError ()));
2132 w32_crypto_hprov = 0;
2133 return -1;
2135 return 0;
2139 w32_init_random (void *buf, ptrdiff_t buflen)
2141 if (!w32_crypto_hprov)
2142 w32_init_crypt_random ();
2143 if (w32_crypto_hprov)
2145 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2146 return 0;
2148 return -1;
2152 random (void)
2154 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2155 return ((rand () << 15) | rand ());
2158 void
2159 srandom (int seed)
2161 srand (seed);
2164 /* Return the maximum length in bytes of a multibyte character
2165 sequence encoded in the current ANSI codepage. This is required to
2166 correctly walk the encoded file names one character at a time. */
2167 static int
2168 max_filename_mbslen (void)
2170 CPINFO cp_info;
2172 codepage_for_filenames (&cp_info);
2173 return cp_info.MaxCharSize;
2176 /* Normalize filename by converting in-place all of its path
2177 separators to the separator specified by PATH_SEP. */
2179 static void
2180 normalize_filename (register char *fp, char path_sep)
2182 char *p2;
2184 /* Always lower-case drive letters a-z, even if the filesystem
2185 preserves case in filenames.
2186 This is so filenames can be compared by string comparison
2187 functions that are case-sensitive. Even case-preserving filesystems
2188 do not distinguish case in drive letters. */
2189 p2 = fp + 1;
2191 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2193 *fp += 'a' - 'A';
2194 fp += 2;
2197 while (*fp)
2199 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2200 *fp = path_sep;
2201 fp++;
2205 /* Destructively turn backslashes into slashes. */
2206 void
2207 dostounix_filename (register char *p)
2209 normalize_filename (p, '/');
2212 /* Destructively turn slashes into backslashes. */
2213 void
2214 unixtodos_filename (register char *p)
2216 normalize_filename (p, '\\');
2219 /* Remove all CR's that are followed by a LF.
2220 (From msdos.c...probably should figure out a way to share it,
2221 although this code isn't going to ever change.) */
2222 static int
2223 crlf_to_lf (register int n, register char *buf)
2225 unsigned char *np = (unsigned char *)buf;
2226 unsigned char *startp = np;
2227 char *endp = buf + n;
2229 if (n == 0)
2230 return n;
2231 while (buf < endp - 1)
2233 if (*buf == 0x0d)
2235 if (*(++buf) != 0x0a)
2236 *np++ = 0x0d;
2238 else
2239 *np++ = *buf++;
2241 if (buf < endp)
2242 *np++ = *buf++;
2243 return np - startp;
2246 /* Parse the root part of file name, if present. Return length and
2247 optionally store pointer to char after root. */
2248 static int
2249 parse_root (const char * name, const char ** pPath)
2251 const char * start = name;
2253 if (name == NULL)
2254 return 0;
2256 /* find the root name of the volume if given */
2257 if (isalpha (name[0]) && name[1] == ':')
2259 /* skip past drive specifier */
2260 name += 2;
2261 if (IS_DIRECTORY_SEP (name[0]))
2262 name++;
2264 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2266 int slashes = 2;
2268 name += 2;
2271 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2272 break;
2273 name++;
2275 while ( *name );
2276 if (IS_DIRECTORY_SEP (name[0]))
2277 name++;
2280 if (pPath)
2281 *pPath = name;
2283 return name - start;
2286 /* Get long base name for name; name is assumed to be absolute. */
2287 static int
2288 get_long_basename (char * name, char * buf, int size)
2290 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2291 char fname_utf8[MAX_UTF8_PATH];
2292 int len = 0;
2293 int cstatus = -1;
2295 /* Must be valid filename, no wild cards or other invalid characters. */
2296 if (strpbrk (name, "*?|<>\""))
2297 return 0;
2299 if (w32_unicode_filenames)
2301 wchar_t fname_utf16[MAX_PATH];
2302 WIN32_FIND_DATAW find_data_wide;
2304 filename_to_utf16 (name, fname_utf16);
2305 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2306 if (dir_handle != INVALID_HANDLE_VALUE)
2307 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2309 else
2311 char fname_ansi[MAX_PATH];
2312 WIN32_FIND_DATAA find_data_ansi;
2314 filename_to_ansi (name, fname_ansi);
2315 /* If the ANSI name includes ? characters, it is not encodable
2316 in the ANSI codepage. In that case, we deliver the question
2317 marks to the caller; calling FindFirstFileA in this case
2318 could return some unrelated file name in the same
2319 directory. */
2320 if (_mbspbrk (fname_ansi, "?"))
2322 /* Find the basename of fname_ansi. */
2323 char *p = strrchr (fname_ansi, '\\');
2325 if (!p)
2326 p = fname_ansi;
2327 else
2328 p++;
2329 cstatus = filename_from_ansi (p, fname_utf8);
2331 else
2333 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2334 if (dir_handle != INVALID_HANDLE_VALUE)
2335 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2339 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2340 memcpy (buf, fname_utf8, len + 1);
2341 else
2342 len = 0;
2344 if (dir_handle != INVALID_HANDLE_VALUE)
2345 FindClose (dir_handle);
2347 return len;
2350 /* Get long name for file, if possible (assumed to be absolute). */
2351 BOOL
2352 w32_get_long_filename (const char * name, char * buf, int size)
2354 char * o = buf;
2355 char * p;
2356 const char * q;
2357 char full[ MAX_UTF8_PATH ];
2358 int len;
2360 len = strlen (name);
2361 if (len >= MAX_UTF8_PATH)
2362 return FALSE;
2364 /* Use local copy for destructive modification. */
2365 memcpy (full, name, len+1);
2366 unixtodos_filename (full);
2368 /* Copy root part verbatim. */
2369 len = parse_root (full, (const char **)&p);
2370 memcpy (o, full, len);
2371 o += len;
2372 *o = '\0';
2373 size -= len;
2375 while (p != NULL && *p)
2377 q = p;
2378 p = strchr (q, '\\');
2379 if (p) *p = '\0';
2380 len = get_long_basename (full, o, size);
2381 if (len > 0)
2383 o += len;
2384 size -= len;
2385 if (p != NULL)
2387 *p++ = '\\';
2388 if (size < 2)
2389 return FALSE;
2390 *o++ = '\\';
2391 size--;
2392 *o = '\0';
2395 else
2396 return FALSE;
2399 return TRUE;
2402 unsigned int
2403 w32_get_short_filename (const char * name, char * buf, int size)
2405 if (w32_unicode_filenames)
2407 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2408 unsigned int retval;
2410 filename_to_utf16 (name, name_utf16);
2411 retval = GetShortPathNameW (name_utf16, short_name, size);
2412 if (retval && retval < size)
2413 filename_from_utf16 (short_name, buf);
2414 return retval;
2416 else
2418 char name_ansi[MAX_PATH];
2420 filename_to_ansi (name, name_ansi);
2421 return GetShortPathNameA (name_ansi, buf, size);
2425 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2426 MS-Windows ANSI codepage. If FILENAME includes characters not
2427 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2428 if it exists. This is needed because the w32 build wants to
2429 support file names outside of the system locale, but image
2430 libraries typically don't support wide (a.k.a. "Unicode") APIs
2431 required for that. */
2433 Lisp_Object
2434 ansi_encode_filename (Lisp_Object filename)
2436 Lisp_Object encoded_filename;
2437 char fname[MAX_PATH];
2439 filename_to_ansi (SSDATA (filename), fname);
2440 if (_mbspbrk (fname, "?"))
2442 char shortname[MAX_PATH];
2444 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2446 dostounix_filename (shortname);
2447 encoded_filename = build_string (shortname);
2449 else
2450 encoded_filename = build_unibyte_string (fname);
2452 else
2453 encoded_filename = build_unibyte_string (fname);
2454 return encoded_filename;
2457 static int
2458 is_unc_volume (const char *filename)
2460 const char *ptr = filename;
2462 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2463 return 0;
2465 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2466 return 0;
2468 return 1;
2471 /* Emulate the Posix unsetenv. */
2473 unsetenv (const char *name)
2475 char *var;
2476 size_t name_len;
2478 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2480 errno = EINVAL;
2481 return -1;
2483 name_len = strlen (name);
2484 /* MS docs says an environment variable cannot be longer than 32K. */
2485 if (name_len > 32767)
2487 errno = ENOMEM;
2488 return 0;
2490 /* It is safe to use 'alloca' with 32K size, since the stack is at
2491 least 2MB, and we set it to 8MB in the link command line. */
2492 var = alloca (name_len + 2);
2493 strncpy (var, name, name_len);
2494 var[name_len++] = '=';
2495 var[name_len] = '\0';
2496 return _putenv (var);
2499 /* MS _putenv doesn't support removing a variable when the argument
2500 does not include the '=' character, so we fix that here. */
2502 sys_putenv (char *str)
2504 const char *const name_end = strchr (str, '=');
2506 if (name_end == NULL)
2508 /* Remove the variable from the environment. */
2509 return unsetenv (str);
2512 if (strncmp (str, "TZ=<", 4) == 0)
2514 /* MS-Windows does not support POSIX.1-2001 angle-bracket TZ
2515 abbreviation syntax. Convert to POSIX.1-1988 syntax if possible,
2516 and to the undocumented placeholder "ZZZ" otherwise. */
2517 bool supported_abbr = true;
2518 for (char *p = str + 4; *p; p++)
2520 if (('0' <= *p && *p <= '9') || *p == '-' || *p == '+')
2521 supported_abbr = false;
2522 else if (*p == '>')
2524 ptrdiff_t abbrlen;
2525 if (supported_abbr)
2527 abbrlen = p - (str + 4);
2528 memmove (str + 3, str + 4, abbrlen);
2530 else
2532 abbrlen = 3;
2533 memset (str + 3, 'Z', abbrlen);
2535 memmove (str + 3 + abbrlen, p + 1, strlen (p));
2536 break;
2541 return _putenv (str);
2544 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2546 LPBYTE
2547 w32_get_resource (const char *key, LPDWORD lpdwtype)
2549 LPBYTE lpvalue;
2550 HKEY hrootkey = NULL;
2551 DWORD cbData;
2553 /* Check both the current user and the local machine to see if
2554 we have any resources. */
2556 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2558 lpvalue = NULL;
2560 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2561 && (lpvalue = xmalloc (cbData)) != NULL
2562 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2564 RegCloseKey (hrootkey);
2565 return (lpvalue);
2568 xfree (lpvalue);
2570 RegCloseKey (hrootkey);
2573 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2575 lpvalue = NULL;
2577 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2578 && (lpvalue = xmalloc (cbData)) != NULL
2579 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2581 RegCloseKey (hrootkey);
2582 return (lpvalue);
2585 xfree (lpvalue);
2587 RegCloseKey (hrootkey);
2590 return (NULL);
2593 /* The argv[] array holds ANSI-encoded strings, and so this function
2594 works with ANS_encoded strings. */
2595 void
2596 init_environment (char ** argv)
2598 static const char * const tempdirs[] = {
2599 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2602 int i;
2604 const int imax = ARRAYELTS (tempdirs);
2606 /* Implementation note: This function explicitly works with ANSI
2607 file names, not with UTF-8 encoded file names. This is because
2608 this function pushes variables into the Emacs's environment, and
2609 the environment variables are always assumed to be in the
2610 locale-specific encoding. Do NOT call any functions that accept
2611 UTF-8 file names from this function! */
2613 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2614 temporary files and assume "/tmp" if $TMPDIR is unset, which
2615 will break on DOS/Windows. Refuse to work if we cannot find
2616 a directory, not even "c:/", usable for that purpose. */
2617 for (i = 0; i < imax ; i++)
2619 const char *tmp = tempdirs[i];
2621 if (*tmp == '$')
2622 tmp = getenv (tmp + 1);
2623 /* Note that `access' can lie to us if the directory resides on a
2624 read-only filesystem, like CD-ROM or a write-protected floppy.
2625 The only way to be really sure is to actually create a file and
2626 see if it succeeds. But I think that's too much to ask. */
2628 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2629 if (tmp && sys_access (tmp, D_OK) == 0)
2631 char * var = alloca (strlen (tmp) + 8);
2632 sprintf (var, "TMPDIR=%s", tmp);
2633 _putenv (strdup (var));
2634 break;
2637 if (i >= imax)
2638 cmd_error_internal
2639 (Fcons (Qerror,
2640 Fcons (build_string ("no usable temporary directories found!!"),
2641 Qnil)),
2642 "While setting TMPDIR: ");
2644 /* Check for environment variables and use registry settings if they
2645 don't exist. Fallback on default values where applicable. */
2647 int i;
2648 LPBYTE lpval;
2649 DWORD dwType;
2650 char locale_name[32];
2651 char default_home[MAX_PATH];
2652 int appdata = 0;
2654 static const struct env_entry
2656 const char * name;
2657 const char * def_value;
2658 } dflt_envvars[] =
2660 /* If the default value is NULL, we will use the value from the
2661 outside environment or the Registry, but will not push the
2662 variable into the Emacs environment if it is defined neither
2663 in the Registry nor in the outside environment. */
2664 {"HOME", "C:/"},
2665 {"PRELOAD_WINSOCK", NULL},
2666 {"emacs_dir", "C:/emacs"},
2667 {"EMACSLOADPATH", NULL},
2668 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2669 {"EMACSDATA", NULL},
2670 {"EMACSPATH", NULL},
2671 {"INFOPATH", NULL},
2672 {"EMACSDOC", NULL},
2673 {"TERM", "cmd"},
2674 {"LANG", NULL},
2677 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2679 /* We need to copy dflt_envvars[] and work on the copy because we
2680 don't want the dumped Emacs to inherit the values of
2681 environment variables we saw during dumping (which could be on
2682 a different system). The defaults above must be left intact. */
2683 struct env_entry env_vars[N_ENV_VARS];
2685 for (i = 0; i < N_ENV_VARS; i++)
2686 env_vars[i] = dflt_envvars[i];
2688 /* For backwards compatibility, check if a .emacs file exists in C:/
2689 If not, then we can try to default to the appdata directory under the
2690 user's profile, which is more likely to be writable. */
2691 if (sys_access ("C:/.emacs", F_OK) != 0)
2693 HRESULT profile_result;
2694 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2695 of Windows 95 and NT4 that have not been updated to include
2696 MSIE 5. */
2697 ShGetFolderPath_fn get_folder_path;
2698 get_folder_path = (ShGetFolderPath_fn)
2699 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2701 if (get_folder_path != NULL)
2703 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2704 0, default_home);
2706 /* If we can't get the appdata dir, revert to old behavior. */
2707 if (profile_result == S_OK)
2709 env_vars[0].def_value = default_home;
2710 appdata = 1;
2715 /* Get default locale info and use it for LANG. */
2716 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2717 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2718 locale_name, sizeof (locale_name)))
2720 for (i = 0; i < N_ENV_VARS; i++)
2722 if (strcmp (env_vars[i].name, "LANG") == 0)
2724 env_vars[i].def_value = locale_name;
2725 break;
2730 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2732 /* Treat emacs_dir specially: set it unconditionally based on our
2733 location. */
2735 char *p;
2736 char modname[MAX_PATH];
2738 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2739 emacs_abort ();
2740 if ((p = _mbsrchr (modname, '\\')) == NULL)
2741 emacs_abort ();
2742 *p = 0;
2744 if ((p = _mbsrchr (modname, '\\'))
2745 /* From bin means installed Emacs, from src means uninstalled. */
2746 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2748 char buf[SET_ENV_BUF_SIZE];
2749 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2751 *p = 0;
2752 for (p = modname; *p; p = CharNext (p))
2753 if (*p == '\\') *p = '/';
2755 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2756 _putenv (strdup (buf));
2757 /* If we are running from the Posix-like build tree, define
2758 SHELL to point to our own cmdproxy. The loop below will
2759 then disregard PATH_EXEC and the default value. */
2760 if (within_build_tree)
2762 _snprintf (buf, sizeof (buf) - 1,
2763 "SHELL=%s/nt/cmdproxy.exe", modname);
2764 _putenv (strdup (buf));
2769 for (i = 0; i < N_ENV_VARS; i++)
2771 if (!getenv (env_vars[i].name))
2773 int dont_free = 0;
2774 char bufc[SET_ENV_BUF_SIZE];
2776 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2777 /* Also ignore empty environment variables. */
2778 || *lpval == 0)
2780 xfree (lpval);
2781 dont_free = 1;
2782 if (strcmp (env_vars[i].name, "SHELL") == 0)
2784 /* Look for cmdproxy.exe in every directory in
2785 PATH_EXEC. FIXME: This does not find cmdproxy
2786 in nt/ when we run uninstalled. */
2787 char fname[MAX_PATH];
2788 const char *pstart = PATH_EXEC, *pend;
2790 do {
2791 pend = _mbschr (pstart, ';');
2792 if (!pend)
2793 pend = pstart + strlen (pstart);
2794 /* Be defensive against series of ;;; characters. */
2795 if (pend > pstart)
2797 strncpy (fname, pstart, pend - pstart);
2798 fname[pend - pstart] = '/';
2799 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2800 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2801 sizeof (bufc));
2802 if (sys_access (bufc, F_OK) == 0)
2804 lpval = bufc;
2805 dwType = REG_SZ;
2806 break;
2809 if (*pend)
2810 pstart = pend + 1;
2811 else
2812 pstart = pend;
2813 if (!*pstart)
2815 /* If not found in any directory, use the
2816 default as the last resort. */
2817 lpval = (char *)env_vars[i].def_value;
2818 dwType = REG_EXPAND_SZ;
2820 } while (*pstart);
2822 else
2824 lpval = (char *)env_vars[i].def_value;
2825 dwType = REG_EXPAND_SZ;
2827 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2828 Vdelayed_warnings_list
2829 = Fcons
2830 (listn (CONSTYPE_HEAP, 2,
2831 intern ("initialization"), build_string
2832 ("Use of `C:\\.emacs' without defining `HOME'\n"
2833 "in the environment is deprecated, "
2834 "see `Windows HOME' in the Emacs manual.")),
2835 Vdelayed_warnings_list);
2838 if (lpval)
2840 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2842 if (dwType == REG_EXPAND_SZ)
2843 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2844 else if (dwType == REG_SZ)
2845 strcpy (buf1, (char *)lpval);
2846 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2848 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2849 buf1);
2850 _putenv (strdup (buf2));
2853 if (!dont_free)
2854 xfree (lpval);
2860 /* Rebuild system configuration to reflect invoking system. */
2861 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2863 /* Another special case: on NT, the PATH variable is actually named
2864 "Path" although cmd.exe (perhaps NT itself) arranges for
2865 environment variable lookup and setting to be case insensitive.
2866 However, Emacs assumes a fully case sensitive environment, so we
2867 need to change "Path" to "PATH" to match the expectations of
2868 various elisp packages. We do this by the sneaky method of
2869 modifying the string in the C runtime environ entry.
2871 The same applies to COMSPEC. */
2873 char ** envp;
2875 for (envp = environ; *envp; envp++)
2876 if (_strnicmp (*envp, "PATH=", 5) == 0)
2877 memcpy (*envp, "PATH=", 5);
2878 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2879 memcpy (*envp, "COMSPEC=", 8);
2882 /* Remember the initial working directory for getcwd. */
2883 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2884 Does it matter anywhere in Emacs? */
2885 if (w32_unicode_filenames)
2887 wchar_t wstartup_dir[MAX_PATH];
2889 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2890 emacs_abort ();
2891 filename_from_utf16 (wstartup_dir, startup_dir);
2893 else
2895 char astartup_dir[MAX_PATH];
2897 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2898 emacs_abort ();
2899 filename_from_ansi (astartup_dir, startup_dir);
2903 static char modname[MAX_PATH];
2905 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2906 emacs_abort ();
2907 argv[0] = modname;
2910 /* Determine if there is a middle mouse button, to allow parse_button
2911 to decide whether right mouse events should be mouse-2 or
2912 mouse-3. */
2913 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2915 init_user_info ();
2918 /* Called from expand-file-name when default-directory is not a string. */
2920 char *
2921 emacs_root_dir (void)
2923 static char root_dir[MAX_UTF8_PATH];
2924 const char *p;
2926 p = getenv ("emacs_dir");
2927 if (p == NULL)
2928 emacs_abort ();
2929 filename_from_ansi (p, root_dir);
2930 root_dir[parse_root (root_dir, NULL)] = '\0';
2931 dostounix_filename (root_dir);
2932 return root_dir;
2935 #include <sys/timeb.h>
2937 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2939 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2941 struct _timeb tb;
2942 _ftime (&tb);
2944 tv->tv_sec = tb.time;
2945 tv->tv_usec = tb.millitm * 1000L;
2946 /* Implementation note: _ftime sometimes doesn't update the dstflag
2947 according to the new timezone when the system timezone is
2948 changed. We could fix that by using GetSystemTime and
2949 GetTimeZoneInformation, but that doesn't seem necessary, since
2950 Emacs always calls gettimeofday with the 2nd argument NULL (see
2951 current_emacs_time). */
2952 if (tz)
2954 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2955 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2957 return 0;
2960 /* Emulate fdutimens. */
2962 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2963 TIMESPEC[0] and TIMESPEC[1], respectively.
2964 FD must be either negative -- in which case it is ignored --
2965 or a file descriptor that is open on FILE.
2966 If FD is nonnegative, then FILE can be NULL, which means
2967 use just futimes instead of utimes.
2968 If TIMESPEC is null, FAIL.
2969 Return 0 on success, -1 (setting errno) on failure. */
2972 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2974 if (!timespec)
2976 errno = ENOSYS;
2977 return -1;
2979 if (fd < 0 && !file)
2981 errno = EBADF;
2982 return -1;
2984 /* _futime's prototype defines 2nd arg as having the type 'struct
2985 _utimbuf', while utime needs to accept 'struct utimbuf' for
2986 compatibility with Posix. So we need to use 2 different (but
2987 equivalent) types to avoid compiler warnings, sigh. */
2988 if (fd >= 0)
2990 struct _utimbuf _ut;
2992 _ut.actime = timespec[0].tv_sec;
2993 _ut.modtime = timespec[1].tv_sec;
2994 return _futime (fd, &_ut);
2996 else
2998 struct utimbuf ut;
3000 ut.actime = timespec[0].tv_sec;
3001 ut.modtime = timespec[1].tv_sec;
3002 /* Call 'utime', which is implemented below, not the MS library
3003 function, which fails on directories. */
3004 return utime (file, &ut);
3009 /* ------------------------------------------------------------------------- */
3010 /* IO support and wrapper functions for the Windows API. */
3011 /* ------------------------------------------------------------------------- */
3013 /* Place a wrapper around the MSVC version of ctime. It returns NULL
3014 on network directories, so we handle that case here.
3015 (Ulrich Leodolter, 1/11/95). */
3016 char *
3017 sys_ctime (const time_t *t)
3019 char *str = (char *) ctime (t);
3020 return (str ? str : (char *)"Sun Jan 01 00:00:00 1970");
3023 /* Emulate sleep...we could have done this with a define, but that
3024 would necessitate including windows.h in the files that used it.
3025 This is much easier. */
3026 void
3027 sys_sleep (int seconds)
3029 Sleep (seconds * 1000);
3032 /* Internal MSVC functions for low-level descriptor munging */
3033 extern int __cdecl _set_osfhnd (int fd, long h);
3034 extern int __cdecl _free_osfhnd (int fd);
3036 /* parallel array of private info on file handles */
3037 filedesc fd_info [ MAXDESC ];
3039 typedef struct volume_info_data {
3040 struct volume_info_data * next;
3042 /* time when info was obtained */
3043 DWORD timestamp;
3045 /* actual volume info */
3046 char * root_dir;
3047 DWORD serialnum;
3048 DWORD maxcomp;
3049 DWORD flags;
3050 char * name;
3051 char * type;
3052 } volume_info_data;
3054 /* Global referenced by various functions. */
3055 static volume_info_data volume_info;
3057 /* Vector to indicate which drives are local and fixed (for which cached
3058 data never expires). */
3059 static BOOL fixed_drives[26];
3061 /* Consider cached volume information to be stale if older than 10s,
3062 at least for non-local drives. Info for fixed drives is never stale. */
3063 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3064 #define VOLINFO_STILL_VALID( root_dir, info ) \
3065 ( ( isalpha (root_dir[0]) && \
3066 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3067 || GetTickCount () - info->timestamp < 10000 )
3069 /* Cache support functions. */
3071 /* Simple linked list with linear search is sufficient. */
3072 static volume_info_data *volume_cache = NULL;
3074 static volume_info_data *
3075 lookup_volume_info (char * root_dir)
3077 volume_info_data * info;
3079 for (info = volume_cache; info; info = info->next)
3080 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3081 break;
3082 return info;
3085 static void
3086 add_volume_info (char * root_dir, volume_info_data * info)
3088 info->root_dir = xstrdup (root_dir);
3089 unixtodos_filename (info->root_dir);
3090 info->next = volume_cache;
3091 volume_cache = info;
3095 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3096 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3097 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3098 static volume_info_data *
3099 GetCachedVolumeInformation (char * root_dir)
3101 volume_info_data * info;
3102 char default_root[ MAX_UTF8_PATH ];
3103 char name[MAX_PATH+1];
3104 char type[MAX_PATH+1];
3106 /* NULL for root_dir means use root from current directory. */
3107 if (root_dir == NULL)
3109 if (w32_unicode_filenames)
3111 wchar_t curdirw[MAX_PATH];
3113 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3114 return NULL;
3115 filename_from_utf16 (curdirw, default_root);
3117 else
3119 char curdira[MAX_PATH];
3121 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3122 return NULL;
3123 filename_from_ansi (curdira, default_root);
3125 parse_root (default_root, (const char **)&root_dir);
3126 *root_dir = 0;
3127 root_dir = default_root;
3130 /* Local fixed drives can be cached permanently. Removable drives
3131 cannot be cached permanently, since the volume name and serial
3132 number (if nothing else) can change. Remote drives should be
3133 treated as if they are removable, since there is no sure way to
3134 tell whether they are or not. Also, the UNC association of drive
3135 letters mapped to remote volumes can be changed at any time (even
3136 by other processes) without notice.
3138 As a compromise, so we can benefit from caching info for remote
3139 volumes, we use a simple expiry mechanism to invalidate cache
3140 entries that are more than ten seconds old. */
3142 #if 0
3143 /* No point doing this, because WNetGetConnection is even slower than
3144 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3145 GetDriveType is about the only call of this type which does not
3146 involve network access, and so is extremely quick). */
3148 /* Map drive letter to UNC if remote. */
3149 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3151 char remote_name[ 256 ];
3152 char drive[3] = { root_dir[0], ':' };
3154 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3155 == NO_ERROR)
3156 /* do something */ ;
3158 #endif
3160 info = lookup_volume_info (root_dir);
3162 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3164 DWORD serialnum;
3165 DWORD maxcomp;
3166 DWORD flags;
3168 /* Info is not cached, or is stale. */
3169 if (w32_unicode_filenames)
3171 wchar_t root_w[MAX_PATH];
3172 wchar_t name_w[MAX_PATH+1];
3173 wchar_t type_w[MAX_PATH+1];
3175 filename_to_utf16 (root_dir, root_w);
3176 if (!GetVolumeInformationW (root_w,
3177 name_w, sizeof (name_w),
3178 &serialnum,
3179 &maxcomp,
3180 &flags,
3181 type_w, sizeof (type_w)))
3182 return NULL;
3183 /* Hmm... not really 100% correct, as these 2 are not file
3184 names... */
3185 filename_from_utf16 (name_w, name);
3186 filename_from_utf16 (type_w, type);
3188 else
3190 char root_a[MAX_PATH];
3191 char name_a[MAX_PATH+1];
3192 char type_a[MAX_PATH+1];
3194 filename_to_ansi (root_dir, root_a);
3195 if (!GetVolumeInformationA (root_a,
3196 name_a, sizeof (name_a),
3197 &serialnum,
3198 &maxcomp,
3199 &flags,
3200 type_a, sizeof (type_a)))
3201 return NULL;
3202 filename_from_ansi (name_a, name);
3203 filename_from_ansi (type_a, type);
3206 /* Cache the volume information for future use, overwriting existing
3207 entry if present. */
3208 if (info == NULL)
3210 info = xmalloc (sizeof (volume_info_data));
3211 add_volume_info (root_dir, info);
3213 else
3215 xfree (info->name);
3216 xfree (info->type);
3219 info->name = xstrdup (name);
3220 unixtodos_filename (info->name);
3221 info->serialnum = serialnum;
3222 info->maxcomp = maxcomp;
3223 info->flags = flags;
3224 info->type = xstrdup (type);
3225 info->timestamp = GetTickCount ();
3228 return info;
3231 /* Get information on the volume where NAME is held; set path pointer to
3232 start of pathname in NAME (past UNC header\volume header if present),
3233 if pPath is non-NULL.
3235 Note: if NAME includes symlinks, the information is for the volume
3236 of the symlink, not of its target. That's because, even though
3237 GetVolumeInformation returns information about the symlink target
3238 of its argument, we only pass the root directory to
3239 GetVolumeInformation, not the full NAME. */
3240 static int
3241 get_volume_info (const char * name, const char ** pPath)
3243 char temp[MAX_UTF8_PATH];
3244 char *rootname = NULL; /* default to current volume */
3245 volume_info_data * info;
3246 int root_len = parse_root (name, pPath);
3248 if (name == NULL)
3249 return FALSE;
3251 /* Copy the root name of the volume, if given. */
3252 if (root_len)
3254 strncpy (temp, name, root_len);
3255 temp[root_len] = '\0';
3256 unixtodos_filename (temp);
3257 rootname = temp;
3260 info = GetCachedVolumeInformation (rootname);
3261 if (info != NULL)
3263 /* Set global referenced by other functions. */
3264 volume_info = *info;
3265 return TRUE;
3267 return FALSE;
3270 /* Determine if volume is FAT format (ie. only supports short 8.3
3271 names); also set path pointer to start of pathname in name, if
3272 pPath is non-NULL. */
3273 static int
3274 is_fat_volume (const char * name, const char ** pPath)
3276 if (get_volume_info (name, pPath))
3277 return (volume_info.maxcomp == 12);
3278 return FALSE;
3281 /* Convert all slashes in a filename to backslashes, and map filename
3282 to a valid 8.3 name if necessary. The result is a pointer to a
3283 static buffer, so CAVEAT EMPTOR! */
3284 const char *map_w32_filename (const char *, const char **);
3286 const char *
3287 map_w32_filename (const char * name, const char ** pPath)
3289 static char shortname[MAX_UTF8_PATH];
3290 char * str = shortname;
3291 char c;
3292 char * path;
3293 const char * save_name = name;
3295 if (strlen (name) >= sizeof (shortname))
3297 /* Return a filename which will cause callers to fail. */
3298 strcpy (shortname, "?");
3299 return shortname;
3302 if (!fatal_error_in_progress /* disable fancy processing during crash */
3303 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3305 register int left = 8; /* maximum number of chars in part */
3306 register int extn = 0; /* extension added? */
3307 register int dots = 2; /* maximum number of dots allowed */
3309 while (name < path)
3310 *str++ = *name++; /* skip past UNC header */
3312 while ((c = *name++))
3314 switch ( c )
3316 case ':':
3317 case '\\':
3318 case '/':
3319 *str++ = (c == ':' ? ':' : '\\');
3320 extn = 0; /* reset extension flags */
3321 dots = 2; /* max 2 dots */
3322 left = 8; /* max length 8 for main part */
3323 break;
3324 case '.':
3325 if ( dots )
3327 /* Convert path components of the form .xxx to _xxx,
3328 but leave . and .. as they are. This allows .emacs
3329 to be read as _emacs, for example. */
3331 if (! *name ||
3332 *name == '.' ||
3333 IS_DIRECTORY_SEP (*name))
3335 *str++ = '.';
3336 dots--;
3338 else
3340 *str++ = '_';
3341 left--;
3342 dots = 0;
3345 else if ( !extn )
3347 *str++ = '.';
3348 extn = 1; /* we've got an extension */
3349 left = 3; /* 3 chars in extension */
3351 else
3353 /* any embedded dots after the first are converted to _ */
3354 *str++ = '_';
3356 break;
3357 case '~':
3358 case '#': /* don't lose these, they're important */
3359 if ( ! left )
3360 str[-1] = c; /* replace last character of part */
3361 /* FALLTHRU */
3362 default:
3363 if ( left && 'A' <= c && c <= 'Z' )
3365 *str++ = tolower (c); /* map to lower case (looks nicer) */
3366 left--;
3367 dots = 0; /* started a path component */
3369 break;
3372 *str = '\0';
3374 else
3376 strcpy (shortname, name);
3377 unixtodos_filename (shortname);
3380 if (pPath)
3381 *pPath = shortname + (path - save_name);
3383 return shortname;
3386 static int
3387 is_exec (const char * name)
3389 char * p = strrchr (name, '.');
3390 return
3391 (p != NULL
3392 && (xstrcasecmp (p, ".exe") == 0 ||
3393 xstrcasecmp (p, ".com") == 0 ||
3394 xstrcasecmp (p, ".bat") == 0 ||
3395 xstrcasecmp (p, ".cmd") == 0));
3398 /* Emulate the Unix directory procedures opendir, closedir, and
3399 readdir. We rename them to sys_* names because some versions of
3400 MinGW startup code call opendir and readdir to glob wildcards, and
3401 the code that calls them doesn't grok UTF-8 encoded file names we
3402 produce in dirent->d_name[]. */
3404 struct dirent dir_static; /* simulated directory contents */
3405 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3406 static int dir_is_fat;
3407 static char dir_pathname[MAX_UTF8_PATH];
3408 static WIN32_FIND_DATAW dir_find_data_w;
3409 static WIN32_FIND_DATAA dir_find_data_a;
3410 #define DIR_FIND_DATA_W 1
3411 #define DIR_FIND_DATA_A 2
3412 static int last_dir_find_data = -1;
3414 /* Support shares on a network resource as subdirectories of a read-only
3415 root directory. */
3416 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3417 static HANDLE open_unc_volume (const char *);
3418 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3419 static void close_unc_volume (HANDLE);
3421 DIR *
3422 sys_opendir (const char *filename)
3424 DIR *dirp;
3426 /* Opening is done by FindFirstFile. However, a read is inherent to
3427 this operation, so we defer the open until read time. */
3429 if (dir_find_handle != INVALID_HANDLE_VALUE)
3430 return NULL;
3431 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3432 return NULL;
3434 /* Note: We don't support traversal of UNC volumes via symlinks.
3435 Doing so would mean punishing 99.99% of use cases by resolving
3436 all the possible symlinks in FILENAME, recursively. */
3437 if (is_unc_volume (filename))
3439 wnet_enum_handle = open_unc_volume (filename);
3440 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3441 return NULL;
3444 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3445 return NULL;
3447 dirp->dd_fd = 0;
3448 dirp->dd_loc = 0;
3449 dirp->dd_size = 0;
3451 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3452 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3453 /* Note: We don't support symlinks to file names on FAT volumes.
3454 Doing so would mean punishing 99.99% of use cases by resolving
3455 all the possible symlinks in FILENAME, recursively. */
3456 dir_is_fat = is_fat_volume (filename, NULL);
3458 return dirp;
3461 void
3462 sys_closedir (DIR *dirp)
3464 /* If we have a find-handle open, close it. */
3465 if (dir_find_handle != INVALID_HANDLE_VALUE)
3467 FindClose (dir_find_handle);
3468 dir_find_handle = INVALID_HANDLE_VALUE;
3470 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3472 close_unc_volume (wnet_enum_handle);
3473 wnet_enum_handle = INVALID_HANDLE_VALUE;
3475 xfree ((char *) dirp);
3478 struct dirent *
3479 sys_readdir (DIR *dirp)
3481 int downcase = !NILP (Vw32_downcase_file_names);
3483 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3485 if (!read_unc_volume (wnet_enum_handle,
3486 dir_find_data_w.cFileName,
3487 dir_find_data_a.cFileName,
3488 MAX_PATH))
3489 return NULL;
3491 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3492 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3494 char filename[MAX_UTF8_PATH];
3495 int ln;
3496 bool last_slash = true;
3498 /* Note: We don't need to worry about dir_pathname being longer
3499 than MAX_UTF8_PATH, as sys_opendir already took care of that
3500 when it called map_w32_filename: that function will put a "?"
3501 in its return value in that case, thus failing all the calls
3502 below. */
3503 strcpy (filename, dir_pathname);
3504 ln = strlen (filename);
3505 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3506 last_slash = false;
3508 /* Note: No need to resolve symlinks in FILENAME, because
3509 FindFirst opens the directory that is the target of a
3510 symlink. */
3511 if (w32_unicode_filenames)
3513 wchar_t fnw[MAX_PATH + 2];
3515 filename_to_utf16 (filename, fnw);
3516 if (!last_slash)
3517 wcscat (fnw, L"\\");
3518 wcscat (fnw, L"*");
3519 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3521 else
3523 char fna[MAX_PATH + 2];
3525 filename_to_ansi (filename, fna);
3526 if (!last_slash)
3527 strcat (fna, "\\");
3528 strcat (fna, "*");
3529 /* If FILENAME is not representable by the current ANSI
3530 codepage, we don't want FindFirstFileA to interpret the
3531 '?' characters as a wildcard. */
3532 if (_mbspbrk (fna, "?"))
3533 dir_find_handle = INVALID_HANDLE_VALUE;
3534 else
3535 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3538 if (dir_find_handle == INVALID_HANDLE_VALUE)
3540 /* Any changes in the value of errno here should be in sync
3541 with what directory_files_internal does when it calls
3542 readdir. */
3543 switch (GetLastError ())
3545 /* Windows uses this value when FindFirstFile finds no
3546 files that match the wildcard. This is not supposed
3547 to happen, since our wildcard is "*", but just in
3548 case, if there's some weird empty directory with not
3549 even "." and ".." entries... */
3550 case ERROR_FILE_NOT_FOUND:
3551 errno = 0;
3552 /* FALLTHRU */
3553 default:
3554 break;
3555 case ERROR_ACCESS_DENIED:
3556 case ERROR_NETWORK_ACCESS_DENIED:
3557 errno = EACCES;
3558 break;
3559 case ERROR_PATH_NOT_FOUND:
3560 case ERROR_INVALID_DRIVE:
3561 case ERROR_NOT_READY:
3562 case ERROR_BAD_NETPATH:
3563 case ERROR_BAD_NET_NAME:
3564 errno = ENOENT;
3565 break;
3567 return NULL;
3570 else if (w32_unicode_filenames)
3572 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3574 errno = 0;
3575 return NULL;
3578 else
3580 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3582 errno = 0;
3583 return NULL;
3587 /* Emacs never uses this value, so don't bother making it match
3588 value returned by stat(). */
3589 dir_static.d_ino = 1;
3591 if (w32_unicode_filenames)
3593 if (downcase || dir_is_fat)
3595 wchar_t tem[MAX_PATH];
3597 wcscpy (tem, dir_find_data_w.cFileName);
3598 CharLowerW (tem);
3599 filename_from_utf16 (tem, dir_static.d_name);
3601 else
3602 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3603 last_dir_find_data = DIR_FIND_DATA_W;
3605 else
3607 char tem[MAX_PATH];
3609 /* If the file name in cFileName[] includes `?' characters, it
3610 means the original file name used characters that cannot be
3611 represented by the current ANSI codepage. To avoid total
3612 lossage, retrieve the short 8+3 alias of the long file
3613 name. */
3614 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3616 strcpy (tem, dir_find_data_a.cAlternateFileName);
3617 /* 8+3 aliases are returned in all caps, which could break
3618 various alists that look at filenames' extensions. */
3619 downcase = 1;
3621 else if (downcase || dir_is_fat)
3622 strcpy (tem, dir_find_data_a.cFileName);
3623 else
3624 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3625 if (downcase || dir_is_fat)
3627 _mbslwr (tem);
3628 filename_from_ansi (tem, dir_static.d_name);
3630 last_dir_find_data = DIR_FIND_DATA_A;
3633 dir_static.d_namlen = strlen (dir_static.d_name);
3634 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3635 dir_static.d_namlen - dir_static.d_namlen % 4;
3637 return &dir_static;
3640 static HANDLE
3641 open_unc_volume (const char *path)
3643 const char *fn = map_w32_filename (path, NULL);
3644 DWORD result;
3645 HANDLE henum;
3647 if (w32_unicode_filenames)
3649 NETRESOURCEW nrw;
3650 wchar_t fnw[MAX_PATH];
3652 nrw.dwScope = RESOURCE_GLOBALNET;
3653 nrw.dwType = RESOURCETYPE_DISK;
3654 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3655 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3656 nrw.lpLocalName = NULL;
3657 filename_to_utf16 (fn, fnw);
3658 nrw.lpRemoteName = fnw;
3659 nrw.lpComment = NULL;
3660 nrw.lpProvider = NULL;
3662 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3663 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3665 else
3667 NETRESOURCEA nra;
3668 char fna[MAX_PATH];
3670 nra.dwScope = RESOURCE_GLOBALNET;
3671 nra.dwType = RESOURCETYPE_DISK;
3672 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3673 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3674 nra.lpLocalName = NULL;
3675 filename_to_ansi (fn, fna);
3676 nra.lpRemoteName = fna;
3677 nra.lpComment = NULL;
3678 nra.lpProvider = NULL;
3680 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3681 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3683 if (result == NO_ERROR)
3684 return henum;
3685 else
3687 /* Make sure directory_files_internal reports a sensible error. */
3688 errno = ENOENT;
3689 return INVALID_HANDLE_VALUE;
3693 static void *
3694 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3696 DWORD count;
3697 int result;
3698 char *buffer;
3699 DWORD bufsize = 512;
3700 void *retval;
3702 count = 1;
3703 if (w32_unicode_filenames)
3705 wchar_t *ptrw;
3707 bufsize *= 2;
3708 buffer = alloca (bufsize);
3709 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3710 if (result != NO_ERROR)
3711 return NULL;
3712 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3713 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3714 ptrw += 2;
3715 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3716 ptrw++;
3717 wcsncpy (fname_w, ptrw, size);
3718 retval = fname_w;
3720 else
3722 int dbcs_p = max_filename_mbslen () > 1;
3723 char *ptra;
3725 buffer = alloca (bufsize);
3726 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3727 if (result != NO_ERROR)
3728 return NULL;
3729 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3730 ptra += 2;
3731 if (!dbcs_p)
3732 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3733 else
3735 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3736 ptra = CharNextExA (file_name_codepage, ptra, 0);
3738 ptra++;
3739 strncpy (fname_a, ptra, size);
3740 retval = fname_a;
3743 return retval;
3746 static void
3747 close_unc_volume (HANDLE henum)
3749 if (henum != INVALID_HANDLE_VALUE)
3750 WNetCloseEnum (henum);
3753 static DWORD
3754 unc_volume_file_attributes (const char *path)
3756 HANDLE henum;
3757 DWORD attrs;
3759 henum = open_unc_volume (path);
3760 if (henum == INVALID_HANDLE_VALUE)
3761 return -1;
3763 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3765 close_unc_volume (henum);
3767 return attrs;
3770 /* Ensure a network connection is authenticated. */
3771 static void
3772 logon_network_drive (const char *path)
3774 char share[MAX_UTF8_PATH];
3775 int n_slashes;
3776 char drive[4];
3777 UINT drvtype;
3778 char *p;
3779 DWORD val;
3781 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3782 drvtype = DRIVE_REMOTE;
3783 else if (path[0] == '\0' || path[1] != ':')
3784 drvtype = GetDriveType (NULL);
3785 else
3787 drive[0] = path[0];
3788 drive[1] = ':';
3789 drive[2] = '\\';
3790 drive[3] = '\0';
3791 drvtype = GetDriveType (drive);
3794 /* Only logon to networked drives. */
3795 if (drvtype != DRIVE_REMOTE)
3796 return;
3798 n_slashes = 2;
3799 strncpy (share, path, MAX_UTF8_PATH);
3800 /* Truncate to just server and share name. */
3801 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3803 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3805 *p = '\0';
3806 break;
3810 if (w32_unicode_filenames)
3812 NETRESOURCEW resourcew;
3813 wchar_t share_w[MAX_PATH];
3815 resourcew.dwScope = RESOURCE_GLOBALNET;
3816 resourcew.dwType = RESOURCETYPE_DISK;
3817 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3818 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3819 resourcew.lpLocalName = NULL;
3820 filename_to_utf16 (share, share_w);
3821 resourcew.lpRemoteName = share_w;
3822 resourcew.lpProvider = NULL;
3824 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3826 else
3828 NETRESOURCEA resourcea;
3829 char share_a[MAX_PATH];
3831 resourcea.dwScope = RESOURCE_GLOBALNET;
3832 resourcea.dwType = RESOURCETYPE_DISK;
3833 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3834 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3835 resourcea.lpLocalName = NULL;
3836 filename_to_ansi (share, share_a);
3837 resourcea.lpRemoteName = share_a;
3838 resourcea.lpProvider = NULL;
3840 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3843 switch (val)
3845 case NO_ERROR:
3846 case ERROR_ALREADY_ASSIGNED:
3847 break;
3848 case ERROR_ACCESS_DENIED:
3849 case ERROR_LOGON_FAILURE:
3850 errno = EACCES;
3851 break;
3852 case ERROR_BUSY:
3853 errno = EAGAIN;
3854 break;
3855 case ERROR_BAD_NET_NAME:
3856 case ERROR_NO_NET_OR_BAD_PATH:
3857 case ERROR_NO_NETWORK:
3858 case ERROR_CANCELLED:
3859 default:
3860 errno = ENOENT;
3861 break;
3865 /* Emulate faccessat(2). */
3867 faccessat (int dirfd, const char * path, int mode, int flags)
3869 DWORD attributes;
3871 if (dirfd != AT_FDCWD
3872 && !(IS_DIRECTORY_SEP (path[0])
3873 || IS_DEVICE_SEP (path[1])))
3875 errno = EBADF;
3876 return -1;
3879 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3880 newer versions blow up when passed D_OK. */
3881 path = map_w32_filename (path, NULL);
3882 /* If the last element of PATH is a symlink, we need to resolve it
3883 to get the attributes of its target file. Note: any symlinks in
3884 PATH elements other than the last one are transparently resolved
3885 by GetFileAttributes below. */
3886 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3887 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3888 path = chase_symlinks (path);
3890 if (w32_unicode_filenames)
3892 wchar_t path_w[MAX_PATH];
3894 filename_to_utf16 (path, path_w);
3895 attributes = GetFileAttributesW (path_w);
3897 else
3899 char path_a[MAX_PATH];
3901 filename_to_ansi (path, path_a);
3902 attributes = GetFileAttributesA (path_a);
3905 if (attributes == -1)
3907 DWORD w32err = GetLastError ();
3909 switch (w32err)
3911 case ERROR_INVALID_NAME:
3912 case ERROR_BAD_PATHNAME:
3913 if (is_unc_volume (path))
3915 attributes = unc_volume_file_attributes (path);
3916 if (attributes == -1)
3918 errno = EACCES;
3919 return -1;
3921 goto check_attrs;
3923 /* FALLTHROUGH */
3924 case ERROR_FILE_NOT_FOUND:
3925 case ERROR_BAD_NETPATH:
3926 errno = ENOENT;
3927 break;
3928 default:
3929 errno = EACCES;
3930 break;
3932 return -1;
3935 check_attrs:
3936 if ((mode & X_OK) != 0
3937 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3939 errno = EACCES;
3940 return -1;
3942 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3944 errno = EACCES;
3945 return -1;
3947 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3949 errno = EACCES;
3950 return -1;
3952 return 0;
3955 /* A special test for DIRNAME being a directory accessible by the
3956 current user. This is needed because the security permissions in
3957 directory's ACLs are not visible in the Posix-style mode bits
3958 returned by 'stat' and in attributes returned by GetFileAttributes.
3959 So a directory would seem like it's readable by the current user,
3960 but will in fact error out with EACCES when they actually try. */
3962 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3964 char pattern[MAX_UTF8_PATH];
3965 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3966 HANDLE dh;
3968 /* Network volumes need a different reading method. */
3969 if (is_unc_volume (dirname))
3971 void *read_result = NULL;
3972 wchar_t fnw[MAX_PATH];
3973 char fna[MAX_PATH];
3975 dh = open_unc_volume (dirname);
3976 if (dh != INVALID_HANDLE_VALUE)
3978 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
3979 close_unc_volume (dh);
3981 /* Treat empty volumes as accessible. */
3982 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
3985 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3986 MAX_UTF8_PATH. */
3987 strcpy (pattern, map_w32_filename (dirname, NULL));
3989 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3990 opens the directory that is the target of a symlink. */
3991 if (w32_unicode_filenames)
3993 wchar_t pat_w[MAX_PATH + 2];
3994 WIN32_FIND_DATAW dfd_w;
3996 filename_to_utf16 (pattern, pat_w);
3997 if (!last_slash)
3998 wcscat (pat_w, L"\\");
3999 wcscat (pat_w, L"*");
4000 dh = FindFirstFileW (pat_w, &dfd_w);
4002 else
4004 char pat_a[MAX_PATH + 2];
4005 WIN32_FIND_DATAA dfd_a;
4007 filename_to_ansi (pattern, pat_a);
4008 if (!last_slash)
4009 strcpy (pat_a, "\\");
4010 strcat (pat_a, "*");
4011 /* In case DIRNAME cannot be expressed in characters from the
4012 current ANSI codepage. */
4013 if (_mbspbrk (pat_a, "?"))
4014 dh = INVALID_HANDLE_VALUE;
4015 else
4016 dh = FindFirstFileA (pat_a, &dfd_a);
4019 if (dh == INVALID_HANDLE_VALUE)
4020 return 0;
4021 FindClose (dh);
4022 return 1;
4025 /* A version of 'access' to be used locally with file names in
4026 locale-specific encoding. Does not resolve symlinks and does not
4027 support file names on FAT12 and FAT16 volumes, but that's OK, since
4028 we only invoke this function for files inside the Emacs source or
4029 installation tree, on directories (so any symlinks should have the
4030 directory bit set), and on short file names such as "C:/.emacs". */
4031 static int
4032 sys_access (const char *fname, int mode)
4034 char fname_copy[MAX_PATH], *p;
4035 DWORD attributes;
4037 strcpy (fname_copy, fname);
4038 /* Do the equivalent of unixtodos_filename. */
4039 for (p = fname_copy; *p; p = CharNext (p))
4040 if (*p == '/')
4041 *p = '\\';
4043 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4045 DWORD w32err = GetLastError ();
4047 switch (w32err)
4049 case ERROR_INVALID_NAME:
4050 case ERROR_BAD_PATHNAME:
4051 case ERROR_FILE_NOT_FOUND:
4052 case ERROR_BAD_NETPATH:
4053 errno = ENOENT;
4054 break;
4055 default:
4056 errno = EACCES;
4057 break;
4059 return -1;
4061 if ((mode & X_OK) != 0
4062 && !(is_exec (fname_copy)
4063 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4065 errno = EACCES;
4066 return -1;
4068 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4070 errno = EACCES;
4071 return -1;
4073 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4075 errno = EACCES;
4076 return -1;
4078 return 0;
4081 /* Shadow some MSVC runtime functions to map requests for long filenames
4082 to reasonable short names if necessary. This was originally added to
4083 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4084 long file names. */
4087 sys_chdir (const char * path)
4089 path = map_w32_filename (path, NULL);
4090 if (w32_unicode_filenames)
4092 wchar_t newdir_w[MAX_PATH];
4094 if (filename_to_utf16 (path, newdir_w) == 0)
4095 return _wchdir (newdir_w);
4096 return -1;
4098 else
4100 char newdir_a[MAX_PATH];
4102 if (filename_to_ansi (path, newdir_a) == 0)
4103 return _chdir (newdir_a);
4104 return -1;
4109 sys_chmod (const char * path, int mode)
4111 path = chase_symlinks (map_w32_filename (path, NULL));
4112 if (w32_unicode_filenames)
4114 wchar_t path_w[MAX_PATH];
4116 filename_to_utf16 (path, path_w);
4117 return _wchmod (path_w, mode);
4119 else
4121 char path_a[MAX_PATH];
4123 filename_to_ansi (path, path_a);
4124 return _chmod (path_a, mode);
4129 sys_creat (const char * path, int mode)
4131 path = map_w32_filename (path, NULL);
4132 if (w32_unicode_filenames)
4134 wchar_t path_w[MAX_PATH];
4136 filename_to_utf16 (path, path_w);
4137 return _wcreat (path_w, mode);
4139 else
4141 char path_a[MAX_PATH];
4143 filename_to_ansi (path, path_a);
4144 return _creat (path_a, mode);
4148 FILE *
4149 sys_fopen (const char * path, const char * mode)
4151 int fd;
4152 int oflag;
4153 const char * mode_save = mode;
4155 /* Force all file handles to be non-inheritable. This is necessary to
4156 ensure child processes don't unwittingly inherit handles that might
4157 prevent future file access. */
4159 if (mode[0] == 'r')
4160 oflag = O_RDONLY;
4161 else if (mode[0] == 'w' || mode[0] == 'a')
4162 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4163 else
4164 return NULL;
4166 /* Only do simplistic option parsing. */
4167 while (*++mode)
4168 if (mode[0] == '+')
4170 oflag &= ~(O_RDONLY | O_WRONLY);
4171 oflag |= O_RDWR;
4173 else if (mode[0] == 'b')
4175 oflag &= ~O_TEXT;
4176 oflag |= O_BINARY;
4178 else if (mode[0] == 't')
4180 oflag &= ~O_BINARY;
4181 oflag |= O_TEXT;
4183 else break;
4185 path = map_w32_filename (path, NULL);
4186 if (w32_unicode_filenames)
4188 wchar_t path_w[MAX_PATH];
4190 filename_to_utf16 (path, path_w);
4191 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4193 else
4195 char path_a[MAX_PATH];
4197 filename_to_ansi (path, path_a);
4198 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4200 if (fd < 0)
4201 return NULL;
4203 return _fdopen (fd, mode_save);
4206 /* This only works on NTFS volumes, but is useful to have. */
4208 sys_link (const char * old, const char * new)
4210 HANDLE fileh;
4211 int result = -1;
4212 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4213 wchar_t oldname_w[MAX_PATH];
4214 char oldname_a[MAX_PATH];
4216 if (old == NULL || new == NULL)
4218 errno = ENOENT;
4219 return -1;
4222 strcpy (oldname, map_w32_filename (old, NULL));
4223 strcpy (newname, map_w32_filename (new, NULL));
4225 if (w32_unicode_filenames)
4227 filename_to_utf16 (oldname, oldname_w);
4228 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4229 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4231 else
4233 filename_to_ansi (oldname, oldname_a);
4234 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4235 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4237 if (fileh != INVALID_HANDLE_VALUE)
4239 int wlen;
4241 /* Confusingly, the "alternate" stream name field does not apply
4242 when restoring a hard link, and instead contains the actual
4243 stream data for the link (ie. the name of the link to create).
4244 The WIN32_STREAM_ID structure before the cStreamName field is
4245 the stream header, which is then immediately followed by the
4246 stream data. */
4248 struct {
4249 WIN32_STREAM_ID wid;
4250 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4251 } data;
4253 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4254 indicates that flag is unsupported for CP_UTF8, and OTOH says
4255 it is the default anyway. */
4256 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4257 data.wid.cStreamName, MAX_PATH);
4258 if (wlen > 0)
4260 LPVOID context = NULL;
4261 DWORD wbytes = 0;
4263 data.wid.dwStreamId = BACKUP_LINK;
4264 data.wid.dwStreamAttributes = 0;
4265 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4266 data.wid.Size.HighPart = 0;
4267 data.wid.dwStreamNameSize = 0;
4269 if (BackupWrite (fileh, (LPBYTE)&data,
4270 offsetof (WIN32_STREAM_ID, cStreamName)
4271 + data.wid.Size.LowPart,
4272 &wbytes, FALSE, FALSE, &context)
4273 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4275 /* succeeded */
4276 result = 0;
4278 else
4280 DWORD err = GetLastError ();
4281 DWORD attributes;
4283 switch (err)
4285 case ERROR_ACCESS_DENIED:
4286 /* This is what happens when OLDNAME is a directory,
4287 since Windows doesn't support hard links to
4288 directories. Posix says to set errno to EPERM in
4289 that case. */
4290 if (w32_unicode_filenames)
4291 attributes = GetFileAttributesW (oldname_w);
4292 else
4293 attributes = GetFileAttributesA (oldname_a);
4294 if (attributes != -1
4295 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4296 errno = EPERM;
4297 else if (attributes == -1
4298 && is_unc_volume (oldname)
4299 && unc_volume_file_attributes (oldname) != -1)
4300 errno = EPERM;
4301 else
4302 errno = EACCES;
4303 break;
4304 case ERROR_TOO_MANY_LINKS:
4305 errno = EMLINK;
4306 break;
4307 case ERROR_NOT_SAME_DEVICE:
4308 errno = EXDEV;
4309 break;
4310 default:
4311 errno = EINVAL;
4312 break;
4317 CloseHandle (fileh);
4319 else
4320 errno = ENOENT;
4322 return result;
4326 sys_mkdir (const char * path)
4328 path = map_w32_filename (path, NULL);
4330 if (w32_unicode_filenames)
4332 wchar_t path_w[MAX_PATH];
4334 filename_to_utf16 (path, path_w);
4335 return _wmkdir (path_w);
4337 else
4339 char path_a[MAX_PATH];
4341 filename_to_ansi (path, path_a);
4342 return _mkdir (path_a);
4347 sys_open (const char * path, int oflag, int mode)
4349 const char* mpath = map_w32_filename (path, NULL);
4350 int res = -1;
4352 if (w32_unicode_filenames)
4354 wchar_t mpath_w[MAX_PATH];
4356 filename_to_utf16 (mpath, mpath_w);
4357 /* If possible, try to open file without _O_CREAT, to be able to
4358 write to existing hidden and system files. Force all file
4359 handles to be non-inheritable. */
4360 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4361 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4362 if (res < 0)
4363 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4365 else
4367 char mpath_a[MAX_PATH];
4369 filename_to_ansi (mpath, mpath_a);
4370 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4371 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4372 if (res < 0)
4373 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4376 return res;
4379 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4380 when using mktemp.
4382 Standard algorithm for generating a temporary file name seems to be
4383 use pid or tid with a letter on the front (in place of the 6 X's)
4384 and cycle through the letters to find a unique name. We extend
4385 that to allow any reasonable character as the first of the 6 X's,
4386 so that the number of simultaneously used temporary files will be
4387 greater. */
4390 mkostemp (char * template, int flags)
4392 char * p;
4393 int i, fd = -1;
4394 unsigned uid = GetCurrentThreadId ();
4395 int save_errno = errno;
4396 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4398 errno = EINVAL;
4399 if (template == NULL)
4400 return -1;
4402 p = template + strlen (template);
4403 i = 5;
4404 /* replace up to the last 5 X's with uid in decimal */
4405 while (--p >= template && p[0] == 'X' && --i >= 0)
4407 p[0] = '0' + uid % 10;
4408 uid /= 10;
4411 if (i < 0 && p[0] == 'X')
4413 i = 0;
4416 p[0] = first_char[i];
4417 if ((fd = sys_open (template,
4418 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4419 S_IRUSR | S_IWUSR)) >= 0
4420 || errno != EEXIST)
4422 if (fd >= 0)
4423 errno = save_errno;
4424 return fd;
4427 while (++i < sizeof (first_char));
4430 /* Template is badly formed or else we can't generate a unique name. */
4431 return -1;
4435 fchmod (int fd, mode_t mode)
4437 return 0;
4441 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4443 BOOL result;
4444 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4445 int newname_dev;
4446 int oldname_dev;
4447 bool have_temp_a = false;
4449 /* MoveFile on Windows 95 doesn't correctly change the short file name
4450 alias in a number of circumstances (it is not easy to predict when
4451 just by looking at oldname and newname, unfortunately). In these
4452 cases, renaming through a temporary name avoids the problem.
4454 A second problem on Windows 95 is that renaming through a temp name when
4455 newname is uppercase fails (the final long name ends up in
4456 lowercase, although the short alias might be uppercase) UNLESS the
4457 long temp name is not 8.3.
4459 So, on Windows 95 we always rename through a temp name, and we make sure
4460 the temp name has a long extension to ensure correct renaming. */
4462 strcpy (temp, map_w32_filename (oldname, NULL));
4464 /* volume_info is set indirectly by map_w32_filename. */
4465 oldname_dev = volume_info.serialnum;
4467 if (os_subtype == OS_9X)
4469 char * o;
4470 char * p;
4471 int i = 0;
4472 char oldname_a[MAX_PATH];
4474 oldname = map_w32_filename (oldname, NULL);
4475 filename_to_ansi (oldname, oldname_a);
4476 filename_to_ansi (temp, temp_a);
4477 if ((o = strrchr (oldname_a, '\\')))
4478 o++;
4479 else
4480 o = (char *) oldname_a;
4482 if ((p = strrchr (temp_a, '\\')))
4483 p++;
4484 else
4485 p = temp_a;
4489 /* Force temp name to require a manufactured 8.3 alias - this
4490 seems to make the second rename work properly. */
4491 sprintf (p, "_.%s.%d", o, i);
4492 i++;
4493 result = rename (oldname_a, temp_a);
4495 /* This loop must surely terminate! */
4496 while (result < 0 && errno == EEXIST);
4497 if (result < 0)
4498 return -1;
4499 have_temp_a = true;
4502 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4503 (at least if it is a file; don't do this for directories).
4505 Since we mustn't do this if we are just changing the case of the
4506 file name (we would end up deleting the file we are trying to
4507 rename!), we let rename detect if the destination file already
4508 exists - that way we avoid the possible pitfalls of trying to
4509 determine ourselves whether two names really refer to the same
4510 file, which is not always possible in the general case. (Consider
4511 all the permutations of shared or subst'd drives, etc.) */
4513 newname = map_w32_filename (newname, NULL);
4515 /* volume_info is set indirectly by map_w32_filename. */
4516 newname_dev = volume_info.serialnum;
4518 if (w32_unicode_filenames)
4520 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4522 filename_to_utf16 (temp, temp_w);
4523 filename_to_utf16 (newname, newname_w);
4524 result = _wrename (temp_w, newname_w);
4525 if (result < 0 && force)
4527 DWORD w32err = GetLastError ();
4529 if (errno == EACCES
4530 && newname_dev != oldname_dev)
4532 /* The implementation of `rename' on Windows does not return
4533 errno = EXDEV when you are moving a directory to a
4534 different storage device (ex. logical disk). It returns
4535 EACCES instead. So here we handle such situations and
4536 return EXDEV. */
4537 DWORD attributes;
4539 if ((attributes = GetFileAttributesW (temp_w)) != -1
4540 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4541 errno = EXDEV;
4543 else if (errno == EEXIST)
4545 if (_wchmod (newname_w, 0666) != 0)
4546 return result;
4547 if (_wunlink (newname_w) != 0)
4548 return result;
4549 result = _wrename (temp_w, newname_w);
4551 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4552 && is_symlink (temp))
4554 /* This is Windows prohibiting the user from creating a
4555 symlink in another place, since that requires
4556 privileges. */
4557 errno = EPERM;
4561 else
4563 char newname_a[MAX_PATH];
4565 if (!have_temp_a)
4566 filename_to_ansi (temp, temp_a);
4567 filename_to_ansi (newname, newname_a);
4568 result = rename (temp_a, newname_a);
4569 if (result < 0 && force)
4571 DWORD w32err = GetLastError ();
4573 if (errno == EACCES
4574 && newname_dev != oldname_dev)
4576 DWORD attributes;
4578 if ((attributes = GetFileAttributesA (temp_a)) != -1
4579 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4580 errno = EXDEV;
4582 else if (errno == EEXIST)
4584 if (_chmod (newname_a, 0666) != 0)
4585 return result;
4586 if (_unlink (newname_a) != 0)
4587 return result;
4588 result = rename (temp_a, newname_a);
4590 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4591 && is_symlink (temp))
4592 errno = EPERM;
4596 return result;
4600 sys_rename (char const *old, char const *new)
4602 return sys_rename_replace (old, new, TRUE);
4606 sys_rmdir (const char * path)
4608 path = map_w32_filename (path, NULL);
4610 if (w32_unicode_filenames)
4612 wchar_t path_w[MAX_PATH];
4614 filename_to_utf16 (path, path_w);
4615 return _wrmdir (path_w);
4617 else
4619 char path_a[MAX_PATH];
4621 filename_to_ansi (path, path_a);
4622 return _rmdir (path_a);
4627 sys_unlink (const char * path)
4629 int rmstatus, e;
4631 path = map_w32_filename (path, NULL);
4633 if (w32_unicode_filenames)
4635 wchar_t path_w[MAX_PATH];
4637 filename_to_utf16 (path, path_w);
4638 /* On Unix, unlink works without write permission. */
4639 _wchmod (path_w, 0666);
4640 rmstatus = _wunlink (path_w);
4641 e = errno;
4642 /* Symlinks to directories can only be deleted by _rmdir;
4643 _unlink returns EACCES. */
4644 if (rmstatus != 0
4645 && errno == EACCES
4646 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4647 rmstatus = _wrmdir (path_w);
4648 else
4649 errno = e;
4651 else
4653 char path_a[MAX_PATH];
4655 filename_to_ansi (path, path_a);
4656 _chmod (path_a, 0666);
4657 rmstatus = _unlink (path_a);
4658 e = errno;
4659 if (rmstatus != 0
4660 && errno == EACCES
4661 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4662 rmstatus = _rmdir (path_a);
4663 else
4664 errno = e;
4667 return rmstatus;
4670 static FILETIME utc_base_ft;
4671 static ULONGLONG utc_base; /* In 100ns units */
4672 static int init = 0;
4674 #define FILETIME_TO_U64(result, ft) \
4675 do { \
4676 ULARGE_INTEGER uiTemp; \
4677 uiTemp.LowPart = (ft).dwLowDateTime; \
4678 uiTemp.HighPart = (ft).dwHighDateTime; \
4679 result = uiTemp.QuadPart; \
4680 } while (0)
4682 static void
4683 initialize_utc_base (void)
4685 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4686 SYSTEMTIME st;
4688 st.wYear = 1970;
4689 st.wMonth = 1;
4690 st.wDay = 1;
4691 st.wHour = 0;
4692 st.wMinute = 0;
4693 st.wSecond = 0;
4694 st.wMilliseconds = 0;
4696 SystemTimeToFileTime (&st, &utc_base_ft);
4697 FILETIME_TO_U64 (utc_base, utc_base_ft);
4700 static time_t
4701 convert_time (FILETIME ft)
4703 ULONGLONG tmp;
4705 if (!init)
4707 initialize_utc_base ();
4708 init = 1;
4711 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4712 return 0;
4714 FILETIME_TO_U64 (tmp, ft);
4715 return (time_t) ((tmp - utc_base) / 10000000L);
4718 static void
4719 convert_from_time_t (time_t time, FILETIME * pft)
4721 ULARGE_INTEGER tmp;
4723 if (!init)
4725 initialize_utc_base ();
4726 init = 1;
4729 /* time in 100ns units since 1-Jan-1601 */
4730 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4731 pft->dwHighDateTime = tmp.HighPart;
4732 pft->dwLowDateTime = tmp.LowPart;
4735 static PSECURITY_DESCRIPTOR
4736 get_file_security_desc_by_handle (HANDLE h)
4738 PSECURITY_DESCRIPTOR psd = NULL;
4739 DWORD err;
4740 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4741 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4743 err = get_security_info (h, SE_FILE_OBJECT, si,
4744 NULL, NULL, NULL, NULL, &psd);
4745 if (err != ERROR_SUCCESS)
4746 return NULL;
4748 return psd;
4751 static PSECURITY_DESCRIPTOR
4752 get_file_security_desc_by_name (const char *fname)
4754 PSECURITY_DESCRIPTOR psd = NULL;
4755 DWORD sd_len, err;
4756 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4757 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4759 if (!get_file_security (fname, si, psd, 0, &sd_len))
4761 err = GetLastError ();
4762 if (err != ERROR_INSUFFICIENT_BUFFER)
4763 return NULL;
4766 psd = xmalloc (sd_len);
4767 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4769 xfree (psd);
4770 return NULL;
4773 return psd;
4776 static DWORD
4777 get_rid (PSID sid)
4779 unsigned n_subauthorities;
4781 /* Use the last sub-authority value of the RID, the relative
4782 portion of the SID, as user/group ID. */
4783 n_subauthorities = *get_sid_sub_authority_count (sid);
4784 if (n_subauthorities < 1)
4785 return 0; /* the "World" RID */
4786 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4789 /* Caching SID and account values for faster lokup. */
4791 struct w32_id {
4792 unsigned rid;
4793 struct w32_id *next;
4794 char name[GNLEN+1];
4795 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4798 static struct w32_id *w32_idlist;
4800 static int
4801 w32_cached_id (PSID sid, unsigned *id, char *name)
4803 struct w32_id *tail, *found;
4805 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4807 if (equal_sid ((PSID)tail->sid, sid))
4809 found = tail;
4810 break;
4813 if (found)
4815 *id = found->rid;
4816 strcpy (name, found->name);
4817 return 1;
4819 else
4820 return 0;
4823 static void
4824 w32_add_to_cache (PSID sid, unsigned id, char *name)
4826 DWORD sid_len;
4827 struct w32_id *new_entry;
4829 /* We don't want to leave behind stale cache from when Emacs was
4830 dumped. */
4831 if (initialized)
4833 sid_len = get_length_sid (sid);
4834 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4835 if (new_entry)
4837 new_entry->rid = id;
4838 strcpy (new_entry->name, name);
4839 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4840 new_entry->next = w32_idlist;
4841 w32_idlist = new_entry;
4846 #define UID 1
4847 #define GID 2
4849 static int
4850 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4852 PSID sid = NULL;
4853 BOOL dflt;
4854 SID_NAME_USE ignore;
4855 char name[UNLEN+1];
4856 DWORD name_len = sizeof (name);
4857 char domain[1024];
4858 DWORD domain_len = sizeof (domain);
4859 int use_dflt = 0;
4860 int result;
4862 if (what == UID)
4863 result = get_security_descriptor_owner (psd, &sid, &dflt);
4864 else if (what == GID)
4865 result = get_security_descriptor_group (psd, &sid, &dflt);
4866 else
4867 result = 0;
4869 if (!result || !is_valid_sid (sid))
4870 use_dflt = 1;
4871 else if (!w32_cached_id (sid, id, nm))
4873 if (!lookup_account_sid (NULL, sid, name, &name_len,
4874 domain, &domain_len, &ignore)
4875 || name_len > UNLEN+1)
4876 use_dflt = 1;
4877 else
4879 *id = get_rid (sid);
4880 strcpy (nm, name);
4881 w32_add_to_cache (sid, *id, name);
4884 return use_dflt;
4887 static void
4888 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4890 int dflt_usr = 0, dflt_grp = 0;
4892 if (!psd)
4894 dflt_usr = 1;
4895 dflt_grp = 1;
4897 else
4899 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4900 dflt_usr = 1;
4901 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4902 dflt_grp = 1;
4904 /* Consider files to belong to current user/group, if we cannot get
4905 more accurate information. */
4906 if (dflt_usr)
4908 st->st_uid = dflt_passwd.pw_uid;
4909 strcpy (st->st_uname, dflt_passwd.pw_name);
4911 if (dflt_grp)
4913 st->st_gid = dflt_passwd.pw_gid;
4914 strcpy (st->st_gname, dflt_group.gr_name);
4918 /* Return non-zero if NAME is a potentially slow filesystem. */
4919 int is_slow_fs (const char *);
4922 is_slow_fs (const char *name)
4924 char drive_root[4];
4925 UINT devtype;
4927 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4928 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4929 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4930 devtype = GetDriveType (NULL); /* use root of current drive */
4931 else
4933 /* GetDriveType needs the root directory of the drive. */
4934 strncpy (drive_root, name, 2);
4935 drive_root[2] = '\\';
4936 drive_root[3] = '\0';
4937 devtype = GetDriveType (drive_root);
4939 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4942 /* If this is non-zero, the caller wants accurate information about
4943 file's owner and group, which could be expensive to get. dired.c
4944 uses this flag when needed for the job at hand. */
4945 int w32_stat_get_owner_group;
4947 /* MSVC stat function can't cope with UNC names and has other bugs, so
4948 replace it with our own. This also allows us to calculate consistent
4949 inode values and owner/group without hacks in the main Emacs code,
4950 and support file names encoded in UTF-8. */
4952 static int
4953 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4955 char *name, *save_name, *r;
4956 WIN32_FIND_DATAW wfd_w;
4957 WIN32_FIND_DATAA wfd_a;
4958 HANDLE fh;
4959 unsigned __int64 fake_inode = 0;
4960 int permission;
4961 int len;
4962 int rootdir = FALSE;
4963 PSECURITY_DESCRIPTOR psd = NULL;
4964 int is_a_symlink = 0;
4965 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4966 DWORD access_rights = 0;
4967 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4968 FILETIME ctime, atime, wtime;
4969 wchar_t name_w[MAX_PATH];
4970 char name_a[MAX_PATH];
4972 if (path == NULL || buf == NULL)
4974 errno = EFAULT;
4975 return -1;
4978 save_name = name = (char *) map_w32_filename (path, &path);
4979 /* Must be valid filename, no wild cards or other invalid
4980 characters. */
4981 if (strpbrk (name, "*?|<>\""))
4983 errno = ENOENT;
4984 return -1;
4987 len = strlen (name);
4988 /* Allocate 1 extra byte so that we could append a slash to a root
4989 directory, down below. */
4990 name = strcpy (alloca (len + 2), name);
4992 /* Avoid a somewhat costly call to is_symlink if the filesystem
4993 doesn't support symlinks. */
4994 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4995 is_a_symlink = is_symlink (name);
4997 /* Plan A: Open the file and get all the necessary information via
4998 the resulting handle. This solves several issues in one blow:
5000 . retrieves attributes for the target of a symlink, if needed
5001 . gets attributes of root directories and symlinks pointing to
5002 root directories, thus avoiding the need for special-casing
5003 these and detecting them by examining the file-name format
5004 . retrieves more accurate attributes (e.g., non-zero size for
5005 some directories, esp. directories that are junction points)
5006 . correctly resolves "c:/..", "/.." and similar file names
5007 . avoids run-time penalties for 99% of use cases
5009 Plan A is always tried first, unless the user asked not to (but
5010 if the file is a symlink and we need to follow links, we try Plan
5011 A even if the user asked not to).
5013 If Plan A fails, we go to Plan B (below), where various
5014 potentially expensive techniques must be used to handle "special"
5015 files such as UNC volumes etc. */
5016 if (!(NILP (Vw32_get_true_file_attributes)
5017 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
5018 /* Following symlinks requires getting the info by handle. */
5019 || (is_a_symlink && follow_symlinks))
5021 BY_HANDLE_FILE_INFORMATION info;
5023 if (is_a_symlink && !follow_symlinks)
5024 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5025 /* READ_CONTROL access rights are required to get security info
5026 by handle. But if the OS doesn't support security in the
5027 first place, we don't need to try. */
5028 if (is_windows_9x () != TRUE)
5029 access_rights |= READ_CONTROL;
5031 if (w32_unicode_filenames)
5033 filename_to_utf16 (name, name_w);
5034 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
5035 file_flags, NULL);
5036 /* If CreateFile fails with READ_CONTROL, try again with
5037 zero as access rights. */
5038 if (fh == INVALID_HANDLE_VALUE && access_rights)
5039 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
5040 file_flags, NULL);
5042 else
5044 filename_to_ansi (name, name_a);
5045 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5046 file_flags, NULL);
5047 if (fh == INVALID_HANDLE_VALUE && access_rights)
5048 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5049 file_flags, NULL);
5051 if (fh == INVALID_HANDLE_VALUE)
5052 goto no_true_file_attributes;
5054 /* This is more accurate in terms of getting the correct number
5055 of links, but is quite slow (it is noticeable when Emacs is
5056 making a list of file name completions). */
5057 if (GetFileInformationByHandle (fh, &info))
5059 nlinks = info.nNumberOfLinks;
5060 /* Might as well use file index to fake inode values, but this
5061 is not guaranteed to be unique unless we keep a handle open
5062 all the time (even then there are situations where it is
5063 not unique). Reputedly, there are at most 48 bits of info
5064 (on NTFS, presumably less on FAT). */
5065 fake_inode = info.nFileIndexHigh;
5066 fake_inode <<= 32;
5067 fake_inode += info.nFileIndexLow;
5068 serialnum = info.dwVolumeSerialNumber;
5069 fs_high = info.nFileSizeHigh;
5070 fs_low = info.nFileSizeLow;
5071 ctime = info.ftCreationTime;
5072 atime = info.ftLastAccessTime;
5073 wtime = info.ftLastWriteTime;
5074 fattrs = info.dwFileAttributes;
5076 else
5078 /* We don't go to Plan B here, because it's not clear that
5079 it's a good idea. The only known use case where
5080 CreateFile succeeds, but GetFileInformationByHandle fails
5081 (with ERROR_INVALID_FUNCTION) is for character devices
5082 such as NUL, PRN, etc. For these, switching to Plan B is
5083 a net loss, because we lose the character device
5084 attribute returned by GetFileType below (FindFirstFile
5085 doesn't set that bit in the attributes), and the other
5086 fields don't make sense for character devices anyway.
5087 Emacs doesn't really care for non-file entities in the
5088 context of l?stat, so neither do we. */
5090 /* w32err is assigned so one could put a breakpoint here and
5091 examine its value, when GetFileInformationByHandle
5092 fails. */
5093 DWORD w32err = GetLastError ();
5095 switch (w32err)
5097 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5098 errno = ENOENT;
5099 return -1;
5103 /* Test for a symlink before testing for a directory, since
5104 symlinks to directories have the directory bit set, but we
5105 don't want them to appear as directories. */
5106 if (is_a_symlink && !follow_symlinks)
5107 buf->st_mode = S_IFLNK;
5108 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5109 buf->st_mode = S_IFDIR;
5110 else
5112 DWORD ftype = GetFileType (fh);
5114 switch (ftype)
5116 case FILE_TYPE_DISK:
5117 buf->st_mode = S_IFREG;
5118 break;
5119 case FILE_TYPE_PIPE:
5120 buf->st_mode = S_IFIFO;
5121 break;
5122 case FILE_TYPE_CHAR:
5123 case FILE_TYPE_UNKNOWN:
5124 default:
5125 buf->st_mode = S_IFCHR;
5128 /* We produce the fallback owner and group data, based on the
5129 current user that runs Emacs, in the following cases:
5131 . caller didn't request owner and group info
5132 . this is Windows 9X
5133 . getting security by handle failed, and we need to produce
5134 information for the target of a symlink (this is better
5135 than producing a potentially misleading info about the
5136 symlink itself)
5138 If getting security by handle fails, and we don't need to
5139 resolve symlinks, we try getting security by name. */
5140 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5141 get_file_owner_and_group (NULL, buf);
5142 else
5144 psd = get_file_security_desc_by_handle (fh);
5145 if (psd)
5147 get_file_owner_and_group (psd, buf);
5148 LocalFree (psd);
5150 else if (!(is_a_symlink && follow_symlinks))
5152 psd = get_file_security_desc_by_name (name);
5153 get_file_owner_and_group (psd, buf);
5154 xfree (psd);
5156 else
5157 get_file_owner_and_group (NULL, buf);
5159 CloseHandle (fh);
5161 else
5163 no_true_file_attributes:
5164 /* Plan B: Either getting a handle on the file failed, or the
5165 caller explicitly asked us to not bother making this
5166 information more accurate.
5168 Implementation note: In Plan B, we never bother to resolve
5169 symlinks, even if we got here because we tried Plan A and
5170 failed. That's because, even if the caller asked for extra
5171 precision by setting Vw32_get_true_file_attributes to t,
5172 resolving symlinks requires acquiring a file handle to the
5173 symlink, which we already know will fail. And if the user
5174 did not ask for extra precision, resolving symlinks will fly
5175 in the face of that request, since the user then wants the
5176 lightweight version of the code. */
5177 rootdir = (path >= save_name + len - 1
5178 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5180 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5181 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5182 if (IS_DIRECTORY_SEP (r[0])
5183 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5184 r[1] = r[2] = '\0';
5186 /* Note: If NAME is a symlink to the root of a UNC volume
5187 (i.e. "\\SERVER"), we will not detect that here, and we will
5188 return data about the symlink as result of FindFirst below.
5189 This is unfortunate, but that marginal use case does not
5190 justify a call to chase_symlinks which would impose a penalty
5191 on all the other use cases. (We get here for symlinks to
5192 roots of UNC volumes because CreateFile above fails for them,
5193 unlike with symlinks to root directories X:\ of drives.) */
5194 if (is_unc_volume (name))
5196 fattrs = unc_volume_file_attributes (name);
5197 if (fattrs == -1)
5198 return -1;
5200 ctime = atime = wtime = utc_base_ft;
5202 else if (rootdir)
5204 /* Make sure root directories end in a slash. */
5205 if (!IS_DIRECTORY_SEP (name[len-1]))
5206 strcpy (name + len, "\\");
5207 if (GetDriveType (name) < 2)
5209 errno = ENOENT;
5210 return -1;
5213 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5214 ctime = atime = wtime = utc_base_ft;
5216 else
5218 int have_wfd = -1;
5220 /* Make sure non-root directories do NOT end in a slash,
5221 otherwise FindFirstFile might fail. */
5222 if (IS_DIRECTORY_SEP (name[len-1]))
5223 name[len - 1] = 0;
5225 /* (This is hacky, but helps when doing file completions on
5226 network drives.) Optimize by using information available from
5227 active readdir if possible. */
5228 len = strlen (dir_pathname);
5229 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5230 len--;
5231 if (dir_find_handle != INVALID_HANDLE_VALUE
5232 && last_dir_find_data != -1
5233 && !(is_a_symlink && follow_symlinks)
5234 /* The 2 file-name comparisons below support only ASCII
5235 characters, and will lose (compare not equal) when
5236 the file names include non-ASCII characters that are
5237 the same but for the case. However, doing this
5238 properly involves: (a) converting both file names to
5239 UTF-16, (b) lower-casing both names using CharLowerW,
5240 and (c) comparing the results; this would be quite a
5241 bit slower, whereas Plan B is for users who want
5242 lightweight albeit inaccurate version of 'stat'. */
5243 && c_strncasecmp (save_name, dir_pathname, len) == 0
5244 && IS_DIRECTORY_SEP (name[len])
5245 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5247 have_wfd = last_dir_find_data;
5248 /* This was the last entry returned by readdir. */
5249 if (last_dir_find_data == DIR_FIND_DATA_W)
5250 wfd_w = dir_find_data_w;
5251 else
5252 wfd_a = dir_find_data_a;
5254 else
5256 logon_network_drive (name);
5258 if (w32_unicode_filenames)
5260 filename_to_utf16 (name, name_w);
5261 fh = FindFirstFileW (name_w, &wfd_w);
5262 have_wfd = DIR_FIND_DATA_W;
5264 else
5266 filename_to_ansi (name, name_a);
5267 /* If NAME includes characters not representable by
5268 the current ANSI codepage, filename_to_ansi
5269 usually replaces them with a '?'. We don't want
5270 to let FindFirstFileA interpret those as wildcards,
5271 and "succeed", returning us data from some random
5272 file in the same directory. */
5273 if (_mbspbrk (name_a, "?"))
5274 fh = INVALID_HANDLE_VALUE;
5275 else
5276 fh = FindFirstFileA (name_a, &wfd_a);
5277 have_wfd = DIR_FIND_DATA_A;
5279 if (fh == INVALID_HANDLE_VALUE)
5281 errno = ENOENT;
5282 return -1;
5284 FindClose (fh);
5286 /* Note: if NAME is a symlink, the information we get from
5287 FindFirstFile is for the symlink, not its target. */
5288 if (have_wfd == DIR_FIND_DATA_W)
5290 fattrs = wfd_w.dwFileAttributes;
5291 ctime = wfd_w.ftCreationTime;
5292 atime = wfd_w.ftLastAccessTime;
5293 wtime = wfd_w.ftLastWriteTime;
5294 fs_high = wfd_w.nFileSizeHigh;
5295 fs_low = wfd_w.nFileSizeLow;
5297 else
5299 fattrs = wfd_a.dwFileAttributes;
5300 ctime = wfd_a.ftCreationTime;
5301 atime = wfd_a.ftLastAccessTime;
5302 wtime = wfd_a.ftLastWriteTime;
5303 fs_high = wfd_a.nFileSizeHigh;
5304 fs_low = wfd_a.nFileSizeLow;
5306 fake_inode = 0;
5307 nlinks = 1;
5308 serialnum = volume_info.serialnum;
5310 if (is_a_symlink && !follow_symlinks)
5311 buf->st_mode = S_IFLNK;
5312 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5313 buf->st_mode = S_IFDIR;
5314 else
5315 buf->st_mode = S_IFREG;
5317 get_file_owner_and_group (NULL, buf);
5320 buf->st_ino = fake_inode;
5322 buf->st_dev = serialnum;
5323 buf->st_rdev = serialnum;
5325 buf->st_size = fs_high;
5326 buf->st_size <<= 32;
5327 buf->st_size += fs_low;
5328 buf->st_nlink = nlinks;
5330 /* Convert timestamps to Unix format. */
5331 buf->st_mtime = convert_time (wtime);
5332 buf->st_atime = convert_time (atime);
5333 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5334 buf->st_ctime = convert_time (ctime);
5335 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5337 /* determine rwx permissions */
5338 if (is_a_symlink && !follow_symlinks)
5339 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5340 else
5342 if (fattrs & FILE_ATTRIBUTE_READONLY)
5343 permission = S_IREAD;
5344 else
5345 permission = S_IREAD | S_IWRITE;
5347 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5348 permission |= S_IEXEC;
5349 else if (is_exec (name))
5350 permission |= S_IEXEC;
5353 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5355 return 0;
5359 stat (const char * path, struct stat * buf)
5361 return stat_worker (path, buf, 1);
5365 lstat (const char * path, struct stat * buf)
5367 return stat_worker (path, buf, 0);
5371 fstatat (int fd, char const *name, struct stat *st, int flags)
5373 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5374 This is good enough for the current usage in Emacs, but is fragile.
5376 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5377 Gnulib does this and can serve as a model. */
5378 char fullname[MAX_UTF8_PATH];
5380 if (fd != AT_FDCWD)
5382 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5384 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5385 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5386 < 0)
5388 errno = ENAMETOOLONG;
5389 return -1;
5391 name = fullname;
5394 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5397 /* Provide fstat and utime as well as stat for consistent handling of
5398 file timestamps. */
5400 fstat (int desc, struct stat * buf)
5402 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5403 BY_HANDLE_FILE_INFORMATION info;
5404 unsigned __int64 fake_inode;
5405 int permission;
5407 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5409 case FILE_TYPE_DISK:
5410 buf->st_mode = S_IFREG;
5411 if (!GetFileInformationByHandle (fh, &info))
5413 errno = EACCES;
5414 return -1;
5416 break;
5417 case FILE_TYPE_PIPE:
5418 buf->st_mode = S_IFIFO;
5419 goto non_disk;
5420 case FILE_TYPE_CHAR:
5421 case FILE_TYPE_UNKNOWN:
5422 default:
5423 buf->st_mode = S_IFCHR;
5424 non_disk:
5425 memset (&info, 0, sizeof (info));
5426 info.dwFileAttributes = 0;
5427 info.ftCreationTime = utc_base_ft;
5428 info.ftLastAccessTime = utc_base_ft;
5429 info.ftLastWriteTime = utc_base_ft;
5432 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5433 buf->st_mode = S_IFDIR;
5435 buf->st_nlink = info.nNumberOfLinks;
5436 /* Might as well use file index to fake inode values, but this
5437 is not guaranteed to be unique unless we keep a handle open
5438 all the time (even then there are situations where it is
5439 not unique). Reputedly, there are at most 48 bits of info
5440 (on NTFS, presumably less on FAT). */
5441 fake_inode = info.nFileIndexHigh;
5442 fake_inode <<= 32;
5443 fake_inode += info.nFileIndexLow;
5445 /* MSVC defines _ino_t to be short; other libc's might not. */
5446 if (sizeof (buf->st_ino) == 2)
5447 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5448 else
5449 buf->st_ino = fake_inode;
5451 /* If the caller so requested, get the true file owner and group.
5452 Otherwise, consider the file to belong to the current user. */
5453 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5454 get_file_owner_and_group (NULL, buf);
5455 else
5457 PSECURITY_DESCRIPTOR psd = NULL;
5459 psd = get_file_security_desc_by_handle (fh);
5460 if (psd)
5462 get_file_owner_and_group (psd, buf);
5463 LocalFree (psd);
5465 else
5466 get_file_owner_and_group (NULL, buf);
5469 buf->st_dev = info.dwVolumeSerialNumber;
5470 buf->st_rdev = info.dwVolumeSerialNumber;
5472 buf->st_size = info.nFileSizeHigh;
5473 buf->st_size <<= 32;
5474 buf->st_size += info.nFileSizeLow;
5476 /* Convert timestamps to Unix format. */
5477 buf->st_mtime = convert_time (info.ftLastWriteTime);
5478 buf->st_atime = convert_time (info.ftLastAccessTime);
5479 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5480 buf->st_ctime = convert_time (info.ftCreationTime);
5481 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5483 /* determine rwx permissions */
5484 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5485 permission = S_IREAD;
5486 else
5487 permission = S_IREAD | S_IWRITE;
5489 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5490 permission |= S_IEXEC;
5491 else
5493 #if 0 /* no way of knowing the filename */
5494 char * p = strrchr (name, '.');
5495 if (p != NULL &&
5496 (xstrcasecmp (p, ".exe") == 0 ||
5497 xstrcasecmp (p, ".com") == 0 ||
5498 xstrcasecmp (p, ".bat") == 0 ||
5499 xstrcasecmp (p, ".cmd") == 0))
5500 permission |= S_IEXEC;
5501 #endif
5504 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5506 return 0;
5509 /* A version of 'utime' which handles directories as well as
5510 files. */
5513 utime (const char *name, struct utimbuf *times)
5515 struct utimbuf deftime;
5516 HANDLE fh;
5517 FILETIME mtime;
5518 FILETIME atime;
5520 if (times == NULL)
5522 deftime.modtime = deftime.actime = time (NULL);
5523 times = &deftime;
5526 if (w32_unicode_filenames)
5528 wchar_t name_utf16[MAX_PATH];
5530 if (filename_to_utf16 (name, name_utf16) != 0)
5531 return -1; /* errno set by filename_to_utf16 */
5533 /* Need write access to set times. */
5534 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5535 /* If NAME specifies a directory, FILE_SHARE_DELETE
5536 allows other processes to delete files inside it,
5537 while we have the directory open. */
5538 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5539 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5541 else
5543 char name_ansi[MAX_PATH];
5545 if (filename_to_ansi (name, name_ansi) != 0)
5546 return -1; /* errno set by filename_to_ansi */
5548 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5549 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5550 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5552 if (fh != INVALID_HANDLE_VALUE)
5554 convert_from_time_t (times->actime, &atime);
5555 convert_from_time_t (times->modtime, &mtime);
5556 if (!SetFileTime (fh, NULL, &atime, &mtime))
5558 CloseHandle (fh);
5559 errno = EACCES;
5560 return -1;
5562 CloseHandle (fh);
5564 else
5566 DWORD err = GetLastError ();
5568 switch (err)
5570 case ERROR_FILE_NOT_FOUND:
5571 case ERROR_PATH_NOT_FOUND:
5572 case ERROR_INVALID_DRIVE:
5573 case ERROR_BAD_NETPATH:
5574 case ERROR_DEV_NOT_EXIST:
5575 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5576 file name includes ?s, i.e. translation to ANSI failed. */
5577 case ERROR_INVALID_NAME:
5578 errno = ENOENT;
5579 break;
5580 case ERROR_TOO_MANY_OPEN_FILES:
5581 errno = ENFILE;
5582 break;
5583 case ERROR_ACCESS_DENIED:
5584 case ERROR_SHARING_VIOLATION:
5585 errno = EACCES;
5586 break;
5587 default:
5588 errno = EINVAL;
5589 break;
5591 return -1;
5593 return 0;
5597 sys_umask (int mode)
5599 static int current_mask;
5600 int retval, arg = 0;
5602 /* The only bit we really support is the write bit. Files are
5603 always readable on MS-Windows, and the execute bit does not exist
5604 at all. */
5605 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5606 to prevent access by other users on NTFS. */
5607 if ((mode & S_IWRITE) != 0)
5608 arg |= S_IWRITE;
5610 retval = _umask (arg);
5611 /* Merge into the return value the bits they've set the last time,
5612 which msvcrt.dll ignores and never returns. Emacs insists on its
5613 notion of mask being identical to what we return. */
5614 retval |= (current_mask & ~S_IWRITE);
5615 current_mask = mode;
5617 return retval;
5621 /* Symlink-related functions. */
5622 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5623 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5624 #endif
5627 symlink (char const *filename, char const *linkname)
5629 char linkfn[MAX_UTF8_PATH], *tgtfn;
5630 DWORD flags = 0;
5631 int dir_access, filename_ends_in_slash;
5633 /* Diagnostics follows Posix as much as possible. */
5634 if (filename == NULL || linkname == NULL)
5636 errno = EFAULT;
5637 return -1;
5639 if (!*filename)
5641 errno = ENOENT;
5642 return -1;
5644 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5646 errno = ENAMETOOLONG;
5647 return -1;
5650 strcpy (linkfn, map_w32_filename (linkname, NULL));
5651 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5653 errno = EPERM;
5654 return -1;
5657 /* Note: since empty FILENAME was already rejected, we can safely
5658 refer to FILENAME[1]. */
5659 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5661 /* Non-absolute FILENAME is understood as being relative to
5662 LINKNAME's directory. We need to prepend that directory to
5663 FILENAME to get correct results from faccessat below, since
5664 otherwise it will interpret FILENAME relative to the
5665 directory where the Emacs process runs. Note that
5666 make-symbolic-link always makes sure LINKNAME is a fully
5667 expanded file name. */
5668 char tem[MAX_UTF8_PATH];
5669 char *p = linkfn + strlen (linkfn);
5671 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5672 p--;
5673 if (p > linkfn)
5674 strncpy (tem, linkfn, p - linkfn);
5675 strcpy (tem + (p - linkfn), filename);
5676 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5678 else
5679 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5681 /* Since Windows distinguishes between symlinks to directories and
5682 to files, we provide a kludgy feature: if FILENAME doesn't
5683 exist, but ends in a slash, we create a symlink to directory. If
5684 FILENAME exists and is a directory, we always create a symlink to
5685 directory. */
5686 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5687 if (dir_access == 0 || filename_ends_in_slash)
5688 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5690 tgtfn = (char *)map_w32_filename (filename, NULL);
5691 if (filename_ends_in_slash)
5692 tgtfn[strlen (tgtfn) - 1] = '\0';
5694 errno = 0;
5695 if (!create_symbolic_link (linkfn, tgtfn, flags))
5697 /* ENOSYS is set by create_symbolic_link, when it detects that
5698 the OS doesn't support the CreateSymbolicLink API. */
5699 if (errno != ENOSYS)
5701 DWORD w32err = GetLastError ();
5703 switch (w32err)
5705 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5706 TGTFN point to the same file name, go figure. */
5707 case ERROR_SUCCESS:
5708 case ERROR_FILE_EXISTS:
5709 errno = EEXIST;
5710 break;
5711 case ERROR_ACCESS_DENIED:
5712 errno = EACCES;
5713 break;
5714 case ERROR_FILE_NOT_FOUND:
5715 case ERROR_PATH_NOT_FOUND:
5716 case ERROR_BAD_NETPATH:
5717 case ERROR_INVALID_REPARSE_DATA:
5718 errno = ENOENT;
5719 break;
5720 case ERROR_DIRECTORY:
5721 errno = EISDIR;
5722 break;
5723 case ERROR_PRIVILEGE_NOT_HELD:
5724 case ERROR_NOT_ALL_ASSIGNED:
5725 errno = EPERM;
5726 break;
5727 case ERROR_DISK_FULL:
5728 errno = ENOSPC;
5729 break;
5730 default:
5731 errno = EINVAL;
5732 break;
5735 return -1;
5737 return 0;
5740 /* A quick inexpensive test of whether FILENAME identifies a file that
5741 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5742 must already be in the normalized form returned by
5743 map_w32_filename. If the symlink is to a directory, the
5744 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5746 Note: for repeated operations on many files, it is best to test
5747 whether the underlying volume actually supports symlinks, by
5748 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5749 avoid the call to this function if it doesn't. That's because the
5750 call to GetFileAttributes takes a non-negligible time, especially
5751 on non-local or removable filesystems. See stat_worker for an
5752 example of how to do that. */
5753 static int
5754 is_symlink (const char *filename)
5756 DWORD attrs;
5757 wchar_t filename_w[MAX_PATH];
5758 char filename_a[MAX_PATH];
5759 WIN32_FIND_DATAW wfdw;
5760 WIN32_FIND_DATAA wfda;
5761 HANDLE fh;
5762 int attrs_mean_symlink;
5764 if (w32_unicode_filenames)
5766 filename_to_utf16 (filename, filename_w);
5767 attrs = GetFileAttributesW (filename_w);
5769 else
5771 filename_to_ansi (filename, filename_a);
5772 attrs = GetFileAttributesA (filename_a);
5774 if (attrs == -1)
5776 DWORD w32err = GetLastError ();
5778 switch (w32err)
5780 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5781 break;
5782 case ERROR_ACCESS_DENIED:
5783 errno = EACCES;
5784 break;
5785 case ERROR_FILE_NOT_FOUND:
5786 case ERROR_PATH_NOT_FOUND:
5787 default:
5788 errno = ENOENT;
5789 break;
5791 return 0;
5793 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5794 return 0;
5795 logon_network_drive (filename);
5796 if (w32_unicode_filenames)
5798 fh = FindFirstFileW (filename_w, &wfdw);
5799 attrs_mean_symlink =
5800 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5801 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5802 if (attrs_mean_symlink)
5803 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5805 else if (_mbspbrk (filename_a, "?"))
5807 /* filename_to_ansi failed to convert the file name. */
5808 errno = ENOENT;
5809 return 0;
5811 else
5813 fh = FindFirstFileA (filename_a, &wfda);
5814 attrs_mean_symlink =
5815 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5816 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5817 if (attrs_mean_symlink)
5818 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5820 if (fh == INVALID_HANDLE_VALUE)
5821 return 0;
5822 FindClose (fh);
5823 return attrs_mean_symlink;
5826 /* If NAME identifies a symbolic link, copy into BUF the file name of
5827 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5828 null-terminate the target name, even if it fits. Return the number
5829 of bytes copied, or -1 if NAME is not a symlink or any error was
5830 encountered while resolving it. The file name copied into BUF is
5831 encoded in the current ANSI codepage. */
5832 ssize_t
5833 readlink (const char *name, char *buf, size_t buf_size)
5835 const char *path;
5836 TOKEN_PRIVILEGES privs;
5837 int restore_privs = 0;
5838 HANDLE sh;
5839 ssize_t retval;
5840 char resolved[MAX_UTF8_PATH];
5842 if (name == NULL)
5844 errno = EFAULT;
5845 return -1;
5847 if (!*name)
5849 errno = ENOENT;
5850 return -1;
5853 path = map_w32_filename (name, NULL);
5855 if (strlen (path) > MAX_UTF8_PATH)
5857 errno = ENAMETOOLONG;
5858 return -1;
5861 errno = 0;
5862 if (is_windows_9x () == TRUE
5863 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5864 || !is_symlink (path))
5866 if (!errno)
5867 errno = EINVAL; /* not a symlink */
5868 return -1;
5871 /* Done with simple tests, now we're in for some _real_ work. */
5872 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5873 restore_privs = 1;
5874 /* Implementation note: From here and onward, don't return early,
5875 since that will fail to restore the original set of privileges of
5876 the calling thread. */
5878 retval = -1; /* not too optimistic, are we? */
5880 /* Note: In the next call to CreateFile, we use zero as the 2nd
5881 argument because, when the symlink is a hidden/system file,
5882 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5883 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5884 and directory symlinks. */
5885 if (w32_unicode_filenames)
5887 wchar_t path_w[MAX_PATH];
5889 filename_to_utf16 (path, path_w);
5890 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5891 FILE_FLAG_OPEN_REPARSE_POINT
5892 | FILE_FLAG_BACKUP_SEMANTICS,
5893 NULL);
5895 else
5897 char path_a[MAX_PATH];
5899 filename_to_ansi (path, path_a);
5900 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5901 FILE_FLAG_OPEN_REPARSE_POINT
5902 | FILE_FLAG_BACKUP_SEMANTICS,
5903 NULL);
5905 if (sh != INVALID_HANDLE_VALUE)
5907 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5908 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5909 DWORD retbytes;
5911 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5912 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5913 &retbytes, NULL))
5914 errno = EIO;
5915 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5916 errno = EINVAL;
5917 else
5919 /* Copy the link target name, in wide characters, from
5920 reparse_data, then convert it to multibyte encoding in
5921 the current locale's codepage. */
5922 WCHAR *lwname;
5923 size_t lname_size;
5924 USHORT lwname_len =
5925 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5926 WCHAR *lwname_src =
5927 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5928 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5929 size_t size_to_copy = buf_size;
5931 /* According to MSDN, PrintNameLength does not include the
5932 terminating null character. */
5933 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5934 memcpy (lwname, lwname_src, lwname_len);
5935 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5936 filename_from_utf16 (lwname, resolved);
5937 dostounix_filename (resolved);
5938 lname_size = strlen (resolved) + 1;
5939 if (lname_size <= buf_size)
5940 size_to_copy = lname_size;
5941 strncpy (buf, resolved, size_to_copy);
5942 /* Success! */
5943 retval = size_to_copy;
5945 CloseHandle (sh);
5947 else
5949 /* CreateFile failed. */
5950 DWORD w32err2 = GetLastError ();
5952 switch (w32err2)
5954 case ERROR_FILE_NOT_FOUND:
5955 case ERROR_PATH_NOT_FOUND:
5956 errno = ENOENT;
5957 break;
5958 case ERROR_ACCESS_DENIED:
5959 case ERROR_TOO_MANY_OPEN_FILES:
5960 errno = EACCES;
5961 break;
5962 default:
5963 errno = EPERM;
5964 break;
5967 if (restore_privs)
5969 restore_privilege (&privs);
5970 revert_to_self ();
5973 return retval;
5976 ssize_t
5977 readlinkat (int fd, char const *name, char *buffer,
5978 size_t buffer_size)
5980 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5981 as in fstatat. FIXME: Add proper support for readlinkat. */
5982 char fullname[MAX_UTF8_PATH];
5984 if (fd != AT_FDCWD)
5986 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5987 < 0)
5989 errno = ENAMETOOLONG;
5990 return -1;
5992 name = fullname;
5995 return readlink (name, buffer, buffer_size);
5998 /* If FILE is a symlink, return its target (stored in a static
5999 buffer); otherwise return FILE.
6001 This function repeatedly resolves symlinks in the last component of
6002 a chain of symlink file names, as in foo -> bar -> baz -> ...,
6003 until it arrives at a file whose last component is not a symlink,
6004 or some error occurs. It returns the target of the last
6005 successfully resolved symlink in the chain. If it succeeds to
6006 resolve even a single symlink, the value returned is an absolute
6007 file name with backslashes (result of GetFullPathName). By
6008 contrast, if the original FILE is returned, it is unaltered.
6010 Note: This function can set errno even if it succeeds.
6012 Implementation note: we only resolve the last portion ("basename")
6013 of the argument FILE and of each following file in the chain,
6014 disregarding any possible symlinks in its leading directories.
6015 This is because Windows system calls and library functions
6016 transparently resolve symlinks in leading directories and return
6017 correct information, as long as the basename is not a symlink. */
6018 static char *
6019 chase_symlinks (const char *file)
6021 static char target[MAX_UTF8_PATH];
6022 char link[MAX_UTF8_PATH];
6023 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
6024 char target_a[MAX_PATH], link_a[MAX_PATH];
6025 ssize_t res, link_len;
6026 int loop_count = 0;
6028 if (is_windows_9x () == TRUE || !is_symlink (file))
6029 return (char *)file;
6031 if (w32_unicode_filenames)
6033 wchar_t file_w[MAX_PATH];
6035 filename_to_utf16 (file, file_w);
6036 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
6037 return (char *)file;
6038 filename_from_utf16 (link_w, link);
6040 else
6042 char file_a[MAX_PATH];
6044 filename_to_ansi (file, file_a);
6045 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6046 return (char *)file;
6047 filename_from_ansi (link_a, link);
6049 link_len = strlen (link);
6051 target[0] = '\0';
6052 do {
6054 /* Remove trailing slashes, as we want to resolve the last
6055 non-trivial part of the link name. */
6056 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6057 link[link_len--] = '\0';
6059 res = readlink (link, target, MAX_UTF8_PATH);
6060 if (res > 0)
6062 target[res] = '\0';
6063 if (!(IS_DEVICE_SEP (target[1])
6064 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6066 /* Target is relative. Append it to the directory part of
6067 the symlink, then copy the result back to target. */
6068 char *p = link + link_len;
6070 while (p > link && !IS_ANY_SEP (p[-1]))
6071 p--;
6072 strcpy (p, target);
6073 strcpy (target, link);
6075 /* Resolve any "." and ".." to get a fully-qualified file name
6076 in link[] again. */
6077 if (w32_unicode_filenames)
6079 filename_to_utf16 (target, target_w);
6080 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6081 if (link_len > 0)
6082 filename_from_utf16 (link_w, link);
6084 else
6086 filename_to_ansi (target, target_a);
6087 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6088 if (link_len > 0)
6089 filename_from_ansi (link_a, link);
6091 link_len = strlen (link);
6093 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6095 if (loop_count > 100)
6096 errno = ELOOP;
6098 if (target[0] == '\0') /* not a single call to readlink succeeded */
6099 return (char *)file;
6100 return target;
6104 /* Posix ACL emulation. */
6107 acl_valid (acl_t acl)
6109 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6112 char *
6113 acl_to_text (acl_t acl, ssize_t *size)
6115 LPTSTR str_acl;
6116 SECURITY_INFORMATION flags =
6117 OWNER_SECURITY_INFORMATION |
6118 GROUP_SECURITY_INFORMATION |
6119 DACL_SECURITY_INFORMATION;
6120 char *retval = NULL;
6121 ULONG local_size;
6122 int e = errno;
6124 errno = 0;
6126 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6128 errno = e;
6129 /* We don't want to mix heaps, so we duplicate the string in our
6130 heap and free the one allocated by the API. */
6131 retval = xstrdup (str_acl);
6132 if (size)
6133 *size = local_size;
6134 LocalFree (str_acl);
6136 else if (errno != ENOTSUP)
6137 errno = EINVAL;
6139 return retval;
6142 acl_t
6143 acl_from_text (const char *acl_str)
6145 PSECURITY_DESCRIPTOR psd, retval = NULL;
6146 ULONG sd_size;
6147 int e = errno;
6149 errno = 0;
6151 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6153 errno = e;
6154 retval = xmalloc (sd_size);
6155 memcpy (retval, psd, sd_size);
6156 LocalFree (psd);
6158 else if (errno != ENOTSUP)
6159 errno = EINVAL;
6161 return retval;
6165 acl_free (void *ptr)
6167 xfree (ptr);
6168 return 0;
6171 acl_t
6172 acl_get_file (const char *fname, acl_type_t type)
6174 PSECURITY_DESCRIPTOR psd = NULL;
6175 const char *filename;
6177 if (type == ACL_TYPE_ACCESS)
6179 DWORD sd_len, err;
6180 SECURITY_INFORMATION si =
6181 OWNER_SECURITY_INFORMATION |
6182 GROUP_SECURITY_INFORMATION |
6183 DACL_SECURITY_INFORMATION ;
6184 int e = errno;
6186 filename = map_w32_filename (fname, NULL);
6187 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6188 fname = chase_symlinks (filename);
6189 else
6190 fname = filename;
6192 errno = 0;
6193 if (!get_file_security (fname, si, psd, 0, &sd_len)
6194 && errno != ENOTSUP)
6196 err = GetLastError ();
6197 if (err == ERROR_INSUFFICIENT_BUFFER)
6199 psd = xmalloc (sd_len);
6200 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6202 xfree (psd);
6203 errno = EIO;
6204 psd = NULL;
6207 else if (err == ERROR_FILE_NOT_FOUND
6208 || err == ERROR_PATH_NOT_FOUND
6209 /* ERROR_INVALID_NAME is what we get if
6210 w32-unicode-filenames is nil and the file cannot
6211 be encoded in the current ANSI codepage. */
6212 || err == ERROR_INVALID_NAME)
6213 errno = ENOENT;
6214 else
6215 errno = EIO;
6217 else if (!errno)
6218 errno = e;
6220 else if (type != ACL_TYPE_DEFAULT)
6221 errno = EINVAL;
6223 return psd;
6227 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6229 TOKEN_PRIVILEGES old1, old2;
6230 DWORD err;
6231 int st = 0, retval = -1;
6232 SECURITY_INFORMATION flags = 0;
6233 PSID psidOwner, psidGroup;
6234 PACL pacl;
6235 BOOL dflt;
6236 BOOL dacl_present;
6237 int e;
6238 const char *filename;
6240 if (acl_valid (acl) != 0
6241 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6243 errno = EINVAL;
6244 return -1;
6247 if (type == ACL_TYPE_DEFAULT)
6249 errno = ENOSYS;
6250 return -1;
6253 filename = map_w32_filename (fname, NULL);
6254 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6255 fname = chase_symlinks (filename);
6256 else
6257 fname = filename;
6259 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6260 &dflt)
6261 && psidOwner)
6262 flags |= OWNER_SECURITY_INFORMATION;
6263 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6264 &dflt)
6265 && psidGroup)
6266 flags |= GROUP_SECURITY_INFORMATION;
6267 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6268 &pacl, &dflt)
6269 && dacl_present)
6270 flags |= DACL_SECURITY_INFORMATION;
6271 if (!flags)
6272 return 0;
6274 /* According to KB-245153, setting the owner will succeed if either:
6275 (1) the caller is the user who will be the new owner, and has the
6276 SE_TAKE_OWNERSHIP privilege, or
6277 (2) the caller has the SE_RESTORE privilege, in which case she can
6278 set any valid user or group as the owner
6280 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6281 privileges, and disregard any failures in obtaining them. If
6282 these privileges cannot be obtained, and do not already exist in
6283 the calling thread's security token, this function could fail
6284 with EPERM. */
6285 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6286 st++;
6287 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6288 st++;
6290 e = errno;
6291 errno = 0;
6292 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6293 DACL inheritance is involved, but it seems to preserve ownership
6294 better than SetNamedSecurityInfo, which is important e.g., in
6295 copy-file. */
6296 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6298 err = GetLastError ();
6300 if (errno != ENOTSUP)
6301 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6302 psidOwner, psidGroup, pacl, NULL);
6304 else
6305 err = ERROR_SUCCESS;
6306 if (err != ERROR_SUCCESS)
6308 if (errno == ENOTSUP)
6310 else if (err == ERROR_INVALID_OWNER
6311 || err == ERROR_NOT_ALL_ASSIGNED
6312 || err == ERROR_ACCESS_DENIED)
6314 /* Maybe the requested ACL and the one the file already has
6315 are identical, in which case we can silently ignore the
6316 failure. (And no, Windows doesn't.) */
6317 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6319 errno = EPERM;
6320 if (current_acl)
6322 char *acl_from = acl_to_text (current_acl, NULL);
6323 char *acl_to = acl_to_text (acl, NULL);
6325 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6327 retval = 0;
6328 errno = e;
6330 if (acl_from)
6331 acl_free (acl_from);
6332 if (acl_to)
6333 acl_free (acl_to);
6334 acl_free (current_acl);
6337 else if (err == ERROR_FILE_NOT_FOUND
6338 || err == ERROR_PATH_NOT_FOUND
6339 /* ERROR_INVALID_NAME is what we get if
6340 w32-unicode-filenames is nil and the file cannot be
6341 encoded in the current ANSI codepage. */
6342 || err == ERROR_INVALID_NAME)
6343 errno = ENOENT;
6344 else
6345 errno = EACCES;
6347 else
6349 retval = 0;
6350 errno = e;
6353 if (st)
6355 if (st >= 2)
6356 restore_privilege (&old2);
6357 restore_privilege (&old1);
6358 revert_to_self ();
6361 return retval;
6365 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6366 have a fixed max size for file names, so we don't need the kind of
6367 alloc/malloc/realloc dance the gnulib version does. We also don't
6368 support FD-relative symlinks. */
6369 char *
6370 careadlinkat (int fd, char const *filename,
6371 char *buffer, size_t buffer_size,
6372 struct allocator const *alloc,
6373 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6375 char linkname[MAX_UTF8_PATH];
6376 ssize_t link_size;
6378 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6380 if (link_size > 0)
6382 char *retval = buffer;
6384 linkname[link_size++] = '\0';
6385 if (link_size > buffer_size)
6386 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6387 if (retval)
6388 memcpy (retval, linkname, link_size);
6390 return retval;
6392 return NULL;
6396 w32_copy_file (const char *from, const char *to,
6397 int keep_time, int preserve_ownership, int copy_acls)
6399 acl_t acl = NULL;
6400 BOOL copy_result;
6401 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6402 char from_a[MAX_PATH], to_a[MAX_PATH];
6404 /* We ignore preserve_ownership for now. */
6405 preserve_ownership = preserve_ownership;
6407 if (copy_acls)
6409 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6410 if (acl == NULL && acl_errno_valid (errno))
6411 return -2;
6413 if (w32_unicode_filenames)
6415 filename_to_utf16 (from, from_w);
6416 filename_to_utf16 (to, to_w);
6417 copy_result = CopyFileW (from_w, to_w, FALSE);
6419 else
6421 filename_to_ansi (from, from_a);
6422 filename_to_ansi (to, to_a);
6423 copy_result = CopyFileA (from_a, to_a, FALSE);
6425 if (!copy_result)
6427 /* CopyFile doesn't set errno when it fails. By far the most
6428 "popular" reason is that the target is read-only. */
6429 DWORD err = GetLastError ();
6431 switch (err)
6433 case ERROR_FILE_NOT_FOUND:
6434 errno = ENOENT;
6435 break;
6436 case ERROR_ACCESS_DENIED:
6437 errno = EACCES;
6438 break;
6439 case ERROR_ENCRYPTION_FAILED:
6440 errno = EIO;
6441 break;
6442 default:
6443 errno = EPERM;
6444 break;
6447 if (acl)
6448 acl_free (acl);
6449 return -1;
6451 /* CopyFile retains the timestamp by default. However, see
6452 "Community Additions" for CopyFile: it sounds like that is not
6453 entirely true. Testing on Windows XP confirms that modified time
6454 is copied, but creation and last-access times are not.
6455 FIXME? */
6456 else if (!keep_time)
6458 struct timespec now;
6459 DWORD attributes;
6461 if (w32_unicode_filenames)
6463 /* Ensure file is writable while its times are set. */
6464 attributes = GetFileAttributesW (to_w);
6465 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6466 now = current_timespec ();
6467 if (set_file_times (-1, to, now, now))
6469 /* Restore original attributes. */
6470 SetFileAttributesW (to_w, attributes);
6471 if (acl)
6472 acl_free (acl);
6473 return -3;
6475 /* Restore original attributes. */
6476 SetFileAttributesW (to_w, attributes);
6478 else
6480 attributes = GetFileAttributesA (to_a);
6481 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6482 now = current_timespec ();
6483 if (set_file_times (-1, to, now, now))
6485 SetFileAttributesA (to_a, attributes);
6486 if (acl)
6487 acl_free (acl);
6488 return -3;
6490 SetFileAttributesA (to_a, attributes);
6493 if (acl != NULL)
6495 bool fail =
6496 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6497 acl_free (acl);
6498 if (fail && acl_errno_valid (errno))
6499 return -4;
6502 return 0;
6506 /* Support for browsing other processes and their attributes. See
6507 process.c for the Lisp bindings. */
6509 /* Helper wrapper functions. */
6511 static HANDLE WINAPI
6512 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6514 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6516 if (g_b_init_create_toolhelp32_snapshot == 0)
6518 g_b_init_create_toolhelp32_snapshot = 1;
6519 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6520 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6521 "CreateToolhelp32Snapshot");
6523 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6525 return INVALID_HANDLE_VALUE;
6527 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6530 static BOOL WINAPI
6531 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6533 static Process32First_Proc s_pfn_Process32_First = NULL;
6535 if (g_b_init_process32_first == 0)
6537 g_b_init_process32_first = 1;
6538 s_pfn_Process32_First = (Process32First_Proc)
6539 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6540 "Process32First");
6542 if (s_pfn_Process32_First == NULL)
6544 return FALSE;
6546 return (s_pfn_Process32_First (hSnapshot, lppe));
6549 static BOOL WINAPI
6550 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6552 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6554 if (g_b_init_process32_next == 0)
6556 g_b_init_process32_next = 1;
6557 s_pfn_Process32_Next = (Process32Next_Proc)
6558 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6559 "Process32Next");
6561 if (s_pfn_Process32_Next == NULL)
6563 return FALSE;
6565 return (s_pfn_Process32_Next (hSnapshot, lppe));
6568 static BOOL WINAPI
6569 open_thread_token (HANDLE ThreadHandle,
6570 DWORD DesiredAccess,
6571 BOOL OpenAsSelf,
6572 PHANDLE TokenHandle)
6574 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6575 HMODULE hm_advapi32 = NULL;
6576 if (is_windows_9x () == TRUE)
6578 SetLastError (ERROR_NOT_SUPPORTED);
6579 return FALSE;
6581 if (g_b_init_open_thread_token == 0)
6583 g_b_init_open_thread_token = 1;
6584 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6585 s_pfn_Open_Thread_Token =
6586 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6588 if (s_pfn_Open_Thread_Token == NULL)
6590 SetLastError (ERROR_NOT_SUPPORTED);
6591 return FALSE;
6593 return (
6594 s_pfn_Open_Thread_Token (
6595 ThreadHandle,
6596 DesiredAccess,
6597 OpenAsSelf,
6598 TokenHandle)
6602 static BOOL WINAPI
6603 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6605 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6606 HMODULE hm_advapi32 = NULL;
6607 if (is_windows_9x () == TRUE)
6609 return FALSE;
6611 if (g_b_init_impersonate_self == 0)
6613 g_b_init_impersonate_self = 1;
6614 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6615 s_pfn_Impersonate_Self =
6616 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6618 if (s_pfn_Impersonate_Self == NULL)
6620 return FALSE;
6622 return s_pfn_Impersonate_Self (ImpersonationLevel);
6625 static BOOL WINAPI
6626 revert_to_self (void)
6628 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6629 HMODULE hm_advapi32 = NULL;
6630 if (is_windows_9x () == TRUE)
6632 return FALSE;
6634 if (g_b_init_revert_to_self == 0)
6636 g_b_init_revert_to_self = 1;
6637 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6638 s_pfn_Revert_To_Self =
6639 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6641 if (s_pfn_Revert_To_Self == NULL)
6643 return FALSE;
6645 return s_pfn_Revert_To_Self ();
6648 static BOOL WINAPI
6649 get_process_memory_info (HANDLE h_proc,
6650 PPROCESS_MEMORY_COUNTERS mem_counters,
6651 DWORD bufsize)
6653 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6654 HMODULE hm_psapi = NULL;
6655 if (is_windows_9x () == TRUE)
6657 return FALSE;
6659 if (g_b_init_get_process_memory_info == 0)
6661 g_b_init_get_process_memory_info = 1;
6662 hm_psapi = LoadLibrary ("Psapi.dll");
6663 if (hm_psapi)
6664 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6665 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6667 if (s_pfn_Get_Process_Memory_Info == NULL)
6669 return FALSE;
6671 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6674 static BOOL WINAPI
6675 get_process_working_set_size (HANDLE h_proc,
6676 PSIZE_T minrss,
6677 PSIZE_T maxrss)
6679 static GetProcessWorkingSetSize_Proc
6680 s_pfn_Get_Process_Working_Set_Size = NULL;
6682 if (is_windows_9x () == TRUE)
6684 return FALSE;
6686 if (g_b_init_get_process_working_set_size == 0)
6688 g_b_init_get_process_working_set_size = 1;
6689 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6690 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6691 "GetProcessWorkingSetSize");
6693 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6695 return FALSE;
6697 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6700 static BOOL WINAPI
6701 global_memory_status (MEMORYSTATUS *buf)
6703 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6705 if (is_windows_9x () == TRUE)
6707 return FALSE;
6709 if (g_b_init_global_memory_status == 0)
6711 g_b_init_global_memory_status = 1;
6712 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6713 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6714 "GlobalMemoryStatus");
6716 if (s_pfn_Global_Memory_Status == NULL)
6718 return FALSE;
6720 return s_pfn_Global_Memory_Status (buf);
6723 static BOOL WINAPI
6724 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6726 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6728 if (is_windows_9x () == TRUE)
6730 return FALSE;
6732 if (g_b_init_global_memory_status_ex == 0)
6734 g_b_init_global_memory_status_ex = 1;
6735 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6736 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6737 "GlobalMemoryStatusEx");
6739 if (s_pfn_Global_Memory_Status_Ex == NULL)
6741 return FALSE;
6743 return s_pfn_Global_Memory_Status_Ex (buf);
6746 Lisp_Object
6747 list_system_processes (void)
6749 Lisp_Object proclist = Qnil;
6750 HANDLE h_snapshot;
6752 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6754 if (h_snapshot != INVALID_HANDLE_VALUE)
6756 PROCESSENTRY32 proc_entry;
6757 DWORD proc_id;
6758 BOOL res;
6760 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6761 for (res = process32_first (h_snapshot, &proc_entry); res;
6762 res = process32_next (h_snapshot, &proc_entry))
6764 proc_id = proc_entry.th32ProcessID;
6765 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6768 CloseHandle (h_snapshot);
6769 proclist = Fnreverse (proclist);
6772 return proclist;
6775 static int
6776 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6778 TOKEN_PRIVILEGES priv;
6779 DWORD priv_size = sizeof (priv);
6780 DWORD opriv_size = sizeof (*old_priv);
6781 HANDLE h_token = NULL;
6782 HANDLE h_thread = GetCurrentThread ();
6783 int ret_val = 0;
6784 BOOL res;
6786 res = open_thread_token (h_thread,
6787 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6788 FALSE, &h_token);
6789 if (!res && GetLastError () == ERROR_NO_TOKEN)
6791 if (impersonate_self (SecurityImpersonation))
6792 res = open_thread_token (h_thread,
6793 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6794 FALSE, &h_token);
6796 if (res)
6798 priv.PrivilegeCount = 1;
6799 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6800 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6801 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6802 old_priv, &opriv_size)
6803 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6804 ret_val = 1;
6806 if (h_token)
6807 CloseHandle (h_token);
6809 return ret_val;
6812 static int
6813 restore_privilege (TOKEN_PRIVILEGES *priv)
6815 DWORD priv_size = sizeof (*priv);
6816 HANDLE h_token = NULL;
6817 int ret_val = 0;
6819 if (open_thread_token (GetCurrentThread (),
6820 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6821 FALSE, &h_token))
6823 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6824 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6825 ret_val = 1;
6827 if (h_token)
6828 CloseHandle (h_token);
6830 return ret_val;
6833 static Lisp_Object
6834 ltime (ULONGLONG time_100ns)
6836 ULONGLONG time_sec = time_100ns / 10000000;
6837 int subsec = time_100ns % 10000000;
6838 return list4i (time_sec >> 16, time_sec & 0xffff,
6839 subsec / 10, subsec % 10 * 100000);
6842 #define U64_TO_LISP_TIME(time) ltime (time)
6844 static int
6845 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6846 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6847 double *pcpu)
6849 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6850 ULONGLONG tem1, tem2, tem3, tem;
6852 if (!h_proc
6853 || !get_process_times_fn
6854 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6855 &ft_kernel, &ft_user))
6856 return 0;
6858 GetSystemTimeAsFileTime (&ft_current);
6860 FILETIME_TO_U64 (tem1, ft_kernel);
6861 *stime = U64_TO_LISP_TIME (tem1);
6863 FILETIME_TO_U64 (tem2, ft_user);
6864 *utime = U64_TO_LISP_TIME (tem2);
6866 tem3 = tem1 + tem2;
6867 *ttime = U64_TO_LISP_TIME (tem3);
6869 FILETIME_TO_U64 (tem, ft_creation);
6870 /* Process no 4 (System) returns zero creation time. */
6871 if (tem)
6872 tem -= utc_base;
6873 *ctime = U64_TO_LISP_TIME (tem);
6875 if (tem)
6877 FILETIME_TO_U64 (tem3, ft_current);
6878 tem = (tem3 - utc_base) - tem;
6880 *etime = U64_TO_LISP_TIME (tem);
6882 if (tem)
6884 *pcpu = 100.0 * (tem1 + tem2) / tem;
6885 if (*pcpu > 100)
6886 *pcpu = 100.0;
6888 else
6889 *pcpu = 0;
6891 return 1;
6894 Lisp_Object
6895 system_process_attributes (Lisp_Object pid)
6897 Lisp_Object attrs = Qnil;
6898 Lisp_Object cmd_str, decoded_cmd, tem;
6899 HANDLE h_snapshot, h_proc;
6900 DWORD proc_id;
6901 int found_proc = 0;
6902 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6903 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6904 DWORD glength = sizeof (gname);
6905 HANDLE token = NULL;
6906 SID_NAME_USE user_type;
6907 unsigned char *buf = NULL;
6908 DWORD blen = 0;
6909 TOKEN_USER user_token;
6910 TOKEN_PRIMARY_GROUP group_token;
6911 unsigned euid;
6912 unsigned egid;
6913 PROCESS_MEMORY_COUNTERS mem;
6914 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6915 SIZE_T minrss, maxrss;
6916 MEMORYSTATUS memst;
6917 MEMORY_STATUS_EX memstex;
6918 double totphys = 0.0;
6919 Lisp_Object ctime, stime, utime, etime, ttime;
6920 double pcpu;
6921 BOOL result = FALSE;
6923 CHECK_NUMBER_OR_FLOAT (pid);
6924 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6926 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6928 if (h_snapshot != INVALID_HANDLE_VALUE)
6930 PROCESSENTRY32 pe;
6931 BOOL res;
6933 pe.dwSize = sizeof (PROCESSENTRY32);
6934 for (res = process32_first (h_snapshot, &pe); res;
6935 res = process32_next (h_snapshot, &pe))
6937 if (proc_id == pe.th32ProcessID)
6939 if (proc_id == 0)
6940 decoded_cmd = build_string ("Idle");
6941 else
6943 /* Decode the command name from locale-specific
6944 encoding. */
6945 cmd_str = build_unibyte_string (pe.szExeFile);
6947 decoded_cmd =
6948 code_convert_string_norecord (cmd_str,
6949 Vlocale_coding_system, 0);
6951 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6952 attrs = Fcons (Fcons (Qppid,
6953 make_fixnum_or_float (pe.th32ParentProcessID)),
6954 attrs);
6955 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6956 attrs);
6957 attrs = Fcons (Fcons (Qthcount,
6958 make_fixnum_or_float (pe.cntThreads)),
6959 attrs);
6960 found_proc = 1;
6961 break;
6965 CloseHandle (h_snapshot);
6968 if (!found_proc)
6969 return Qnil;
6971 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6972 FALSE, proc_id);
6973 /* If we were denied a handle to the process, try again after
6974 enabling the SeDebugPrivilege in our process. */
6975 if (!h_proc)
6977 TOKEN_PRIVILEGES priv_current;
6979 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6981 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6982 FALSE, proc_id);
6983 restore_privilege (&priv_current);
6984 revert_to_self ();
6987 if (h_proc)
6989 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6990 if (result)
6992 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6993 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6995 buf = xmalloc (blen);
6996 result = get_token_information (token, TokenUser,
6997 (LPVOID)buf, blen, &needed);
6998 if (result)
7000 memcpy (&user_token, buf, sizeof (user_token));
7001 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
7003 euid = get_rid (user_token.User.Sid);
7004 result = lookup_account_sid (NULL, user_token.User.Sid,
7005 uname, &ulength,
7006 domain, &dlength,
7007 &user_type);
7008 if (result)
7009 w32_add_to_cache (user_token.User.Sid, euid, uname);
7010 else
7012 strcpy (uname, "unknown");
7013 result = TRUE;
7016 ulength = strlen (uname);
7020 if (result)
7022 /* Determine a reasonable euid and gid values. */
7023 if (xstrcasecmp ("administrator", uname) == 0)
7025 euid = 500; /* well-known Administrator uid */
7026 egid = 513; /* well-known None gid */
7028 else
7030 /* Get group id and name. */
7031 result = get_token_information (token, TokenPrimaryGroup,
7032 (LPVOID)buf, blen, &needed);
7033 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7035 buf = xrealloc (buf, blen = needed);
7036 result = get_token_information (token, TokenPrimaryGroup,
7037 (LPVOID)buf, blen, &needed);
7039 if (result)
7041 memcpy (&group_token, buf, sizeof (group_token));
7042 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7044 egid = get_rid (group_token.PrimaryGroup);
7045 dlength = sizeof (domain);
7046 result =
7047 lookup_account_sid (NULL, group_token.PrimaryGroup,
7048 gname, &glength, NULL, &dlength,
7049 &user_type);
7050 if (result)
7051 w32_add_to_cache (group_token.PrimaryGroup,
7052 egid, gname);
7053 else
7055 strcpy (gname, "None");
7056 result = TRUE;
7059 glength = strlen (gname);
7063 xfree (buf);
7065 if (!result)
7067 if (!is_windows_9x ())
7069 /* We couldn't open the process token, presumably because of
7070 insufficient access rights. Assume this process is run
7071 by the system. */
7072 strcpy (uname, "SYSTEM");
7073 strcpy (gname, "None");
7074 euid = 18; /* SYSTEM */
7075 egid = 513; /* None */
7076 glength = strlen (gname);
7077 ulength = strlen (uname);
7079 /* If we are running under Windows 9X, where security calls are
7080 not supported, we assume all processes are run by the current
7081 user. */
7082 else if (GetUserName (uname, &ulength))
7084 if (xstrcasecmp ("administrator", uname) == 0)
7085 euid = 0;
7086 else
7087 euid = 123;
7088 egid = euid;
7089 strcpy (gname, "None");
7090 glength = strlen (gname);
7091 ulength = strlen (uname);
7093 else
7095 euid = 123;
7096 egid = 123;
7097 strcpy (uname, "administrator");
7098 ulength = strlen (uname);
7099 strcpy (gname, "None");
7100 glength = strlen (gname);
7102 if (token)
7103 CloseHandle (token);
7106 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7107 tem = make_unibyte_string (uname, ulength);
7108 attrs = Fcons (Fcons (Quser,
7109 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7110 attrs);
7111 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7112 tem = make_unibyte_string (gname, glength);
7113 attrs = Fcons (Fcons (Qgroup,
7114 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7115 attrs);
7117 if (global_memory_status_ex (&memstex))
7118 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7119 totphys = memstex.ullTotalPhys / 1024.0;
7120 #else
7121 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7122 double, so we need to do this for it... */
7124 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7125 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7126 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7128 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7130 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7131 else if (global_memory_status (&memst))
7132 totphys = memst.dwTotalPhys / 1024.0;
7134 if (h_proc
7135 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7136 sizeof (mem_ex)))
7138 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7140 attrs = Fcons (Fcons (Qmajflt,
7141 make_fixnum_or_float (mem_ex.PageFaultCount)),
7142 attrs);
7143 attrs = Fcons (Fcons (Qvsize,
7144 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7145 attrs);
7146 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7147 if (totphys)
7148 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7150 else if (h_proc
7151 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7153 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7155 attrs = Fcons (Fcons (Qmajflt,
7156 make_fixnum_or_float (mem.PageFaultCount)),
7157 attrs);
7158 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7159 if (totphys)
7160 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7162 else if (h_proc
7163 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7165 DWORD rss = maxrss / 1024;
7167 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7168 if (totphys)
7169 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7172 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7174 attrs = Fcons (Fcons (Qutime, utime), attrs);
7175 attrs = Fcons (Fcons (Qstime, stime), attrs);
7176 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7177 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7178 attrs = Fcons (Fcons (Qetime, etime), attrs);
7179 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7182 /* FIXME: Retrieve command line by walking the PEB of the process. */
7184 if (h_proc)
7185 CloseHandle (h_proc);
7186 return attrs;
7190 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7191 unsigned long long *totalswap, unsigned long long *freeswap)
7193 MEMORYSTATUS memst;
7194 MEMORY_STATUS_EX memstex;
7196 /* Use GlobalMemoryStatusEx if available, as it can report more than
7197 2GB of memory. */
7198 if (global_memory_status_ex (&memstex))
7200 *totalram = memstex.ullTotalPhys;
7201 *freeram = memstex.ullAvailPhys;
7202 *totalswap = memstex.ullTotalPageFile;
7203 *freeswap = memstex.ullAvailPageFile;
7204 return 0;
7206 else if (global_memory_status (&memst))
7208 *totalram = memst.dwTotalPhys;
7209 *freeram = memst.dwAvailPhys;
7210 *totalswap = memst.dwTotalPageFile;
7211 *freeswap = memst.dwAvailPageFile;
7212 return 0;
7214 else
7215 return -1;
7219 /* Wrappers for winsock functions to map between our file descriptors
7220 and winsock's handles; also set h_errno for convenience.
7222 To allow Emacs to run on systems which don't have winsock support
7223 installed, we dynamically link to winsock on startup if present, and
7224 otherwise provide the minimum necessary functionality
7225 (eg. gethostname). */
7227 /* function pointers for relevant socket functions */
7228 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7229 void (PASCAL *pfn_WSASetLastError) (int iError);
7230 int (PASCAL *pfn_WSAGetLastError) (void);
7231 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7232 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7233 WSANETWORKEVENTS *NetworkEvents);
7235 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7236 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7237 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7238 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7239 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7240 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7241 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7242 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7243 int (PASCAL *pfn_closesocket) (SOCKET s);
7244 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7245 int (PASCAL *pfn_WSACleanup) (void);
7247 u_short (PASCAL *pfn_htons) (u_short hostshort);
7248 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7249 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7250 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7251 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7252 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7253 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7254 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7255 const char * optval, int optlen);
7256 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7257 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7258 int * namelen);
7259 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7260 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7261 struct sockaddr * from, int * fromlen);
7262 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7263 const struct sockaddr * to, int tolen);
7265 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7266 const struct addrinfo *, struct addrinfo **);
7267 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7269 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7270 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7271 #ifndef HANDLE_FLAG_INHERIT
7272 #define HANDLE_FLAG_INHERIT 1
7273 #endif
7275 HANDLE winsock_lib;
7276 static int winsock_inuse;
7278 BOOL term_winsock (void);
7280 BOOL
7281 term_winsock (void)
7283 if (winsock_lib != NULL && winsock_inuse == 0)
7285 release_listen_threads ();
7286 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7287 after WSAStartup returns successfully, but it seems reasonable
7288 to allow unloading winsock anyway in that case. */
7289 if (pfn_WSACleanup () == 0 ||
7290 pfn_WSAGetLastError () == WSAENETDOWN)
7292 if (FreeLibrary (winsock_lib))
7293 winsock_lib = NULL;
7294 return TRUE;
7297 return FALSE;
7300 BOOL
7301 init_winsock (int load_now)
7303 WSADATA winsockData;
7305 if (winsock_lib != NULL)
7306 return TRUE;
7308 pfn_SetHandleInformation
7309 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7310 "SetHandleInformation");
7312 winsock_lib = LoadLibrary ("Ws2_32.dll");
7314 if (winsock_lib != NULL)
7316 /* dynamically link to socket functions */
7318 #define LOAD_PROC(fn) \
7319 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7320 goto fail;
7322 LOAD_PROC (WSAStartup);
7323 LOAD_PROC (WSASetLastError);
7324 LOAD_PROC (WSAGetLastError);
7325 LOAD_PROC (WSAEventSelect);
7326 LOAD_PROC (WSAEnumNetworkEvents);
7327 LOAD_PROC (WSACreateEvent);
7328 LOAD_PROC (WSACloseEvent);
7329 LOAD_PROC (socket);
7330 LOAD_PROC (bind);
7331 LOAD_PROC (connect);
7332 LOAD_PROC (ioctlsocket);
7333 LOAD_PROC (recv);
7334 LOAD_PROC (send);
7335 LOAD_PROC (closesocket);
7336 LOAD_PROC (shutdown);
7337 LOAD_PROC (htons);
7338 LOAD_PROC (ntohs);
7339 LOAD_PROC (inet_addr);
7340 LOAD_PROC (gethostname);
7341 LOAD_PROC (gethostbyname);
7342 LOAD_PROC (getservbyname);
7343 LOAD_PROC (getpeername);
7344 LOAD_PROC (WSACleanup);
7345 LOAD_PROC (setsockopt);
7346 LOAD_PROC (listen);
7347 LOAD_PROC (getsockname);
7348 LOAD_PROC (accept);
7349 LOAD_PROC (recvfrom);
7350 LOAD_PROC (sendto);
7351 #undef LOAD_PROC
7353 /* Try loading functions not available before XP. */
7354 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7355 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7356 /* Paranoia: these two functions should go together, so if one
7357 is absent, we cannot use the other. */
7358 if (pfn_getaddrinfo == NULL)
7359 pfn_freeaddrinfo = NULL;
7360 else if (pfn_freeaddrinfo == NULL)
7361 pfn_getaddrinfo = NULL;
7363 /* specify version 1.1 of winsock */
7364 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7366 if (winsockData.wVersion != 0x101)
7367 goto fail;
7369 if (!load_now)
7371 /* Report that winsock exists and is usable, but leave
7372 socket functions disabled. I am assuming that calling
7373 WSAStartup does not require any network interaction,
7374 and in particular does not cause or require a dial-up
7375 connection to be established. */
7377 pfn_WSACleanup ();
7378 FreeLibrary (winsock_lib);
7379 winsock_lib = NULL;
7381 winsock_inuse = 0;
7382 return TRUE;
7385 fail:
7386 FreeLibrary (winsock_lib);
7387 winsock_lib = NULL;
7390 return FALSE;
7394 int h_errno = 0;
7396 /* Function to map winsock error codes to errno codes for those errno
7397 code defined in errno.h (errno values not defined by errno.h are
7398 already in nt/inc/sys/socket.h). */
7399 static void
7400 set_errno (void)
7402 int wsa_err;
7404 h_errno = 0;
7405 if (winsock_lib == NULL)
7406 wsa_err = EINVAL;
7407 else
7408 wsa_err = pfn_WSAGetLastError ();
7410 switch (wsa_err)
7412 case WSAEACCES: errno = EACCES; break;
7413 case WSAEBADF: errno = EBADF; break;
7414 case WSAEFAULT: errno = EFAULT; break;
7415 case WSAEINTR: errno = EINTR; break;
7416 case WSAEINVAL: errno = EINVAL; break;
7417 case WSAEMFILE: errno = EMFILE; break;
7418 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7419 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7420 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7421 case WSAENOTCONN: errno = ENOTCONN; break;
7422 default: errno = wsa_err; break;
7426 static void
7427 check_errno (void)
7429 h_errno = 0;
7430 if (winsock_lib != NULL)
7431 pfn_WSASetLastError (0);
7434 /* Extend strerror to handle the winsock-specific error codes. */
7435 struct {
7436 int errnum;
7437 const char * msg;
7438 } _wsa_errlist[] = {
7439 {WSAEINTR , "Interrupted function call"},
7440 {WSAEBADF , "Bad file descriptor"},
7441 {WSAEACCES , "Permission denied"},
7442 {WSAEFAULT , "Bad address"},
7443 {WSAEINVAL , "Invalid argument"},
7444 {WSAEMFILE , "Too many open files"},
7446 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7447 {WSAEINPROGRESS , "Operation now in progress"},
7448 {WSAEALREADY , "Operation already in progress"},
7449 {WSAENOTSOCK , "Socket operation on non-socket"},
7450 {WSAEDESTADDRREQ , "Destination address required"},
7451 {WSAEMSGSIZE , "Message too long"},
7452 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7453 {WSAENOPROTOOPT , "Bad protocol option"},
7454 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7455 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7456 {WSAEOPNOTSUPP , "Operation not supported"},
7457 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7458 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7459 {WSAEADDRINUSE , "Address already in use"},
7460 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7461 {WSAENETDOWN , "Network is down"},
7462 {WSAENETUNREACH , "Network is unreachable"},
7463 {WSAENETRESET , "Network dropped connection on reset"},
7464 {WSAECONNABORTED , "Software caused connection abort"},
7465 {WSAECONNRESET , "Connection reset by peer"},
7466 {WSAENOBUFS , "No buffer space available"},
7467 {WSAEISCONN , "Socket is already connected"},
7468 {WSAENOTCONN , "Socket is not connected"},
7469 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7470 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7471 {WSAETIMEDOUT , "Connection timed out"},
7472 {WSAECONNREFUSED , "Connection refused"},
7473 {WSAELOOP , "Network loop"}, /* not sure */
7474 {WSAENAMETOOLONG , "Name is too long"},
7475 {WSAEHOSTDOWN , "Host is down"},
7476 {WSAEHOSTUNREACH , "No route to host"},
7477 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7478 {WSAEPROCLIM , "Too many processes"},
7479 {WSAEUSERS , "Too many users"}, /* not sure */
7480 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7481 {WSAESTALE , "Data is stale"}, /* not sure */
7482 {WSAEREMOTE , "Remote error"}, /* not sure */
7484 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7485 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7486 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7487 {WSAEDISCON , "Graceful shutdown in progress"},
7488 #ifdef WSAENOMORE
7489 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7490 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7491 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7492 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7493 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7494 {WSASYSCALLFAILURE , "System call failure"},
7495 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7496 {WSATYPE_NOT_FOUND , "Class type not found"},
7497 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7498 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7499 {WSAEREFUSED , "Operation refused"}, /* not sure */
7500 #endif
7502 {WSAHOST_NOT_FOUND , "Host not found"},
7503 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7504 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7505 {WSANO_DATA , "Valid name, no data record of requested type"},
7507 {-1, NULL}
7510 char *
7511 sys_strerror (int error_no)
7513 int i;
7514 static char unknown_msg[40];
7516 if (error_no >= 0 && error_no < sys_nerr)
7517 return sys_errlist[error_no];
7519 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7520 if (_wsa_errlist[i].errnum == error_no)
7521 return (char *)_wsa_errlist[i].msg;
7523 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7524 return unknown_msg;
7527 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7528 but I believe the method of keeping the socket handle separate (and
7529 insuring it is not inheritable) is the correct one. */
7531 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7533 static int socket_to_fd (SOCKET s);
7536 sys_socket (int af, int type, int protocol)
7538 SOCKET s;
7540 if (winsock_lib == NULL)
7542 errno = ENETDOWN;
7543 return -1;
7546 check_errno ();
7548 /* call the real socket function */
7549 s = pfn_socket (af, type, protocol);
7551 if (s != INVALID_SOCKET)
7552 return socket_to_fd (s);
7554 set_errno ();
7555 return -1;
7558 /* Convert a SOCKET to a file descriptor. */
7559 static int
7560 socket_to_fd (SOCKET s)
7562 int fd;
7563 child_process * cp;
7565 /* Although under NT 3.5 _open_osfhandle will accept a socket
7566 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7567 that does not work under NT 3.1. However, we can get the same
7568 effect by using a backdoor function to replace an existing
7569 descriptor handle with the one we want. */
7571 /* allocate a file descriptor (with appropriate flags) */
7572 fd = _open ("NUL:", _O_RDWR);
7573 if (fd >= 0)
7575 /* Make a non-inheritable copy of the socket handle. Note
7576 that it is possible that sockets aren't actually kernel
7577 handles, which appears to be the case on Windows 9x when
7578 the MS Proxy winsock client is installed. */
7580 /* Apparently there is a bug in NT 3.51 with some service
7581 packs, which prevents using DuplicateHandle to make a
7582 socket handle non-inheritable (causes WSACleanup to
7583 hang). The work-around is to use SetHandleInformation
7584 instead if it is available and implemented. */
7585 if (pfn_SetHandleInformation)
7587 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7589 else
7591 HANDLE parent = GetCurrentProcess ();
7592 HANDLE new_s = INVALID_HANDLE_VALUE;
7594 if (DuplicateHandle (parent,
7595 (HANDLE) s,
7596 parent,
7597 &new_s,
7599 FALSE,
7600 DUPLICATE_SAME_ACCESS))
7602 /* It is possible that DuplicateHandle succeeds even
7603 though the socket wasn't really a kernel handle,
7604 because a real handle has the same value. So
7605 test whether the new handle really is a socket. */
7606 unsigned long nonblocking = 0;
7607 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7609 pfn_closesocket (s);
7610 s = (SOCKET) new_s;
7612 else
7614 CloseHandle (new_s);
7619 eassert (fd < MAXDESC);
7620 fd_info[fd].hnd = (HANDLE) s;
7622 /* set our own internal flags */
7623 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7625 cp = new_child ();
7626 if (cp)
7628 cp->fd = fd;
7629 cp->status = STATUS_READ_ACKNOWLEDGED;
7631 /* attach child_process to fd_info */
7632 if (fd_info[ fd ].cp != NULL)
7634 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7635 emacs_abort ();
7638 fd_info[ fd ].cp = cp;
7640 /* success! */
7641 winsock_inuse++; /* count open sockets */
7642 return fd;
7645 /* clean up */
7646 _close (fd);
7648 else
7649 pfn_closesocket (s);
7650 errno = EMFILE;
7651 return -1;
7655 sys_bind (int s, const struct sockaddr * addr, int namelen)
7657 if (winsock_lib == NULL)
7659 errno = ENOTSOCK;
7660 return SOCKET_ERROR;
7663 check_errno ();
7664 if (fd_info[s].flags & FILE_SOCKET)
7666 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7667 if (rc == SOCKET_ERROR)
7668 set_errno ();
7669 return rc;
7671 errno = ENOTSOCK;
7672 return SOCKET_ERROR;
7676 sys_connect (int s, const struct sockaddr * name, int namelen)
7678 if (winsock_lib == NULL)
7680 errno = ENOTSOCK;
7681 return SOCKET_ERROR;
7684 check_errno ();
7685 if (fd_info[s].flags & FILE_SOCKET)
7687 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7688 if (rc == SOCKET_ERROR)
7690 set_errno ();
7691 /* If this is a non-blocking 'connect', set the bit in flags
7692 that will tell reader_thread to wait for connection
7693 before trying to read. */
7694 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7696 errno = EINPROGRESS; /* that's what process.c expects */
7697 fd_info[s].flags |= FILE_CONNECT;
7700 return rc;
7702 errno = ENOTSOCK;
7703 return SOCKET_ERROR;
7706 u_short
7707 sys_htons (u_short hostshort)
7709 return (winsock_lib != NULL) ?
7710 pfn_htons (hostshort) : hostshort;
7713 u_short
7714 sys_ntohs (u_short netshort)
7716 return (winsock_lib != NULL) ?
7717 pfn_ntohs (netshort) : netshort;
7720 unsigned long
7721 sys_inet_addr (const char * cp)
7723 return (winsock_lib != NULL) ?
7724 pfn_inet_addr (cp) : INADDR_NONE;
7728 sys_gethostname (char * name, int namelen)
7730 if (winsock_lib != NULL)
7732 int retval;
7734 check_errno ();
7735 retval = pfn_gethostname (name, namelen);
7736 if (retval == SOCKET_ERROR)
7737 set_errno ();
7738 return retval;
7741 if (namelen > MAX_COMPUTERNAME_LENGTH)
7742 return !GetComputerName (name, (DWORD *)&namelen);
7744 errno = EFAULT;
7745 return SOCKET_ERROR;
7748 struct hostent *
7749 sys_gethostbyname (const char * name)
7751 struct hostent * host;
7752 int h_err = h_errno;
7754 if (winsock_lib == NULL)
7756 h_errno = NO_RECOVERY;
7757 errno = ENETDOWN;
7758 return NULL;
7761 check_errno ();
7762 host = pfn_gethostbyname (name);
7763 if (!host)
7765 set_errno ();
7766 h_errno = errno;
7768 else
7769 h_errno = h_err;
7770 return host;
7773 struct servent *
7774 sys_getservbyname (const char * name, const char * proto)
7776 struct servent * serv;
7778 if (winsock_lib == NULL)
7780 errno = ENETDOWN;
7781 return NULL;
7784 check_errno ();
7785 serv = pfn_getservbyname (name, proto);
7786 if (!serv)
7787 set_errno ();
7788 return serv;
7792 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7794 if (winsock_lib == NULL)
7796 errno = ENETDOWN;
7797 return SOCKET_ERROR;
7800 check_errno ();
7801 if (fd_info[s].flags & FILE_SOCKET)
7803 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7804 if (rc == SOCKET_ERROR)
7805 set_errno ();
7806 return rc;
7808 errno = ENOTSOCK;
7809 return SOCKET_ERROR;
7813 sys_getaddrinfo (const char *node, const char *service,
7814 const struct addrinfo *hints, struct addrinfo **res)
7816 int rc;
7818 if (winsock_lib == NULL)
7820 errno = ENETDOWN;
7821 return SOCKET_ERROR;
7824 check_errno ();
7825 if (pfn_getaddrinfo)
7826 rc = pfn_getaddrinfo (node, service, hints, res);
7827 else
7829 int port = 0;
7830 struct hostent *host_info;
7831 struct gai_storage {
7832 struct addrinfo addrinfo;
7833 struct sockaddr_in sockaddr_in;
7834 } *gai_storage;
7836 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7837 if (hints && hints->ai_flags != 0)
7838 return WSAEINVAL;
7839 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7840 if (!node)
7841 return WSAHOST_NOT_FOUND;
7843 if (service)
7845 const char *protocol =
7846 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7847 struct servent *srv = sys_getservbyname (service, protocol);
7849 if (srv)
7850 port = srv->s_port;
7851 else if (*service >= '0' && *service <= '9')
7853 char *endp;
7855 port = strtoul (service, &endp, 10);
7856 if (*endp || port > 65536)
7857 return WSAHOST_NOT_FOUND;
7858 port = sys_htons ((unsigned short) port);
7860 else
7861 return WSAHOST_NOT_FOUND;
7864 gai_storage = xzalloc (sizeof *gai_storage);
7865 gai_storage->sockaddr_in.sin_port = port;
7866 host_info = sys_gethostbyname (node);
7867 if (host_info)
7869 memcpy (&gai_storage->sockaddr_in.sin_addr,
7870 host_info->h_addr, host_info->h_length);
7871 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7873 else
7875 /* Attempt to interpret host as numeric inet address. */
7876 unsigned long numeric_addr = sys_inet_addr (node);
7878 if (numeric_addr == -1)
7880 free (gai_storage);
7881 return WSAHOST_NOT_FOUND;
7884 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7885 sizeof (gai_storage->sockaddr_in.sin_addr));
7886 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7889 gai_storage->addrinfo.ai_addr =
7890 (struct sockaddr *)&gai_storage->sockaddr_in;
7891 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7892 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7893 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7894 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7895 gai_storage->addrinfo.ai_next = NULL;
7897 *res = &gai_storage->addrinfo;
7898 rc = 0;
7901 return rc;
7904 void
7905 sys_freeaddrinfo (struct addrinfo *ai)
7907 if (winsock_lib == NULL)
7909 errno = ENETDOWN;
7910 return;
7913 check_errno ();
7914 if (pfn_freeaddrinfo)
7915 pfn_freeaddrinfo (ai);
7916 else
7918 eassert (ai->ai_next == NULL);
7919 xfree (ai);
7924 sys_shutdown (int s, int how)
7926 if (winsock_lib == NULL)
7928 errno = ENETDOWN;
7929 return SOCKET_ERROR;
7932 check_errno ();
7933 if (fd_info[s].flags & FILE_SOCKET)
7935 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7936 if (rc == SOCKET_ERROR)
7937 set_errno ();
7938 return rc;
7940 errno = ENOTSOCK;
7941 return SOCKET_ERROR;
7945 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7947 if (winsock_lib == NULL)
7949 errno = ENETDOWN;
7950 return SOCKET_ERROR;
7953 check_errno ();
7954 if (fd_info[s].flags & FILE_SOCKET)
7956 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7957 (const char *)optval, optlen);
7958 if (rc == SOCKET_ERROR)
7959 set_errno ();
7960 return rc;
7962 errno = ENOTSOCK;
7963 return SOCKET_ERROR;
7967 sys_listen (int s, int backlog)
7969 if (winsock_lib == NULL)
7971 errno = ENETDOWN;
7972 return SOCKET_ERROR;
7975 check_errno ();
7976 if (fd_info[s].flags & FILE_SOCKET)
7978 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7979 if (rc == SOCKET_ERROR)
7980 set_errno ();
7981 else
7982 fd_info[s].flags |= FILE_LISTEN;
7983 return rc;
7985 errno = ENOTSOCK;
7986 return SOCKET_ERROR;
7990 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7992 if (winsock_lib == NULL)
7994 errno = ENETDOWN;
7995 return SOCKET_ERROR;
7998 check_errno ();
7999 if (fd_info[s].flags & FILE_SOCKET)
8001 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
8002 if (rc == SOCKET_ERROR)
8003 set_errno ();
8004 return rc;
8006 errno = ENOTSOCK;
8007 return SOCKET_ERROR;
8011 sys_accept (int s, struct sockaddr * addr, int * addrlen)
8013 if (winsock_lib == NULL)
8015 errno = ENETDOWN;
8016 return -1;
8019 check_errno ();
8020 if (fd_info[s].flags & FILE_LISTEN)
8022 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
8023 int fd = -1;
8024 if (t == INVALID_SOCKET)
8025 set_errno ();
8026 else
8027 fd = socket_to_fd (t);
8029 if (fd >= 0)
8031 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
8032 ResetEvent (fd_info[s].cp->char_avail);
8034 return fd;
8036 errno = ENOTSOCK;
8037 return -1;
8041 sys_recvfrom (int s, char * buf, int len, int flags,
8042 struct sockaddr * from, int * fromlen)
8044 if (winsock_lib == NULL)
8046 errno = ENETDOWN;
8047 return SOCKET_ERROR;
8050 check_errno ();
8051 if (fd_info[s].flags & FILE_SOCKET)
8053 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8054 if (rc == SOCKET_ERROR)
8055 set_errno ();
8056 return rc;
8058 errno = ENOTSOCK;
8059 return SOCKET_ERROR;
8063 sys_sendto (int s, const char * buf, int len, int flags,
8064 const struct sockaddr * to, int tolen)
8066 if (winsock_lib == NULL)
8068 errno = ENETDOWN;
8069 return SOCKET_ERROR;
8072 check_errno ();
8073 if (fd_info[s].flags & FILE_SOCKET)
8075 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8076 if (rc == SOCKET_ERROR)
8077 set_errno ();
8078 return rc;
8080 errno = ENOTSOCK;
8081 return SOCKET_ERROR;
8084 /* Windows does not have an fcntl function. Provide an implementation
8085 good enough for Emacs. */
8087 fcntl (int s, int cmd, int options)
8089 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8090 invoked in a context where fd1 is closed and all descriptors less
8091 than fd1 are open, so sys_dup is an adequate implementation. */
8092 if (cmd == F_DUPFD_CLOEXEC)
8093 return sys_dup (s);
8095 check_errno ();
8096 if (fd_info[s].flags & FILE_SOCKET)
8098 if (winsock_lib == NULL)
8100 errno = ENETDOWN;
8101 return -1;
8104 if (cmd == F_SETFL && options == O_NONBLOCK)
8106 unsigned long nblock = 1;
8107 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8108 if (rc == SOCKET_ERROR)
8109 set_errno ();
8110 /* Keep track of the fact that we set this to non-blocking. */
8111 fd_info[s].flags |= FILE_NDELAY;
8112 return rc;
8114 else
8116 errno = EINVAL;
8117 return SOCKET_ERROR;
8120 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8121 == (FILE_PIPE | FILE_WRITE))
8123 /* Force our writes to pipes be non-blocking. */
8124 if (cmd == F_SETFL && options == O_NONBLOCK)
8126 HANDLE h = (HANDLE)_get_osfhandle (s);
8127 DWORD pipe_mode = PIPE_NOWAIT;
8129 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8131 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8132 return SOCKET_ERROR;
8134 fd_info[s].flags |= FILE_NDELAY;
8135 return 0;
8137 else
8139 errno = EINVAL;
8140 return SOCKET_ERROR;
8143 errno = ENOTSOCK;
8144 return SOCKET_ERROR;
8148 /* Shadow main io functions: we need to handle pipes and sockets more
8149 intelligently. */
8152 sys_close (int fd)
8154 int rc;
8156 if (fd < 0)
8158 errno = EBADF;
8159 return -1;
8162 if (fd < MAXDESC && fd_info[fd].cp)
8164 child_process * cp = fd_info[fd].cp;
8166 fd_info[fd].cp = NULL;
8168 if (CHILD_ACTIVE (cp))
8170 /* if last descriptor to active child_process then cleanup */
8171 int i;
8172 for (i = 0; i < MAXDESC; i++)
8174 if (i == fd)
8175 continue;
8176 if (fd_info[i].cp == cp)
8177 break;
8179 if (i == MAXDESC)
8181 if (fd_info[fd].flags & FILE_SOCKET)
8183 if (winsock_lib == NULL) emacs_abort ();
8185 pfn_shutdown (SOCK_HANDLE (fd), 2);
8186 rc = pfn_closesocket (SOCK_HANDLE (fd));
8188 winsock_inuse--; /* count open sockets */
8190 /* If the process handle is NULL, it's either a socket
8191 or serial connection, or a subprocess that was
8192 already reaped by reap_subprocess, but whose
8193 resources were not yet freed, because its output was
8194 not fully read yet by the time it was reaped. (This
8195 usually happens with async subprocesses whose output
8196 is being read by Emacs.) Otherwise, this process was
8197 not reaped yet, so we set its FD to a negative value
8198 to make sure sys_select will eventually get to
8199 calling the SIGCHLD handler for it, which will then
8200 invoke waitpid and reap_subprocess. */
8201 if (cp->procinfo.hProcess == NULL)
8202 delete_child (cp);
8203 else
8204 cp->fd = -1;
8209 if (fd >= 0 && fd < MAXDESC)
8210 fd_info[fd].flags = 0;
8212 /* Note that sockets do not need special treatment here (at least on
8213 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8214 closesocket is equivalent to CloseHandle, which is to be expected
8215 because socket handles are fully fledged kernel handles. */
8216 rc = _close (fd);
8218 return rc;
8222 sys_dup (int fd)
8224 int new_fd;
8226 new_fd = _dup (fd);
8227 if (new_fd >= 0 && new_fd < MAXDESC)
8229 /* duplicate our internal info as well */
8230 fd_info[new_fd] = fd_info[fd];
8232 return new_fd;
8236 sys_dup2 (int src, int dst)
8238 int rc;
8240 if (dst < 0 || dst >= MAXDESC)
8242 errno = EBADF;
8243 return -1;
8246 /* MS _dup2 seems to have weird side effect when invoked with 2
8247 identical arguments: an attempt to fclose the corresponding stdio
8248 stream after that hangs (we do close standard streams in
8249 init_ntproc). Attempt to avoid that by not calling _dup2 that
8250 way: if SRC is valid, we know that dup2 should be a no-op, so do
8251 nothing and return DST. */
8252 if (src == dst)
8254 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8256 errno = EBADF;
8257 return -1;
8259 return dst;
8262 /* Make sure we close the destination first if it's a pipe or socket. */
8263 if (fd_info[dst].flags != 0)
8264 sys_close (dst);
8266 rc = _dup2 (src, dst);
8267 if (rc == 0)
8269 /* Duplicate our internal info as well. */
8270 fd_info[dst] = fd_info[src];
8272 return rc == 0 ? dst : rc;
8276 pipe2 (int * phandles, int pipe2_flags)
8278 int rc;
8279 unsigned flags;
8280 unsigned pipe_size = 0;
8282 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8284 /* Allow Lisp to override the default buffer size of the pipe. */
8285 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8286 pipe_size = w32_pipe_buffer_size;
8288 /* make pipe handles non-inheritable; when we spawn a child, we
8289 replace the relevant handle with an inheritable one. Also put
8290 pipes into binary mode; we will do text mode translation ourselves
8291 if required. */
8292 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8294 if (rc == 0)
8296 /* Protect against overflow, since Windows can open more handles than
8297 our fd_info array has room for. */
8298 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8300 _close (phandles[0]);
8301 _close (phandles[1]);
8302 errno = EMFILE;
8303 rc = -1;
8305 else
8307 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8308 fd_info[phandles[0]].flags = flags;
8310 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8311 fd_info[phandles[1]].flags = flags;
8315 return rc;
8318 /* Function to do blocking read of one byte, needed to implement
8319 select. It is only allowed on communication ports, sockets, or
8320 pipes. */
8322 _sys_read_ahead (int fd)
8324 child_process * cp;
8325 int rc;
8327 if (fd < 0 || fd >= MAXDESC)
8328 return STATUS_READ_ERROR;
8330 cp = fd_info[fd].cp;
8332 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8333 return STATUS_READ_ERROR;
8335 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8336 || (fd_info[fd].flags & FILE_READ) == 0)
8338 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8339 emacs_abort ();
8342 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8343 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8344 cp->status = STATUS_READ_IN_PROGRESS;
8346 if (fd_info[fd].flags & FILE_PIPE)
8348 rc = _read (fd, &cp->chr, sizeof (char));
8350 /* Give subprocess time to buffer some more output for us before
8351 reporting that input is available; we need this because Windows 95
8352 connects DOS programs to pipes by making the pipe appear to be
8353 the normal console stdout - as a result most DOS programs will
8354 write to stdout without buffering, ie. one character at a
8355 time. Even some W32 programs do this - "dir" in a command
8356 shell on NT is very slow if we don't do this. */
8357 if (rc > 0)
8359 int wait = w32_pipe_read_delay;
8361 if (wait > 0)
8362 Sleep (wait);
8363 else if (wait < 0)
8364 while (++wait <= 0)
8365 /* Yield remainder of our time slice, effectively giving a
8366 temporary priority boost to the child process. */
8367 Sleep (0);
8370 else if (fd_info[fd].flags & FILE_SERIAL)
8372 HANDLE hnd = fd_info[fd].hnd;
8373 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8374 COMMTIMEOUTS ct;
8376 /* Configure timeouts for blocking read. */
8377 if (!GetCommTimeouts (hnd, &ct))
8379 cp->status = STATUS_READ_ERROR;
8380 return STATUS_READ_ERROR;
8382 ct.ReadIntervalTimeout = 0;
8383 ct.ReadTotalTimeoutMultiplier = 0;
8384 ct.ReadTotalTimeoutConstant = 0;
8385 if (!SetCommTimeouts (hnd, &ct))
8387 cp->status = STATUS_READ_ERROR;
8388 return STATUS_READ_ERROR;
8391 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8393 if (GetLastError () != ERROR_IO_PENDING)
8395 cp->status = STATUS_READ_ERROR;
8396 return STATUS_READ_ERROR;
8398 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8400 cp->status = STATUS_READ_ERROR;
8401 return STATUS_READ_ERROR;
8405 else if (fd_info[fd].flags & FILE_SOCKET)
8407 unsigned long nblock = 0;
8408 /* We always want this to block, so temporarily disable NDELAY. */
8409 if (fd_info[fd].flags & FILE_NDELAY)
8410 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8412 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8414 if (fd_info[fd].flags & FILE_NDELAY)
8416 nblock = 1;
8417 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8421 if (rc == sizeof (char))
8422 cp->status = STATUS_READ_SUCCEEDED;
8423 else
8424 cp->status = STATUS_READ_FAILED;
8426 return cp->status;
8430 _sys_wait_accept (int fd)
8432 HANDLE hEv;
8433 child_process * cp;
8434 int rc;
8436 if (fd < 0 || fd >= MAXDESC)
8437 return STATUS_READ_ERROR;
8439 cp = fd_info[fd].cp;
8441 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8442 return STATUS_READ_ERROR;
8444 cp->status = STATUS_READ_FAILED;
8446 hEv = pfn_WSACreateEvent ();
8447 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8448 if (rc != SOCKET_ERROR)
8450 do {
8451 rc = WaitForSingleObject (hEv, 500);
8452 Sleep (5);
8453 } while (rc == WAIT_TIMEOUT
8454 && cp->status != STATUS_READ_ERROR
8455 && cp->char_avail);
8456 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8457 if (rc == WAIT_OBJECT_0)
8458 cp->status = STATUS_READ_SUCCEEDED;
8460 pfn_WSACloseEvent (hEv);
8462 return cp->status;
8466 _sys_wait_connect (int fd)
8468 HANDLE hEv;
8469 child_process * cp;
8470 int rc;
8472 if (fd < 0 || fd >= MAXDESC)
8473 return STATUS_READ_ERROR;
8475 cp = fd_info[fd].cp;
8476 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8477 return STATUS_READ_ERROR;
8479 cp->status = STATUS_READ_FAILED;
8481 hEv = pfn_WSACreateEvent ();
8482 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8483 if (rc != SOCKET_ERROR)
8485 do {
8486 rc = WaitForSingleObject (hEv, 500);
8487 Sleep (5);
8488 } while (rc == WAIT_TIMEOUT
8489 && cp->status != STATUS_READ_ERROR
8490 && cp->char_avail);
8491 if (rc == WAIT_OBJECT_0)
8493 /* We've got an event, but it could be a successful
8494 connection, or it could be a failure. Find out
8495 which one is it. */
8496 WSANETWORKEVENTS events;
8498 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8499 if ((events.lNetworkEvents & FD_CONNECT) != 0
8500 && events.iErrorCode[FD_CONNECT_BIT])
8502 cp->status = STATUS_CONNECT_FAILED;
8503 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8505 else
8507 cp->status = STATUS_READ_SUCCEEDED;
8508 cp->errcode = 0;
8511 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8513 else
8514 pfn_WSACloseEvent (hEv);
8516 return cp->status;
8520 sys_read (int fd, char * buffer, unsigned int count)
8522 int nchars;
8523 int to_read;
8524 DWORD waiting;
8525 char * orig_buffer = buffer;
8527 if (fd < 0)
8529 errno = EBADF;
8530 return -1;
8533 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8535 child_process *cp = fd_info[fd].cp;
8537 if ((fd_info[fd].flags & FILE_READ) == 0)
8539 errno = EBADF;
8540 return -1;
8543 nchars = 0;
8545 /* re-read CR carried over from last read */
8546 if (fd_info[fd].flags & FILE_LAST_CR)
8548 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8549 *buffer++ = 0x0d;
8550 count--;
8551 nchars++;
8552 fd_info[fd].flags &= ~FILE_LAST_CR;
8555 /* presence of a child_process structure means we are operating in
8556 non-blocking mode - otherwise we just call _read directly.
8557 Note that the child_process structure might be missing because
8558 reap_subprocess has been called; in this case the pipe is
8559 already broken, so calling _read on it is okay. */
8560 if (cp)
8562 int current_status = cp->status;
8564 switch (current_status)
8566 case STATUS_READ_FAILED:
8567 case STATUS_READ_ERROR:
8568 /* report normal EOF if nothing in buffer */
8569 if (nchars <= 0)
8570 fd_info[fd].flags |= FILE_AT_EOF;
8571 return nchars;
8573 case STATUS_READ_READY:
8574 case STATUS_READ_IN_PROGRESS:
8575 #if 0
8576 /* This happens all the time during GnuTLS handshake
8577 with the remote, evidently because GnuTLS waits for
8578 the read to complete by retrying the read operation
8579 upon EAGAIN. So I'm disabling the DebPrint to avoid
8580 wasting cycles on something that is not a real
8581 problem. Enable if you need to debug something that
8582 bumps into this. */
8583 DebPrint (("sys_read called when read is in progress %d\n",
8584 current_status));
8585 #endif
8586 errno = EWOULDBLOCK;
8587 return -1;
8589 case STATUS_READ_SUCCEEDED:
8590 /* consume read-ahead char */
8591 *buffer++ = cp->chr;
8592 count--;
8593 nchars++;
8594 cp->status = STATUS_READ_ACKNOWLEDGED;
8595 ResetEvent (cp->char_avail);
8597 case STATUS_READ_ACKNOWLEDGED:
8598 case STATUS_CONNECT_FAILED:
8599 break;
8601 default:
8602 DebPrint (("sys_read: bad status %d\n", current_status));
8603 errno = EBADF;
8604 return -1;
8607 if (fd_info[fd].flags & FILE_PIPE)
8609 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8610 to_read = min (waiting, (DWORD) count);
8612 if (to_read > 0)
8613 nchars += _read (fd, buffer, to_read);
8615 else if (fd_info[fd].flags & FILE_SERIAL)
8617 HANDLE hnd = fd_info[fd].hnd;
8618 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8619 int rc = 0;
8620 COMMTIMEOUTS ct;
8622 if (count > 0)
8624 /* Configure timeouts for non-blocking read. */
8625 if (!GetCommTimeouts (hnd, &ct))
8627 errno = EIO;
8628 return -1;
8630 ct.ReadIntervalTimeout = MAXDWORD;
8631 ct.ReadTotalTimeoutMultiplier = 0;
8632 ct.ReadTotalTimeoutConstant = 0;
8633 if (!SetCommTimeouts (hnd, &ct))
8635 errno = EIO;
8636 return -1;
8639 if (!ResetEvent (ovl->hEvent))
8641 errno = EIO;
8642 return -1;
8644 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8646 if (GetLastError () != ERROR_IO_PENDING)
8648 errno = EIO;
8649 return -1;
8651 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8653 errno = EIO;
8654 return -1;
8657 nchars += rc;
8660 else /* FILE_SOCKET */
8662 if (winsock_lib == NULL) emacs_abort ();
8664 /* When a non-blocking 'connect' call fails,
8665 wait_reading_process_output detects this by calling
8666 'getpeername', and then attempts to obtain the connection
8667 error code by trying to read 1 byte from the socket. If
8668 we try to serve that read by calling 'recv' below, the
8669 error we get is a generic WSAENOTCONN, not the actual
8670 connection error. So instead, we use the actual error
8671 code stashed by '_sys_wait_connect' in cp->errcode.
8672 Alternatively, we could have used 'getsockopt', like on
8673 GNU/Linux, but: (a) I have no idea whether the winsock
8674 version could hang, as it does "on some systems" (see the
8675 comment in process.c); and (b) 'getsockopt' on Windows is
8676 documented to clear the socket error for the entire
8677 process, which I'm not sure is TRT; FIXME. */
8678 if (current_status == STATUS_CONNECT_FAILED
8679 && (fd_info[fd].flags & FILE_CONNECT) != 0
8680 && cp->errcode != 0)
8682 pfn_WSASetLastError (cp->errcode);
8683 set_errno ();
8684 return -1;
8686 /* Do the equivalent of a non-blocking read. */
8687 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8688 if (waiting == 0 && nchars == 0)
8690 errno = EWOULDBLOCK;
8691 return -1;
8694 if (waiting)
8696 /* always use binary mode for sockets */
8697 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8698 if (res == SOCKET_ERROR)
8700 set_errno ();
8701 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8702 errno, SOCK_HANDLE (fd)));
8703 return -1;
8705 nchars += res;
8709 else
8711 int nread = _read (fd, buffer, count);
8712 if (nread >= 0)
8713 nchars += nread;
8714 else if (nchars == 0)
8715 nchars = nread;
8718 if (nchars <= 0)
8719 fd_info[fd].flags |= FILE_AT_EOF;
8720 /* Perform text mode translation if required. */
8721 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8723 nchars = crlf_to_lf (nchars, orig_buffer);
8724 /* If buffer contains only CR, return that. To be absolutely
8725 sure we should attempt to read the next char, but in
8726 practice a CR to be followed by LF would not appear by
8727 itself in the buffer. */
8728 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8730 fd_info[fd].flags |= FILE_LAST_CR;
8731 nchars--;
8735 else
8736 nchars = _read (fd, buffer, count);
8738 return nchars;
8741 /* From w32xfns.c */
8742 extern HANDLE interrupt_handle;
8745 sys_write (int fd, const void * buffer, unsigned int count)
8747 int nchars;
8748 USE_SAFE_ALLOCA;
8750 if (fd < 0)
8752 errno = EBADF;
8753 return -1;
8756 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8758 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8760 errno = EBADF;
8761 return -1;
8764 /* Perform text mode translation if required. */
8765 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8767 char * tmpbuf;
8768 const unsigned char * src = buffer;
8769 unsigned char * dst;
8770 int nbytes = count;
8772 SAFE_NALLOCA (tmpbuf, 2, count);
8773 dst = (unsigned char *)tmpbuf;
8775 while (1)
8777 unsigned char *next;
8778 /* Copy next line or remaining bytes. */
8779 next = _memccpy (dst, src, '\n', nbytes);
8780 if (next)
8782 /* Copied one line ending with '\n'. */
8783 int copied = next - dst;
8784 nbytes -= copied;
8785 src += copied;
8786 /* Insert '\r' before '\n'. */
8787 next[-1] = '\r';
8788 next[0] = '\n';
8789 dst = next + 1;
8790 count++;
8792 else
8793 /* Copied remaining partial line -> now finished. */
8794 break;
8796 buffer = tmpbuf;
8800 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8802 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8803 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8804 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8805 DWORD active = 0;
8807 /* This is async (a.k.a. "overlapped") I/O, so the return value
8808 of FALSE from WriteFile means either an error or the output
8809 will be completed asynchronously (ERROR_IO_PENDING). */
8810 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8812 if (GetLastError () != ERROR_IO_PENDING)
8814 errno = EIO;
8815 nchars = -1;
8817 else
8819 /* Wait for the write to complete, and watch C-g while
8820 at that. */
8821 if (detect_input_pending ())
8822 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8823 INFINITE, QS_ALLINPUT);
8824 else
8825 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8826 switch (active)
8828 case WAIT_OBJECT_0:
8829 /* User pressed C-g, cancel write, then leave.
8830 Don't bother cleaning up as we may only get stuck
8831 in buggy drivers. */
8832 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8833 CancelIo (hnd);
8834 errno = EIO; /* Why not EINTR? */
8835 nchars = -1;
8836 break;
8837 case WAIT_OBJECT_0 + 1:
8838 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8840 errno = EIO;
8841 nchars = -1;
8843 break;
8848 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8850 unsigned long nblock = 0;
8851 if (winsock_lib == NULL) emacs_abort ();
8853 child_process *cp = fd_info[fd].cp;
8855 /* If this is a non-blocking socket whose connection is in
8856 progress or terminated with an error already, return the
8857 proper error code to the caller. */
8858 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8860 /* In case connection is in progress, ENOTCONN that would
8861 result from calling pfn_send is not what callers expect. */
8862 if (cp->status != STATUS_CONNECT_FAILED)
8864 errno = EWOULDBLOCK;
8865 return -1;
8867 /* In case connection failed, use the actual error code
8868 stashed by '_sys_wait_connect' in cp->errcode. */
8869 else if (cp->errcode != 0)
8871 pfn_WSASetLastError (cp->errcode);
8872 set_errno ();
8873 return -1;
8877 /* TODO: implement select() properly so non-blocking I/O works. */
8878 /* For now, make sure the write blocks. */
8879 if (fd_info[fd].flags & FILE_NDELAY)
8880 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8882 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8884 if (nchars == SOCKET_ERROR)
8886 set_errno ();
8887 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8888 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8891 /* Set the socket back to non-blocking if it was before,
8892 for other operations that support it. */
8893 if (fd_info[fd].flags & FILE_NDELAY)
8895 nblock = 1;
8896 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8899 else
8901 /* Some networked filesystems don't like too large writes, so
8902 break them into smaller chunks. See the Comments section of
8903 the MSDN documentation of WriteFile for details behind the
8904 choice of the value of CHUNK below. See also the thread
8905 http://thread.gmane.org/gmane.comp.version-control.git/145294
8906 in the git mailing list. */
8907 const unsigned char *p = buffer;
8908 const bool is_pipe = (fd < MAXDESC
8909 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8910 == (FILE_PIPE | FILE_NDELAY)));
8911 /* Some programs, notably Node.js's node.exe, seem to never
8912 completely empty the pipe, so writing more than the size of
8913 the pipe's buffer always returns ENOSPC, and we loop forever
8914 between send_process and here. As a workaround, write no
8915 more than the pipe's buffer can hold. */
8916 DWORD pipe_buffer_size;
8917 if (is_pipe)
8919 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8920 NULL, &pipe_buffer_size, NULL, NULL))
8922 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8923 pipe_buffer_size = 4096;
8926 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8928 nchars = 0;
8929 errno = 0;
8930 while (count > 0)
8932 unsigned this_chunk = count < chunk ? count : chunk;
8933 int n = _write (fd, p, this_chunk);
8935 if (n > 0)
8936 nchars += n;
8937 if (n < 0)
8939 /* When there's no buffer space in a pipe that is in the
8940 non-blocking mode, _write returns ENOSPC. We return
8941 EAGAIN instead, which should trigger the logic in
8942 send_process that enters waiting loop and calls
8943 wait_reading_process_output to allow process input to
8944 be accepted during the wait. Those calls to
8945 wait_reading_process_output allow sys_select to
8946 notice when process input becomes available, thus
8947 avoiding deadlock whereby each side of the pipe is
8948 blocked on write, waiting for the other party to read
8949 its end of the pipe. */
8950 if (errno == ENOSPC && is_pipe)
8951 errno = EAGAIN;
8952 if (nchars == 0)
8953 nchars = -1;
8954 break;
8956 else if (n < this_chunk)
8957 break;
8958 count -= n;
8959 p += n;
8963 SAFE_FREE ();
8964 return nchars;
8968 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8970 /* Return information about network interface IFNAME, or about all
8971 interfaces (if IFNAME is nil). */
8972 static Lisp_Object
8973 network_interface_get_info (Lisp_Object ifname)
8975 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8976 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8977 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8978 Lisp_Object res = Qnil;
8980 if (retval == ERROR_BUFFER_OVERFLOW)
8982 ainfo = xrealloc (ainfo, ainfo_len);
8983 retval = get_adapters_info (ainfo, &ainfo_len);
8986 if (retval == ERROR_SUCCESS)
8988 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8989 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8990 int if_num;
8991 struct sockaddr_in sa;
8993 /* For the below, we need some winsock functions, so make sure
8994 the winsock DLL is loaded. If we cannot successfully load
8995 it, they will have no use of the information we provide,
8996 anyway, so punt. */
8997 if (!winsock_lib && !init_winsock (1))
8998 goto done;
9000 for (adapter = ainfo; adapter; adapter = adapter->Next)
9002 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
9003 u_long ip_addr;
9004 /* Present Unix-compatible interface names, instead of the
9005 Windows names, which are really GUIDs not readable by
9006 humans. */
9007 static const char *ifmt[] = {
9008 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
9009 "lo", "ifx%d"
9011 enum {
9012 NONE = -1,
9013 ETHERNET = 0,
9014 TOKENRING = 1,
9015 FDDI = 2,
9016 PPP = 3,
9017 SLIP = 4,
9018 WLAN = 5,
9019 LOOPBACK = 6,
9020 OTHER_IF = 7
9021 } ifmt_idx;
9023 switch (adapter->Type)
9025 case MIB_IF_TYPE_ETHERNET:
9026 /* Windows before Vista reports wireless adapters as
9027 Ethernet. Work around by looking at the Description
9028 string. */
9029 if (strstr (adapter->Description, "Wireless "))
9031 ifmt_idx = WLAN;
9032 if_num = wlan_count++;
9034 else
9036 ifmt_idx = ETHERNET;
9037 if_num = eth_count++;
9039 break;
9040 case MIB_IF_TYPE_TOKENRING:
9041 ifmt_idx = TOKENRING;
9042 if_num = tr_count++;
9043 break;
9044 case MIB_IF_TYPE_FDDI:
9045 ifmt_idx = FDDI;
9046 if_num = fddi_count++;
9047 break;
9048 case MIB_IF_TYPE_PPP:
9049 ifmt_idx = PPP;
9050 if_num = ppp_count++;
9051 break;
9052 case MIB_IF_TYPE_SLIP:
9053 ifmt_idx = SLIP;
9054 if_num = sl_count++;
9055 break;
9056 case IF_TYPE_IEEE80211:
9057 ifmt_idx = WLAN;
9058 if_num = wlan_count++;
9059 break;
9060 case MIB_IF_TYPE_LOOPBACK:
9061 if (lo_count < 0)
9063 ifmt_idx = LOOPBACK;
9064 if_num = lo_count++;
9066 else
9067 ifmt_idx = NONE;
9068 break;
9069 default:
9070 ifmt_idx = OTHER_IF;
9071 if_num = ifx_count++;
9072 break;
9074 if (ifmt_idx == NONE)
9075 continue;
9076 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9078 sa.sin_family = AF_INET;
9079 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9080 if (ip_addr == INADDR_NONE)
9082 /* Bogus address, skip this interface. */
9083 continue;
9085 sa.sin_addr.s_addr = ip_addr;
9086 sa.sin_port = 0;
9087 if (NILP (ifname))
9088 res = Fcons (Fcons (build_string (namebuf),
9089 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9090 sizeof (struct sockaddr))),
9091 res);
9092 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9094 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9095 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9096 Lisp_Object flags = Qnil;
9097 int n;
9098 u_long net_mask;
9100 /* Flags. We guess most of them by type, since the
9101 Windows flags are different and hard to get by. */
9102 flags = Fcons (intern ("up"), flags);
9103 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9105 flags = Fcons (intern ("broadcast"), flags);
9106 flags = Fcons (intern ("multicast"), flags);
9108 flags = Fcons (intern ("running"), flags);
9109 if (ifmt_idx == PPP)
9111 flags = Fcons (intern ("pointopoint"), flags);
9112 flags = Fcons (intern ("noarp"), flags);
9114 if (adapter->HaveWins)
9115 flags = Fcons (intern ("WINS"), flags);
9116 if (adapter->DhcpEnabled)
9117 flags = Fcons (intern ("dynamic"), flags);
9119 res = Fcons (flags, res);
9121 /* Hardware address and its family. */
9122 for (n = 0; n < adapter->AddressLength; n++)
9123 p->contents[n] = make_number ((int) adapter->Address[n]);
9124 /* Windows does not support AF_LINK or AF_PACKET family
9125 of addresses. Use an arbitrary family number that is
9126 identical to what GNU/Linux returns. */
9127 res = Fcons (Fcons (make_number (1), hwaddr), res);
9129 /* Network mask. */
9130 sa.sin_family = AF_INET;
9131 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9132 if (net_mask != INADDR_NONE)
9134 sa.sin_addr.s_addr = net_mask;
9135 sa.sin_port = 0;
9136 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9137 sizeof (struct sockaddr)),
9138 res);
9140 else
9141 res = Fcons (Qnil, res);
9143 sa.sin_family = AF_INET;
9144 if (ip_addr != INADDR_NONE)
9146 /* Broadcast address is only reported by
9147 GetAdaptersAddresses, which is of limited
9148 availability. Generate it on our own. */
9149 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9151 sa.sin_addr.s_addr = bcast_addr;
9152 sa.sin_port = 0;
9153 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9154 sizeof (struct sockaddr)),
9155 res);
9157 /* IP address. */
9158 sa.sin_addr.s_addr = ip_addr;
9159 sa.sin_port = 0;
9160 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9161 sizeof (struct sockaddr)),
9162 res);
9164 else
9165 res = Fcons (Qnil, Fcons (Qnil, res));
9168 /* GetAdaptersInfo is documented to not report loopback
9169 interfaces, so we generate one out of thin air. */
9170 if (!lo_count)
9172 sa.sin_family = AF_INET;
9173 sa.sin_port = 0;
9174 if (NILP (ifname))
9176 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9177 res = Fcons (Fcons (build_string ("lo"),
9178 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9179 sizeof (struct sockaddr))),
9180 res);
9182 else if (strcmp (SSDATA (ifname), "lo") == 0)
9184 res = Fcons (Fcons (intern ("running"),
9185 Fcons (intern ("loopback"),
9186 Fcons (intern ("up"), Qnil))), Qnil);
9187 /* 772 is what 3 different GNU/Linux systems report for
9188 the loopback interface. */
9189 res = Fcons (Fcons (make_number (772),
9190 Fmake_vector (make_number (6),
9191 make_number (0))),
9192 res);
9193 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9194 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9195 sizeof (struct sockaddr)),
9196 res);
9197 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
9198 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9199 sizeof (struct sockaddr)),
9200 res);
9201 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9202 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9203 sizeof (struct sockaddr)),
9204 res);
9210 done:
9211 xfree (ainfo);
9212 return res;
9215 Lisp_Object
9216 network_interface_list (void)
9218 return network_interface_get_info (Qnil);
9221 Lisp_Object
9222 network_interface_info (Lisp_Object ifname)
9224 CHECK_STRING (ifname);
9225 return network_interface_get_info (ifname);
9229 /* The Windows CRT functions are "optimized for speed", so they don't
9230 check for timezone and DST changes if they were last called less
9231 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9232 all Emacs features that repeatedly call time functions (e.g.,
9233 display-time) are in real danger of missing timezone and DST
9234 changes. Calling tzset before each localtime call fixes that. */
9235 struct tm *
9236 sys_localtime (const time_t *t)
9238 tzset ();
9239 return localtime (t);
9244 /* Try loading LIBRARY_ID from the file(s) specified in
9245 Vdynamic_library_alist. If the library is loaded successfully,
9246 return the handle of the DLL, and record the filename in the
9247 property :loaded-from of LIBRARY_ID. If the library could not be
9248 found, or when it was already loaded (because the handle is not
9249 recorded anywhere, and so is lost after use), return NULL.
9251 We could also save the handle in :loaded-from, but currently
9252 there's no use case for it. */
9253 HMODULE
9254 w32_delayed_load (Lisp_Object library_id)
9256 HMODULE dll_handle = NULL;
9258 CHECK_SYMBOL (library_id);
9260 if (CONSP (Vdynamic_library_alist)
9261 && NILP (Fassq (library_id, Vlibrary_cache)))
9263 Lisp_Object found = Qnil;
9264 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9266 if (CONSP (dlls))
9267 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9269 Lisp_Object dll = XCAR (dlls);
9270 char name[MAX_UTF8_PATH];
9271 DWORD res = -1;
9273 CHECK_STRING (dll);
9274 dll = ENCODE_FILE (dll);
9275 if (w32_unicode_filenames)
9277 wchar_t name_w[MAX_PATH];
9279 filename_to_utf16 (SSDATA (dll), name_w);
9280 dll_handle = LoadLibraryW (name_w);
9281 if (dll_handle)
9283 res = GetModuleFileNameW (dll_handle, name_w,
9284 sizeof (name_w));
9285 if (res > 0)
9286 filename_from_utf16 (name_w, name);
9289 else
9291 char name_a[MAX_PATH];
9293 filename_to_ansi (SSDATA (dll), name_a);
9294 dll_handle = LoadLibraryA (name_a);
9295 if (dll_handle)
9297 res = GetModuleFileNameA (dll_handle, name_a,
9298 sizeof (name_a));
9299 if (res > 0)
9300 filename_from_ansi (name_a, name);
9303 if (dll_handle)
9305 ptrdiff_t len = strlen (name);
9306 found = Fcons (dll,
9307 (res > 0)
9308 /* Possibly truncated */
9309 ? make_specified_string (name, -1, len, 1)
9310 : Qnil);
9311 /* This prevents thread start and end notifications
9312 from being sent to the DLL, for every thread we
9313 start. We don't need those notifications because
9314 threads we create never use any of these DLLs, only
9315 the main thread uses them. This is supposed to
9316 speed up thread creation. */
9317 DisableThreadLibraryCalls (dll_handle);
9318 break;
9322 Fput (library_id, QCloaded_from, found);
9325 return dll_handle;
9329 void
9330 check_windows_init_file (void)
9332 /* A common indication that Emacs is not installed properly is when
9333 it cannot find the Windows installation file. If this file does
9334 not exist in the expected place, tell the user. */
9336 if (!noninteractive && !inhibit_window_system
9337 /* Vload_path is not yet initialized when we are loading
9338 loadup.el. */
9339 && NILP (Vpurify_flag))
9341 Lisp_Object init_file;
9342 int fd;
9344 /* Implementation note: this function runs early during Emacs
9345 startup, before startup.el is run. So Vload_path is still in
9346 its initial unibyte form, but it holds UTF-8 encoded file
9347 names, since init_callproc was already called. So we do not
9348 need to ENCODE_FILE here, but we do need to convert the file
9349 names from UTF-8 to ANSI. */
9350 init_file = build_string ("term/w32-win");
9351 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9352 if (fd < 0)
9354 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9355 char *init_file_name = SSDATA (init_file);
9356 char *load_path = SSDATA (load_path_print);
9357 char *buffer = alloca (1024
9358 + strlen (init_file_name)
9359 + strlen (load_path));
9360 char *msg = buffer;
9361 int needed;
9363 sprintf (buffer,
9364 "The Emacs Windows initialization file \"%s.el\" "
9365 "could not be found in your Emacs installation. "
9366 "Emacs checked the following directories for this file:\n"
9367 "\n%s\n\n"
9368 "When Emacs cannot find this file, it usually means that it "
9369 "was not installed properly, or its distribution file was "
9370 "not unpacked properly.\nSee the README.W32 file in the "
9371 "top-level Emacs directory for more information.",
9372 init_file_name, load_path);
9373 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9374 buffer, -1, NULL, 0);
9375 if (needed > 0)
9377 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9379 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9380 -1, msg_w, needed);
9381 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9382 NULL, 0, NULL, NULL);
9383 if (needed > 0)
9385 char *msg_a = alloca (needed + 1);
9387 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9388 NULL, NULL);
9389 msg = msg_a;
9392 MessageBox (NULL,
9393 msg,
9394 "Emacs Abort Dialog",
9395 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9396 /* Use the low-level system abort. */
9397 abort ();
9399 else
9401 _close (fd);
9406 void
9407 term_ntproc (int ignored)
9409 (void)ignored;
9411 term_timers ();
9413 /* shutdown the socket interface if necessary */
9414 term_winsock ();
9416 term_w32select ();
9419 void
9420 init_ntproc (int dumping)
9422 sigset_t initial_mask = 0;
9424 /* Initialize the socket interface now if available and requested by
9425 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9426 delayed until open-network-stream is called (w32-has-winsock can
9427 also be used to dynamically load or reload winsock).
9429 Conveniently, init_environment is called before us, so
9430 PRELOAD_WINSOCK can be set in the registry. */
9432 /* Always initialize this correctly. */
9433 winsock_lib = NULL;
9435 if (getenv ("PRELOAD_WINSOCK") != NULL)
9436 init_winsock (TRUE);
9438 /* Initial preparation for subprocess support: replace our standard
9439 handles with non-inheritable versions. */
9441 HANDLE parent;
9442 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9443 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9444 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9446 parent = GetCurrentProcess ();
9448 /* ignore errors when duplicating and closing; typically the
9449 handles will be invalid when running as a gui program. */
9450 DuplicateHandle (parent,
9451 GetStdHandle (STD_INPUT_HANDLE),
9452 parent,
9453 &stdin_save,
9455 FALSE,
9456 DUPLICATE_SAME_ACCESS);
9458 DuplicateHandle (parent,
9459 GetStdHandle (STD_OUTPUT_HANDLE),
9460 parent,
9461 &stdout_save,
9463 FALSE,
9464 DUPLICATE_SAME_ACCESS);
9466 DuplicateHandle (parent,
9467 GetStdHandle (STD_ERROR_HANDLE),
9468 parent,
9469 &stderr_save,
9471 FALSE,
9472 DUPLICATE_SAME_ACCESS);
9474 fclose (stdin);
9475 fclose (stdout);
9476 fclose (stderr);
9478 if (stdin_save != INVALID_HANDLE_VALUE)
9479 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9480 else
9481 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9482 _fdopen (0, "r");
9484 if (stdout_save != INVALID_HANDLE_VALUE)
9485 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9486 else
9487 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9488 _fdopen (1, "w");
9490 if (stderr_save != INVALID_HANDLE_VALUE)
9491 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9492 else
9493 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9494 _fdopen (2, "w");
9497 /* unfortunately, atexit depends on implementation of malloc */
9498 /* atexit (term_ntproc); */
9499 if (!dumping)
9501 /* Make sure we start with all signals unblocked. */
9502 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9503 signal (SIGABRT, term_ntproc);
9505 init_timers ();
9507 /* determine which drives are fixed, for GetCachedVolumeInformation */
9509 /* GetDriveType must have trailing backslash. */
9510 char drive[] = "A:\\";
9512 /* Loop over all possible drive letters */
9513 while (*drive <= 'Z')
9515 /* Record if this drive letter refers to a fixed drive. */
9516 fixed_drives[DRIVE_INDEX (*drive)] =
9517 (GetDriveType (drive) == DRIVE_FIXED);
9519 (*drive)++;
9522 /* Reset the volume info cache. */
9523 volume_cache = NULL;
9528 shutdown_handler ensures that buffers' autosave files are
9529 up to date when the user logs off, or the system shuts down.
9531 static BOOL WINAPI
9532 shutdown_handler (DWORD type)
9534 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9535 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9536 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9537 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9539 /* Shut down cleanly, making sure autosave files are up to date. */
9540 shut_down_emacs (0, Qnil);
9543 /* Allow other handlers to handle this signal. */
9544 return FALSE;
9547 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9548 NT, return a handle to GDI32.DLL. */
9549 HANDLE
9550 maybe_load_unicows_dll (void)
9552 if (os_subtype == OS_9X)
9554 HANDLE ret = LoadLibrary ("Unicows.dll");
9555 if (ret)
9557 /* These two functions are present on Windows 9X as stubs
9558 that always fail. We need the real implementations from
9559 UNICOWS.DLL, so we must call these functions through
9560 pointers, and assign the correct addresses to these
9561 pointers at program startup (see emacs.c, which calls
9562 this function early on). */
9563 pMultiByteToWideChar =
9564 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9565 pWideCharToMultiByte =
9566 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9567 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9568 return ret;
9570 else
9572 int button;
9574 button = MessageBox (NULL,
9575 "Emacs cannot load the UNICOWS.DLL library.\n"
9576 "This library is essential for using Emacs\n"
9577 "on this system. You need to install it.\n\n"
9578 "Emacs will exit when you click OK.",
9579 "Emacs cannot load UNICOWS.DLL",
9580 MB_ICONERROR | MB_TASKMODAL
9581 | MB_SETFOREGROUND | MB_OK);
9582 switch (button)
9584 case IDOK:
9585 default:
9586 exit (1);
9590 else
9592 /* On NT family of Windows, these two functions are always
9593 linked in, so we just assign their addresses to the 2
9594 pointers; no need for the LoadLibrary dance. */
9595 pMultiByteToWideChar = MultiByteToWideChar;
9596 pWideCharToMultiByte = WideCharToMultiByte;
9597 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9598 if (w32_major_version < 5)
9599 multiByteToWideCharFlags = 0;
9600 else
9601 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9602 return LoadLibrary ("Gdi32.dll");
9607 globals_of_w32 is used to initialize those global variables that
9608 must always be initialized on startup even when the global variable
9609 initialized is non zero (see the function main in emacs.c).
9611 void
9612 globals_of_w32 (void)
9614 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9616 get_process_times_fn = (GetProcessTimes_Proc)
9617 GetProcAddress (kernel32, "GetProcessTimes");
9619 DEFSYM (QCloaded_from, ":loaded-from");
9621 g_b_init_is_windows_9x = 0;
9622 g_b_init_open_process_token = 0;
9623 g_b_init_get_token_information = 0;
9624 g_b_init_lookup_account_sid = 0;
9625 g_b_init_get_sid_sub_authority = 0;
9626 g_b_init_get_sid_sub_authority_count = 0;
9627 g_b_init_get_security_info = 0;
9628 g_b_init_get_file_security_w = 0;
9629 g_b_init_get_file_security_a = 0;
9630 g_b_init_get_security_descriptor_owner = 0;
9631 g_b_init_get_security_descriptor_group = 0;
9632 g_b_init_is_valid_sid = 0;
9633 g_b_init_create_toolhelp32_snapshot = 0;
9634 g_b_init_process32_first = 0;
9635 g_b_init_process32_next = 0;
9636 g_b_init_open_thread_token = 0;
9637 g_b_init_impersonate_self = 0;
9638 g_b_init_revert_to_self = 0;
9639 g_b_init_get_process_memory_info = 0;
9640 g_b_init_get_process_working_set_size = 0;
9641 g_b_init_global_memory_status = 0;
9642 g_b_init_global_memory_status_ex = 0;
9643 g_b_init_equal_sid = 0;
9644 g_b_init_copy_sid = 0;
9645 g_b_init_get_length_sid = 0;
9646 g_b_init_get_native_system_info = 0;
9647 g_b_init_get_system_times = 0;
9648 g_b_init_create_symbolic_link_w = 0;
9649 g_b_init_create_symbolic_link_a = 0;
9650 g_b_init_get_security_descriptor_dacl = 0;
9651 g_b_init_convert_sd_to_sddl = 0;
9652 g_b_init_convert_sddl_to_sd = 0;
9653 g_b_init_is_valid_security_descriptor = 0;
9654 g_b_init_set_file_security_w = 0;
9655 g_b_init_set_file_security_a = 0;
9656 g_b_init_set_named_security_info_w = 0;
9657 g_b_init_set_named_security_info_a = 0;
9658 g_b_init_get_adapters_info = 0;
9659 g_b_init_compare_string_w = 0;
9660 num_of_processors = 0;
9661 /* The following sets a handler for shutdown notifications for
9662 console apps. This actually applies to Emacs in both console and
9663 GUI modes, since we had to fool windows into thinking emacs is a
9664 console application to get console mode to work. */
9665 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9667 /* "None" is the default group name on standalone workstations. */
9668 strcpy (dflt_group_name, "None");
9670 /* Reset, in case it has some value inherited from dump time. */
9671 w32_stat_get_owner_group = 0;
9673 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9674 (a.k.a. "wide") APIs to invoke functions that accept file
9675 names. */
9676 if (is_windows_9x ())
9677 w32_unicode_filenames = 0;
9678 else
9679 w32_unicode_filenames = 1;
9681 #ifdef HAVE_MODULES
9682 dynlib_reset_last_error ();
9683 #endif
9685 w32_crypto_hprov = (HCRYPTPROV)0;
9688 /* For make-serial-process */
9690 serial_open (Lisp_Object port_obj)
9692 char *port = SSDATA (port_obj);
9693 HANDLE hnd;
9694 child_process *cp;
9695 int fd = -1;
9697 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9698 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9699 if (hnd == INVALID_HANDLE_VALUE)
9700 error ("Could not open %s", port);
9701 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9702 if (fd == -1)
9703 error ("Could not open %s", port);
9705 cp = new_child ();
9706 if (!cp)
9707 error ("Could not create child process");
9708 cp->fd = fd;
9709 cp->status = STATUS_READ_ACKNOWLEDGED;
9710 fd_info[ fd ].hnd = hnd;
9711 fd_info[ fd ].flags |=
9712 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9713 if (fd_info[ fd ].cp != NULL)
9715 error ("fd_info[fd = %d] is already in use", fd);
9717 fd_info[ fd ].cp = cp;
9718 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9719 if (cp->ovl_read.hEvent == NULL)
9720 error ("Could not create read event");
9721 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9722 if (cp->ovl_write.hEvent == NULL)
9723 error ("Could not create write event");
9725 return fd;
9728 /* For serial-process-configure */
9729 void
9730 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9732 Lisp_Object childp2 = Qnil;
9733 Lisp_Object tem = Qnil;
9734 HANDLE hnd;
9735 DCB dcb;
9736 COMMTIMEOUTS ct;
9737 char summary[4] = "???"; /* This usually becomes "8N1". */
9739 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9740 error ("Not a serial process");
9741 hnd = fd_info[ p->outfd ].hnd;
9743 childp2 = Fcopy_sequence (p->childp);
9745 /* Initialize timeouts for blocking read and blocking write. */
9746 if (!GetCommTimeouts (hnd, &ct))
9747 error ("GetCommTimeouts() failed");
9748 ct.ReadIntervalTimeout = 0;
9749 ct.ReadTotalTimeoutMultiplier = 0;
9750 ct.ReadTotalTimeoutConstant = 0;
9751 ct.WriteTotalTimeoutMultiplier = 0;
9752 ct.WriteTotalTimeoutConstant = 0;
9753 if (!SetCommTimeouts (hnd, &ct))
9754 error ("SetCommTimeouts() failed");
9755 /* Read port attributes and prepare default configuration. */
9756 memset (&dcb, 0, sizeof (dcb));
9757 dcb.DCBlength = sizeof (DCB);
9758 if (!GetCommState (hnd, &dcb))
9759 error ("GetCommState() failed");
9760 dcb.fBinary = TRUE;
9761 dcb.fNull = FALSE;
9762 dcb.fAbortOnError = FALSE;
9763 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9764 dcb.ErrorChar = 0;
9765 dcb.EofChar = 0;
9766 dcb.EvtChar = 0;
9768 /* Configure speed. */
9769 if (!NILP (Fplist_member (contact, QCspeed)))
9770 tem = Fplist_get (contact, QCspeed);
9771 else
9772 tem = Fplist_get (p->childp, QCspeed);
9773 CHECK_NUMBER (tem);
9774 dcb.BaudRate = XINT (tem);
9775 childp2 = Fplist_put (childp2, QCspeed, tem);
9777 /* Configure bytesize. */
9778 if (!NILP (Fplist_member (contact, QCbytesize)))
9779 tem = Fplist_get (contact, QCbytesize);
9780 else
9781 tem = Fplist_get (p->childp, QCbytesize);
9782 if (NILP (tem))
9783 tem = make_number (8);
9784 CHECK_NUMBER (tem);
9785 if (XINT (tem) != 7 && XINT (tem) != 8)
9786 error (":bytesize must be nil (8), 7, or 8");
9787 dcb.ByteSize = XINT (tem);
9788 summary[0] = XINT (tem) + '0';
9789 childp2 = Fplist_put (childp2, QCbytesize, tem);
9791 /* Configure parity. */
9792 if (!NILP (Fplist_member (contact, QCparity)))
9793 tem = Fplist_get (contact, QCparity);
9794 else
9795 tem = Fplist_get (p->childp, QCparity);
9796 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9797 error (":parity must be nil (no parity), `even', or `odd'");
9798 dcb.fParity = FALSE;
9799 dcb.Parity = NOPARITY;
9800 dcb.fErrorChar = FALSE;
9801 if (NILP (tem))
9803 summary[1] = 'N';
9805 else if (EQ (tem, Qeven))
9807 summary[1] = 'E';
9808 dcb.fParity = TRUE;
9809 dcb.Parity = EVENPARITY;
9810 dcb.fErrorChar = TRUE;
9812 else if (EQ (tem, Qodd))
9814 summary[1] = 'O';
9815 dcb.fParity = TRUE;
9816 dcb.Parity = ODDPARITY;
9817 dcb.fErrorChar = TRUE;
9819 childp2 = Fplist_put (childp2, QCparity, tem);
9821 /* Configure stopbits. */
9822 if (!NILP (Fplist_member (contact, QCstopbits)))
9823 tem = Fplist_get (contact, QCstopbits);
9824 else
9825 tem = Fplist_get (p->childp, QCstopbits);
9826 if (NILP (tem))
9827 tem = make_number (1);
9828 CHECK_NUMBER (tem);
9829 if (XINT (tem) != 1 && XINT (tem) != 2)
9830 error (":stopbits must be nil (1 stopbit), 1, or 2");
9831 summary[2] = XINT (tem) + '0';
9832 if (XINT (tem) == 1)
9833 dcb.StopBits = ONESTOPBIT;
9834 else if (XINT (tem) == 2)
9835 dcb.StopBits = TWOSTOPBITS;
9836 childp2 = Fplist_put (childp2, QCstopbits, tem);
9838 /* Configure flowcontrol. */
9839 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9840 tem = Fplist_get (contact, QCflowcontrol);
9841 else
9842 tem = Fplist_get (p->childp, QCflowcontrol);
9843 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9844 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9845 dcb.fOutxCtsFlow = FALSE;
9846 dcb.fOutxDsrFlow = FALSE;
9847 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9848 dcb.fDsrSensitivity = FALSE;
9849 dcb.fTXContinueOnXoff = FALSE;
9850 dcb.fOutX = FALSE;
9851 dcb.fInX = FALSE;
9852 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9853 dcb.XonChar = 17; /* Control-Q */
9854 dcb.XoffChar = 19; /* Control-S */
9855 if (NILP (tem))
9857 /* Already configured. */
9859 else if (EQ (tem, Qhw))
9861 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9862 dcb.fOutxCtsFlow = TRUE;
9864 else if (EQ (tem, Qsw))
9866 dcb.fOutX = TRUE;
9867 dcb.fInX = TRUE;
9869 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9871 /* Activate configuration. */
9872 if (!SetCommState (hnd, &dcb))
9873 error ("SetCommState() failed");
9875 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9876 pset_childp (p, childp2);
9879 /* For make-pipe-process */
9880 void
9881 register_aux_fd (int infd)
9883 child_process *cp;
9885 cp = new_child ();
9886 if (!cp)
9887 error ("Could not create child process");
9888 cp->fd = infd;
9889 cp->status = STATUS_READ_ACKNOWLEDGED;
9891 if (fd_info[ infd ].cp != NULL)
9893 error ("fd_info[fd = %d] is already in use", infd);
9895 fd_info[ infd ].cp = cp;
9896 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9899 #ifdef HAVE_GNUTLS
9901 ssize_t
9902 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9904 int n, err;
9905 struct Lisp_Process *process = (struct Lisp_Process *)p;
9906 int fd = process->infd;
9908 n = sys_read (fd, (char*)buf, sz);
9910 if (n >= 0)
9911 return n;
9913 err = errno;
9915 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9916 if (err == EWOULDBLOCK)
9917 err = EAGAIN;
9919 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9921 return -1;
9924 ssize_t
9925 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9927 struct Lisp_Process *process = (struct Lisp_Process *)p;
9928 int fd = process->outfd;
9929 ssize_t n = sys_write (fd, buf, sz);
9931 /* 0 or more bytes written means everything went fine. */
9932 if (n >= 0)
9933 return n;
9935 /* Negative bytes written means we got an error in errno.
9936 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9937 emacs_gnutls_transport_set_errno (process->gnutls_state,
9938 errno == EWOULDBLOCK ? EAGAIN : errno);
9940 return -1;
9942 #endif /* HAVE_GNUTLS */
9944 /* end of w32.c */