* src/casefiddle.c (casify_word): Return Qnil.
[emacs.git] / src / w32.c
blob1db34260978825b4fe9190ebb5e4fec9bf2a77ce
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <float.h> /* for DBL_EPSILON */
29 #include <io.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <sys/file.h>
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
36 #include <sys/time.h>
37 #include <sys/utime.h>
38 #include <math.h>
40 /* must include CRT headers *before* config.h */
42 #include <config.h>
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
45 #undef access
46 #undef chdir
47 #undef chmod
48 #undef creat
49 #undef ctime
50 #undef fopen
51 #undef link
52 #undef mkdir
53 #undef open
54 #undef rename
55 #undef rmdir
56 #undef unlink
58 #undef close
59 #undef dup
60 #undef dup2
61 #undef pipe
62 #undef read
63 #undef write
65 #undef strerror
67 #undef localtime
69 char *sys_ctime (const time_t *);
70 int sys_chdir (const char *);
71 int sys_creat (const char *, int);
72 FILE *sys_fopen (const char *, const char *);
73 int sys_mkdir (const char *);
74 int sys_open (const char *, int, int);
75 int sys_rename (char const *, char const *);
76 int sys_rmdir (const char *);
77 int sys_close (int);
78 int sys_dup2 (int, int);
79 int sys_read (int, char *, unsigned int);
80 int sys_write (int, const void *, unsigned int);
81 struct tm *sys_localtime (const time_t *);
83 #ifdef HAVE_MODULES
84 extern void dynlib_reset_last_error (void);
85 #endif
87 #include "lisp.h"
88 #include "epaths.h" /* for PATH_EXEC */
90 #include <pwd.h>
91 #include <grp.h>
93 /* MinGW64 defines these in its _mingw.h. */
94 #ifndef _ANONYMOUS_UNION
95 # define _ANONYMOUS_UNION
96 #endif
97 #ifndef _ANONYMOUS_STRUCT
98 # define _ANONYMOUS_STRUCT
99 #endif
100 #include <windows.h>
101 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
102 use a different name to avoid compilation problems. */
103 typedef struct _MEMORY_STATUS_EX {
104 DWORD dwLength;
105 DWORD dwMemoryLoad;
106 DWORDLONG ullTotalPhys;
107 DWORDLONG ullAvailPhys;
108 DWORDLONG ullTotalPageFile;
109 DWORDLONG ullAvailPageFile;
110 DWORDLONG ullTotalVirtual;
111 DWORDLONG ullAvailVirtual;
112 DWORDLONG ullAvailExtendedVirtual;
113 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
115 /* These are here so that GDB would know about these data types. This
116 allows attaching GDB to Emacs when a fatal exception is triggered
117 and Windows pops up the "application needs to be closed" dialog.
118 At that point, _gnu_exception_handler, the top-level exception
119 handler installed by the MinGW startup code, is somewhere on the
120 call-stack of the main thread, so going to that call frame and
121 looking at the argument to _gnu_exception_handler, which is a
122 PEXCEPTION_POINTERS pointer, can reveal the exception code
123 (excptr->ExceptionRecord->ExceptionCode) and the address where the
124 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
125 well as some additional information specific to the exception. */
126 PEXCEPTION_POINTERS excptr;
127 PEXCEPTION_RECORD excprec;
128 PCONTEXT ctxrec;
130 #include <lmcons.h>
131 #include <shlobj.h>
133 #include <tlhelp32.h>
134 #include <psapi.h>
135 #ifndef _MSC_VER
136 #include <w32api.h>
137 #endif
138 #if _WIN32_WINNT < 0x0500
139 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
140 /* This either is not in psapi.h or guarded by higher value of
141 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
142 defines it in psapi.h */
143 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
144 DWORD cb;
145 DWORD PageFaultCount;
146 SIZE_T PeakWorkingSetSize;
147 SIZE_T WorkingSetSize;
148 SIZE_T QuotaPeakPagedPoolUsage;
149 SIZE_T QuotaPagedPoolUsage;
150 SIZE_T QuotaPeakNonPagedPoolUsage;
151 SIZE_T QuotaNonPagedPoolUsage;
152 SIZE_T PagefileUsage;
153 SIZE_T PeakPagefileUsage;
154 SIZE_T PrivateUsage;
155 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
156 #endif
157 #endif
159 #include <winioctl.h>
160 #include <aclapi.h>
161 #include <sddl.h>
163 #include <sys/acl.h>
164 #include <acl.h>
166 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
167 define them by hand if not already defined. */
168 #ifndef SDDL_REVISION_1
169 #define SDDL_REVISION_1 1
170 #endif /* SDDL_REVISION_1 */
172 #if defined(_MSC_VER) || defined(MINGW_W64)
173 /* MSVC and MinGW64 don't provide the definition of
174 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
175 which cannot be included because it triggers conflicts with other
176 Windows API headers. So we define it here by hand. */
178 typedef struct _REPARSE_DATA_BUFFER {
179 ULONG ReparseTag;
180 USHORT ReparseDataLength;
181 USHORT Reserved;
182 union {
183 struct {
184 USHORT SubstituteNameOffset;
185 USHORT SubstituteNameLength;
186 USHORT PrintNameOffset;
187 USHORT PrintNameLength;
188 ULONG Flags;
189 WCHAR PathBuffer[1];
190 } SymbolicLinkReparseBuffer;
191 struct {
192 USHORT SubstituteNameOffset;
193 USHORT SubstituteNameLength;
194 USHORT PrintNameOffset;
195 USHORT PrintNameLength;
196 WCHAR PathBuffer[1];
197 } MountPointReparseBuffer;
198 struct {
199 UCHAR DataBuffer[1];
200 } GenericReparseBuffer;
201 } DUMMYUNIONNAME;
202 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
204 #ifndef FILE_DEVICE_FILE_SYSTEM
205 #define FILE_DEVICE_FILE_SYSTEM 9
206 #endif
207 #ifndef METHOD_BUFFERED
208 #define METHOD_BUFFERED 0
209 #endif
210 #ifndef FILE_ANY_ACCESS
211 #define FILE_ANY_ACCESS 0x00000000
212 #endif
213 #ifndef CTL_CODE
214 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
215 #endif
216 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
217 #ifndef FSCTL_GET_REPARSE_POINT
218 #define FSCTL_GET_REPARSE_POINT \
219 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
220 #endif
221 #endif
223 /* TCP connection support. */
224 #include <sys/socket.h>
225 #undef socket
226 #undef bind
227 #undef connect
228 #undef htons
229 #undef ntohs
230 #undef inet_addr
231 #undef gethostname
232 #undef gethostbyname
233 #undef getservbyname
234 #undef getpeername
235 #undef shutdown
236 #undef setsockopt
237 #undef listen
238 #undef getsockname
239 #undef accept
240 #undef recvfrom
241 #undef sendto
243 #include <iphlpapi.h> /* should be after winsock2.h */
245 #include <wincrypt.h>
247 #include <c-strcase.h>
248 #include <utimens.h> /* for fdutimens */
250 #include "w32.h"
251 #include <dirent.h>
252 #include "w32common.h"
253 #include "w32select.h"
254 #include "systime.h" /* for current_timespec, struct timespec */
255 #include "dispextern.h" /* for xstrcasecmp */
256 #include "coding.h" /* for Vlocale_coding_system */
258 #include "careadlinkat.h"
259 #include "allocator.h"
261 /* For Lisp_Process, serial_configure and serial_open. */
262 #include "process.h"
263 #include "systty.h"
265 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
266 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
268 static DWORD get_rid (PSID);
269 static int is_symlink (const char *);
270 static char * chase_symlinks (const char *);
271 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
272 static int restore_privilege (TOKEN_PRIVILEGES *);
273 static BOOL WINAPI revert_to_self (void);
275 static int sys_access (const char *, int);
276 extern void *e_malloc (size_t);
277 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
278 struct timespec *, void *);
279 extern int sys_dup (int);
284 /* Initialization states.
286 WARNING: If you add any more such variables for additional APIs,
287 you MUST add initialization for them to globals_of_w32
288 below. This is because these variables might get set
289 to non-NULL values during dumping, but the dumped Emacs
290 cannot reuse those values, because it could be run on a
291 different version of the OS, where API addresses are
292 different. */
293 static BOOL g_b_init_is_windows_9x;
294 static BOOL g_b_init_open_process_token;
295 static BOOL g_b_init_get_token_information;
296 static BOOL g_b_init_lookup_account_sid;
297 static BOOL g_b_init_get_sid_sub_authority;
298 static BOOL g_b_init_get_sid_sub_authority_count;
299 static BOOL g_b_init_get_security_info;
300 static BOOL g_b_init_get_file_security_w;
301 static BOOL g_b_init_get_file_security_a;
302 static BOOL g_b_init_get_security_descriptor_owner;
303 static BOOL g_b_init_get_security_descriptor_group;
304 static BOOL g_b_init_is_valid_sid;
305 static BOOL g_b_init_create_toolhelp32_snapshot;
306 static BOOL g_b_init_process32_first;
307 static BOOL g_b_init_process32_next;
308 static BOOL g_b_init_open_thread_token;
309 static BOOL g_b_init_impersonate_self;
310 static BOOL g_b_init_revert_to_self;
311 static BOOL g_b_init_get_process_memory_info;
312 static BOOL g_b_init_get_process_working_set_size;
313 static BOOL g_b_init_global_memory_status;
314 static BOOL g_b_init_global_memory_status_ex;
315 static BOOL g_b_init_get_length_sid;
316 static BOOL g_b_init_equal_sid;
317 static BOOL g_b_init_copy_sid;
318 static BOOL g_b_init_get_native_system_info;
319 static BOOL g_b_init_get_system_times;
320 static BOOL g_b_init_create_symbolic_link_w;
321 static BOOL g_b_init_create_symbolic_link_a;
322 static BOOL g_b_init_get_security_descriptor_dacl;
323 static BOOL g_b_init_convert_sd_to_sddl;
324 static BOOL g_b_init_convert_sddl_to_sd;
325 static BOOL g_b_init_is_valid_security_descriptor;
326 static BOOL g_b_init_set_file_security_w;
327 static BOOL g_b_init_set_file_security_a;
328 static BOOL g_b_init_set_named_security_info_w;
329 static BOOL g_b_init_set_named_security_info_a;
330 static BOOL g_b_init_get_adapters_info;
332 BOOL g_b_init_compare_string_w;
335 BEGIN: Wrapper functions around OpenProcessToken
336 and other functions in advapi32.dll that are only
337 supported in Windows NT / 2k / XP
339 /* ** Function pointer typedefs ** */
340 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
341 HANDLE ProcessHandle,
342 DWORD DesiredAccess,
343 PHANDLE TokenHandle);
344 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
345 HANDLE TokenHandle,
346 TOKEN_INFORMATION_CLASS TokenInformationClass,
347 LPVOID TokenInformation,
348 DWORD TokenInformationLength,
349 PDWORD ReturnLength);
350 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
351 HANDLE process_handle,
352 LPFILETIME creation_time,
353 LPFILETIME exit_time,
354 LPFILETIME kernel_time,
355 LPFILETIME user_time);
357 GetProcessTimes_Proc get_process_times_fn = NULL;
359 #ifdef _UNICODE
360 const char * const LookupAccountSid_Name = "LookupAccountSidW";
361 #else
362 const char * const LookupAccountSid_Name = "LookupAccountSidA";
363 #endif
364 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
365 LPCTSTR lpSystemName,
366 PSID Sid,
367 LPTSTR Name,
368 LPDWORD cbName,
369 LPTSTR DomainName,
370 LPDWORD cbDomainName,
371 PSID_NAME_USE peUse);
372 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
373 PSID pSid,
374 DWORD n);
375 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
376 PSID pSid);
377 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
378 HANDLE handle,
379 SE_OBJECT_TYPE ObjectType,
380 SECURITY_INFORMATION SecurityInfo,
381 PSID *ppsidOwner,
382 PSID *ppsidGroup,
383 PACL *ppDacl,
384 PACL *ppSacl,
385 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
386 typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
387 LPCWSTR lpFileName,
388 SECURITY_INFORMATION RequestedInformation,
389 PSECURITY_DESCRIPTOR pSecurityDescriptor,
390 DWORD nLength,
391 LPDWORD lpnLengthNeeded);
392 typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
393 LPCSTR lpFileName,
394 SECURITY_INFORMATION RequestedInformation,
395 PSECURITY_DESCRIPTOR pSecurityDescriptor,
396 DWORD nLength,
397 LPDWORD lpnLengthNeeded);
398 typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
399 LPCWSTR lpFileName,
400 SECURITY_INFORMATION SecurityInformation,
401 PSECURITY_DESCRIPTOR pSecurityDescriptor);
402 typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
403 LPCSTR lpFileName,
404 SECURITY_INFORMATION SecurityInformation,
405 PSECURITY_DESCRIPTOR pSecurityDescriptor);
406 typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
407 LPCWSTR lpObjectName,
408 SE_OBJECT_TYPE ObjectType,
409 SECURITY_INFORMATION SecurityInformation,
410 PSID psidOwner,
411 PSID psidGroup,
412 PACL pDacl,
413 PACL pSacl);
414 typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
415 LPCSTR lpObjectName,
416 SE_OBJECT_TYPE ObjectType,
417 SECURITY_INFORMATION SecurityInformation,
418 PSID psidOwner,
419 PSID psidGroup,
420 PACL pDacl,
421 PACL pSacl);
422 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
423 PSECURITY_DESCRIPTOR pSecurityDescriptor,
424 PSID *pOwner,
425 LPBOOL lpbOwnerDefaulted);
426 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
427 PSECURITY_DESCRIPTOR pSecurityDescriptor,
428 PSID *pGroup,
429 LPBOOL lpbGroupDefaulted);
430 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
431 PSECURITY_DESCRIPTOR pSecurityDescriptor,
432 LPBOOL lpbDaclPresent,
433 PACL *pDacl,
434 LPBOOL lpbDaclDefaulted);
435 typedef BOOL (WINAPI * IsValidSid_Proc) (
436 PSID sid);
437 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
438 DWORD dwFlags,
439 DWORD th32ProcessID);
440 typedef BOOL (WINAPI * Process32First_Proc) (
441 HANDLE hSnapshot,
442 LPPROCESSENTRY32 lppe);
443 typedef BOOL (WINAPI * Process32Next_Proc) (
444 HANDLE hSnapshot,
445 LPPROCESSENTRY32 lppe);
446 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
447 HANDLE ThreadHandle,
448 DWORD DesiredAccess,
449 BOOL OpenAsSelf,
450 PHANDLE TokenHandle);
451 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
452 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
453 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
454 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
455 HANDLE Process,
456 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
457 DWORD cb);
458 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
459 HANDLE hProcess,
460 PSIZE_T lpMinimumWorkingSetSize,
461 PSIZE_T lpMaximumWorkingSetSize);
462 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
463 LPMEMORYSTATUS lpBuffer);
464 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
465 LPMEMORY_STATUS_EX lpBuffer);
466 typedef BOOL (WINAPI * CopySid_Proc) (
467 DWORD nDestinationSidLength,
468 PSID pDestinationSid,
469 PSID pSourceSid);
470 typedef BOOL (WINAPI * EqualSid_Proc) (
471 PSID pSid1,
472 PSID pSid2);
473 typedef DWORD (WINAPI * GetLengthSid_Proc) (
474 PSID pSid);
475 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
476 LPSYSTEM_INFO lpSystemInfo);
477 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
478 LPFILETIME lpIdleTime,
479 LPFILETIME lpKernelTime,
480 LPFILETIME lpUserTime);
481 typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
482 LPCWSTR lpSymlinkFileName,
483 LPCWSTR lpTargetFileName,
484 DWORD dwFlags);
485 typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
486 LPCSTR lpSymlinkFileName,
487 LPCSTR lpTargetFileName,
488 DWORD dwFlags);
489 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
490 LPCTSTR StringSecurityDescriptor,
491 DWORD StringSDRevision,
492 PSECURITY_DESCRIPTOR *SecurityDescriptor,
493 PULONG SecurityDescriptorSize);
494 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
495 PSECURITY_DESCRIPTOR SecurityDescriptor,
496 DWORD RequestedStringSDRevision,
497 SECURITY_INFORMATION SecurityInformation,
498 LPTSTR *StringSecurityDescriptor,
499 PULONG StringSecurityDescriptorLen);
500 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
501 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
502 PIP_ADAPTER_INFO pAdapterInfo,
503 PULONG pOutBufLen);
505 int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
506 int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
507 DWORD multiByteToWideCharFlags;
509 /* ** A utility function ** */
510 static BOOL
511 is_windows_9x (void)
513 static BOOL s_b_ret = 0;
514 OSVERSIONINFO os_ver;
515 if (g_b_init_is_windows_9x == 0)
517 g_b_init_is_windows_9x = 1;
518 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
519 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
520 if (GetVersionEx (&os_ver))
522 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
525 return s_b_ret;
528 static Lisp_Object ltime (ULONGLONG);
530 /* Get total user and system times for get-internal-run-time.
531 Returns a list of integers if the times are provided by the OS
532 (NT derivatives), otherwise it returns the result of current-time. */
533 Lisp_Object w32_get_internal_run_time (void);
535 Lisp_Object
536 w32_get_internal_run_time (void)
538 if (get_process_times_fn)
540 FILETIME create, exit, kernel, user;
541 HANDLE proc = GetCurrentProcess ();
542 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
544 LARGE_INTEGER user_int, kernel_int, total;
545 user_int.LowPart = user.dwLowDateTime;
546 user_int.HighPart = user.dwHighDateTime;
547 kernel_int.LowPart = kernel.dwLowDateTime;
548 kernel_int.HighPart = kernel.dwHighDateTime;
549 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
550 return ltime (total.QuadPart);
554 return Fcurrent_time ();
557 /* ** The wrapper functions ** */
559 static BOOL WINAPI
560 open_process_token (HANDLE ProcessHandle,
561 DWORD DesiredAccess,
562 PHANDLE TokenHandle)
564 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
565 HMODULE hm_advapi32 = NULL;
566 if (is_windows_9x () == TRUE)
568 return FALSE;
570 if (g_b_init_open_process_token == 0)
572 g_b_init_open_process_token = 1;
573 hm_advapi32 = LoadLibrary ("Advapi32.dll");
574 s_pfn_Open_Process_Token =
575 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
577 if (s_pfn_Open_Process_Token == NULL)
579 return FALSE;
581 return (
582 s_pfn_Open_Process_Token (
583 ProcessHandle,
584 DesiredAccess,
585 TokenHandle)
589 static BOOL WINAPI
590 get_token_information (HANDLE TokenHandle,
591 TOKEN_INFORMATION_CLASS TokenInformationClass,
592 LPVOID TokenInformation,
593 DWORD TokenInformationLength,
594 PDWORD ReturnLength)
596 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
597 HMODULE hm_advapi32 = NULL;
598 if (is_windows_9x () == TRUE)
600 return FALSE;
602 if (g_b_init_get_token_information == 0)
604 g_b_init_get_token_information = 1;
605 hm_advapi32 = LoadLibrary ("Advapi32.dll");
606 s_pfn_Get_Token_Information =
607 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
609 if (s_pfn_Get_Token_Information == NULL)
611 return FALSE;
613 return (
614 s_pfn_Get_Token_Information (
615 TokenHandle,
616 TokenInformationClass,
617 TokenInformation,
618 TokenInformationLength,
619 ReturnLength)
623 static BOOL WINAPI
624 lookup_account_sid (LPCTSTR lpSystemName,
625 PSID Sid,
626 LPTSTR Name,
627 LPDWORD cbName,
628 LPTSTR DomainName,
629 LPDWORD cbDomainName,
630 PSID_NAME_USE peUse)
632 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
633 HMODULE hm_advapi32 = NULL;
634 if (is_windows_9x () == TRUE)
636 return FALSE;
638 if (g_b_init_lookup_account_sid == 0)
640 g_b_init_lookup_account_sid = 1;
641 hm_advapi32 = LoadLibrary ("Advapi32.dll");
642 s_pfn_Lookup_Account_Sid =
643 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
645 if (s_pfn_Lookup_Account_Sid == NULL)
647 return FALSE;
649 return (
650 s_pfn_Lookup_Account_Sid (
651 lpSystemName,
652 Sid,
653 Name,
654 cbName,
655 DomainName,
656 cbDomainName,
657 peUse)
661 static PDWORD WINAPI
662 get_sid_sub_authority (PSID pSid, DWORD n)
664 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
665 static DWORD zero = 0U;
666 HMODULE hm_advapi32 = NULL;
667 if (is_windows_9x () == TRUE)
669 return &zero;
671 if (g_b_init_get_sid_sub_authority == 0)
673 g_b_init_get_sid_sub_authority = 1;
674 hm_advapi32 = LoadLibrary ("Advapi32.dll");
675 s_pfn_Get_Sid_Sub_Authority =
676 (GetSidSubAuthority_Proc) GetProcAddress (
677 hm_advapi32, "GetSidSubAuthority");
679 if (s_pfn_Get_Sid_Sub_Authority == NULL)
681 return &zero;
683 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
686 static PUCHAR WINAPI
687 get_sid_sub_authority_count (PSID pSid)
689 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
690 static UCHAR zero = 0U;
691 HMODULE hm_advapi32 = NULL;
692 if (is_windows_9x () == TRUE)
694 return &zero;
696 if (g_b_init_get_sid_sub_authority_count == 0)
698 g_b_init_get_sid_sub_authority_count = 1;
699 hm_advapi32 = LoadLibrary ("Advapi32.dll");
700 s_pfn_Get_Sid_Sub_Authority_Count =
701 (GetSidSubAuthorityCount_Proc) GetProcAddress (
702 hm_advapi32, "GetSidSubAuthorityCount");
704 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
706 return &zero;
708 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
711 static DWORD WINAPI
712 get_security_info (HANDLE handle,
713 SE_OBJECT_TYPE ObjectType,
714 SECURITY_INFORMATION SecurityInfo,
715 PSID *ppsidOwner,
716 PSID *ppsidGroup,
717 PACL *ppDacl,
718 PACL *ppSacl,
719 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
721 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
722 HMODULE hm_advapi32 = NULL;
723 if (is_windows_9x () == TRUE)
725 return FALSE;
727 if (g_b_init_get_security_info == 0)
729 g_b_init_get_security_info = 1;
730 hm_advapi32 = LoadLibrary ("Advapi32.dll");
731 s_pfn_Get_Security_Info =
732 (GetSecurityInfo_Proc) GetProcAddress (
733 hm_advapi32, "GetSecurityInfo");
735 if (s_pfn_Get_Security_Info == NULL)
737 return FALSE;
739 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
740 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
741 ppSecurityDescriptor));
744 static BOOL WINAPI
745 get_file_security (const char *lpFileName,
746 SECURITY_INFORMATION RequestedInformation,
747 PSECURITY_DESCRIPTOR pSecurityDescriptor,
748 DWORD nLength,
749 LPDWORD lpnLengthNeeded)
751 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
752 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
753 HMODULE hm_advapi32 = NULL;
754 if (is_windows_9x () == TRUE)
756 errno = ENOTSUP;
757 return FALSE;
759 if (w32_unicode_filenames)
761 wchar_t filename_w[MAX_PATH];
763 if (g_b_init_get_file_security_w == 0)
765 g_b_init_get_file_security_w = 1;
766 hm_advapi32 = LoadLibrary ("Advapi32.dll");
767 s_pfn_Get_File_SecurityW =
768 (GetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
769 "GetFileSecurityW");
771 if (s_pfn_Get_File_SecurityW == NULL)
773 errno = ENOTSUP;
774 return FALSE;
776 filename_to_utf16 (lpFileName, filename_w);
777 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
778 pSecurityDescriptor, nLength,
779 lpnLengthNeeded));
781 else
783 char filename_a[MAX_PATH];
785 if (g_b_init_get_file_security_a == 0)
787 g_b_init_get_file_security_a = 1;
788 hm_advapi32 = LoadLibrary ("Advapi32.dll");
789 s_pfn_Get_File_SecurityA =
790 (GetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
791 "GetFileSecurityA");
793 if (s_pfn_Get_File_SecurityA == NULL)
795 errno = ENOTSUP;
796 return FALSE;
798 filename_to_ansi (lpFileName, filename_a);
799 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
800 pSecurityDescriptor, nLength,
801 lpnLengthNeeded));
805 static BOOL WINAPI
806 set_file_security (const char *lpFileName,
807 SECURITY_INFORMATION SecurityInformation,
808 PSECURITY_DESCRIPTOR pSecurityDescriptor)
810 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
811 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
812 HMODULE hm_advapi32 = NULL;
813 if (is_windows_9x () == TRUE)
815 errno = ENOTSUP;
816 return FALSE;
818 if (w32_unicode_filenames)
820 wchar_t filename_w[MAX_PATH];
822 if (g_b_init_set_file_security_w == 0)
824 g_b_init_set_file_security_w = 1;
825 hm_advapi32 = LoadLibrary ("Advapi32.dll");
826 s_pfn_Set_File_SecurityW =
827 (SetFileSecurityW_Proc) GetProcAddress (hm_advapi32,
828 "SetFileSecurityW");
830 if (s_pfn_Set_File_SecurityW == NULL)
832 errno = ENOTSUP;
833 return FALSE;
835 filename_to_utf16 (lpFileName, filename_w);
836 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
837 pSecurityDescriptor));
839 else
841 char filename_a[MAX_PATH];
843 if (g_b_init_set_file_security_a == 0)
845 g_b_init_set_file_security_a = 1;
846 hm_advapi32 = LoadLibrary ("Advapi32.dll");
847 s_pfn_Set_File_SecurityA =
848 (SetFileSecurityA_Proc) GetProcAddress (hm_advapi32,
849 "SetFileSecurityA");
851 if (s_pfn_Set_File_SecurityA == NULL)
853 errno = ENOTSUP;
854 return FALSE;
856 filename_to_ansi (lpFileName, filename_a);
857 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
858 pSecurityDescriptor));
862 static DWORD WINAPI
863 set_named_security_info (LPCTSTR lpObjectName,
864 SE_OBJECT_TYPE ObjectType,
865 SECURITY_INFORMATION SecurityInformation,
866 PSID psidOwner,
867 PSID psidGroup,
868 PACL pDacl,
869 PACL pSacl)
871 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
872 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
873 HMODULE hm_advapi32 = NULL;
874 if (is_windows_9x () == TRUE)
876 errno = ENOTSUP;
877 return ENOTSUP;
879 if (w32_unicode_filenames)
881 wchar_t filename_w[MAX_PATH];
883 if (g_b_init_set_named_security_info_w == 0)
885 g_b_init_set_named_security_info_w = 1;
886 hm_advapi32 = LoadLibrary ("Advapi32.dll");
887 s_pfn_Set_Named_Security_InfoW =
888 (SetNamedSecurityInfoW_Proc) GetProcAddress (hm_advapi32,
889 "SetNamedSecurityInfoW");
891 if (s_pfn_Set_Named_Security_InfoW == NULL)
893 errno = ENOTSUP;
894 return ENOTSUP;
896 filename_to_utf16 (lpObjectName, filename_w);
897 return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
898 SecurityInformation, psidOwner,
899 psidGroup, pDacl, pSacl));
901 else
903 char filename_a[MAX_PATH];
905 if (g_b_init_set_named_security_info_a == 0)
907 g_b_init_set_named_security_info_a = 1;
908 hm_advapi32 = LoadLibrary ("Advapi32.dll");
909 s_pfn_Set_Named_Security_InfoA =
910 (SetNamedSecurityInfoA_Proc) GetProcAddress (hm_advapi32,
911 "SetNamedSecurityInfoA");
913 if (s_pfn_Set_Named_Security_InfoA == NULL)
915 errno = ENOTSUP;
916 return ENOTSUP;
918 filename_to_ansi (lpObjectName, filename_a);
919 return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
920 SecurityInformation, psidOwner,
921 psidGroup, pDacl, pSacl));
925 static BOOL WINAPI
926 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
927 PSID *pOwner,
928 LPBOOL lpbOwnerDefaulted)
930 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
931 HMODULE hm_advapi32 = NULL;
932 if (is_windows_9x () == TRUE)
934 errno = ENOTSUP;
935 return FALSE;
937 if (g_b_init_get_security_descriptor_owner == 0)
939 g_b_init_get_security_descriptor_owner = 1;
940 hm_advapi32 = LoadLibrary ("Advapi32.dll");
941 s_pfn_Get_Security_Descriptor_Owner =
942 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
943 hm_advapi32, "GetSecurityDescriptorOwner");
945 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
947 errno = ENOTSUP;
948 return FALSE;
950 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
951 lpbOwnerDefaulted));
954 static BOOL WINAPI
955 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
956 PSID *pGroup,
957 LPBOOL lpbGroupDefaulted)
959 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
960 HMODULE hm_advapi32 = NULL;
961 if (is_windows_9x () == TRUE)
963 errno = ENOTSUP;
964 return FALSE;
966 if (g_b_init_get_security_descriptor_group == 0)
968 g_b_init_get_security_descriptor_group = 1;
969 hm_advapi32 = LoadLibrary ("Advapi32.dll");
970 s_pfn_Get_Security_Descriptor_Group =
971 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
972 hm_advapi32, "GetSecurityDescriptorGroup");
974 if (s_pfn_Get_Security_Descriptor_Group == NULL)
976 errno = ENOTSUP;
977 return FALSE;
979 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
980 lpbGroupDefaulted));
983 static BOOL WINAPI
984 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
985 LPBOOL lpbDaclPresent,
986 PACL *pDacl,
987 LPBOOL lpbDaclDefaulted)
989 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
990 HMODULE hm_advapi32 = NULL;
991 if (is_windows_9x () == TRUE)
993 errno = ENOTSUP;
994 return FALSE;
996 if (g_b_init_get_security_descriptor_dacl == 0)
998 g_b_init_get_security_descriptor_dacl = 1;
999 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1000 s_pfn_Get_Security_Descriptor_Dacl =
1001 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
1002 hm_advapi32, "GetSecurityDescriptorDacl");
1004 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
1006 errno = ENOTSUP;
1007 return FALSE;
1009 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
1010 lpbDaclPresent, pDacl,
1011 lpbDaclDefaulted));
1014 static BOOL WINAPI
1015 is_valid_sid (PSID sid)
1017 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
1018 HMODULE hm_advapi32 = NULL;
1019 if (is_windows_9x () == TRUE)
1021 return FALSE;
1023 if (g_b_init_is_valid_sid == 0)
1025 g_b_init_is_valid_sid = 1;
1026 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1027 s_pfn_Is_Valid_Sid =
1028 (IsValidSid_Proc) GetProcAddress (
1029 hm_advapi32, "IsValidSid");
1031 if (s_pfn_Is_Valid_Sid == NULL)
1033 return FALSE;
1035 return (s_pfn_Is_Valid_Sid (sid));
1038 static BOOL WINAPI
1039 equal_sid (PSID sid1, PSID sid2)
1041 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1042 HMODULE hm_advapi32 = NULL;
1043 if (is_windows_9x () == TRUE)
1045 return FALSE;
1047 if (g_b_init_equal_sid == 0)
1049 g_b_init_equal_sid = 1;
1050 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1051 s_pfn_Equal_Sid =
1052 (EqualSid_Proc) GetProcAddress (
1053 hm_advapi32, "EqualSid");
1055 if (s_pfn_Equal_Sid == NULL)
1057 return FALSE;
1059 return (s_pfn_Equal_Sid (sid1, sid2));
1062 static DWORD WINAPI
1063 get_length_sid (PSID sid)
1065 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1066 HMODULE hm_advapi32 = NULL;
1067 if (is_windows_9x () == TRUE)
1069 return 0;
1071 if (g_b_init_get_length_sid == 0)
1073 g_b_init_get_length_sid = 1;
1074 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1075 s_pfn_Get_Length_Sid =
1076 (GetLengthSid_Proc) GetProcAddress (
1077 hm_advapi32, "GetLengthSid");
1079 if (s_pfn_Get_Length_Sid == NULL)
1081 return 0;
1083 return (s_pfn_Get_Length_Sid (sid));
1086 static BOOL WINAPI
1087 copy_sid (DWORD destlen, PSID dest, PSID src)
1089 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1090 HMODULE hm_advapi32 = NULL;
1091 if (is_windows_9x () == TRUE)
1093 return FALSE;
1095 if (g_b_init_copy_sid == 0)
1097 g_b_init_copy_sid = 1;
1098 hm_advapi32 = LoadLibrary ("Advapi32.dll");
1099 s_pfn_Copy_Sid =
1100 (CopySid_Proc) GetProcAddress (
1101 hm_advapi32, "CopySid");
1103 if (s_pfn_Copy_Sid == NULL)
1105 return FALSE;
1107 return (s_pfn_Copy_Sid (destlen, dest, src));
1111 END: Wrapper functions around OpenProcessToken
1112 and other functions in advapi32.dll that are only
1113 supported in Windows NT / 2k / XP
1116 static void WINAPI
1117 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1119 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1120 if (is_windows_9x () != TRUE)
1122 if (g_b_init_get_native_system_info == 0)
1124 g_b_init_get_native_system_info = 1;
1125 s_pfn_Get_Native_System_Info =
1126 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1127 "GetNativeSystemInfo");
1129 if (s_pfn_Get_Native_System_Info != NULL)
1130 s_pfn_Get_Native_System_Info (lpSystemInfo);
1132 else
1133 lpSystemInfo->dwNumberOfProcessors = -1;
1136 static BOOL WINAPI
1137 get_system_times (LPFILETIME lpIdleTime,
1138 LPFILETIME lpKernelTime,
1139 LPFILETIME lpUserTime)
1141 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1142 if (is_windows_9x () == TRUE)
1144 return FALSE;
1146 if (g_b_init_get_system_times == 0)
1148 g_b_init_get_system_times = 1;
1149 s_pfn_Get_System_times =
1150 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1151 "GetSystemTimes");
1153 if (s_pfn_Get_System_times == NULL)
1154 return FALSE;
1155 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1158 static BOOLEAN WINAPI
1159 create_symbolic_link (LPCSTR lpSymlinkFilename,
1160 LPCSTR lpTargetFileName,
1161 DWORD dwFlags)
1163 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1164 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1165 BOOLEAN retval;
1167 if (is_windows_9x () == TRUE)
1169 errno = ENOSYS;
1170 return 0;
1172 if (w32_unicode_filenames)
1174 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1176 if (g_b_init_create_symbolic_link_w == 0)
1178 g_b_init_create_symbolic_link_w = 1;
1179 s_pfn_Create_Symbolic_LinkW =
1180 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1181 "CreateSymbolicLinkW");
1183 if (s_pfn_Create_Symbolic_LinkW == NULL)
1185 errno = ENOSYS;
1186 return 0;
1189 filename_to_utf16 (lpSymlinkFilename, symfn_w);
1190 filename_to_utf16 (lpTargetFileName, tgtfn_w);
1191 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1192 /* If we were denied creation of the symlink, try again after
1193 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1194 if (!retval)
1196 TOKEN_PRIVILEGES priv_current;
1198 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1199 &priv_current))
1201 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1202 restore_privilege (&priv_current);
1203 revert_to_self ();
1207 else
1209 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1211 if (g_b_init_create_symbolic_link_a == 0)
1213 g_b_init_create_symbolic_link_a = 1;
1214 s_pfn_Create_Symbolic_LinkA =
1215 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1216 "CreateSymbolicLinkA");
1218 if (s_pfn_Create_Symbolic_LinkA == NULL)
1220 errno = ENOSYS;
1221 return 0;
1224 filename_to_ansi (lpSymlinkFilename, symfn_a);
1225 filename_to_ansi (lpTargetFileName, tgtfn_a);
1226 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1227 /* If we were denied creation of the symlink, try again after
1228 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1229 if (!retval)
1231 TOKEN_PRIVILEGES priv_current;
1233 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1234 &priv_current))
1236 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1237 restore_privilege (&priv_current);
1238 revert_to_self ();
1242 return retval;
1245 static BOOL WINAPI
1246 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1248 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1250 if (is_windows_9x () == TRUE)
1252 errno = ENOTSUP;
1253 return FALSE;
1256 if (g_b_init_is_valid_security_descriptor == 0)
1258 g_b_init_is_valid_security_descriptor = 1;
1259 s_pfn_Is_Valid_Security_Descriptor_Proc =
1260 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1261 "IsValidSecurityDescriptor");
1263 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1265 errno = ENOTSUP;
1266 return FALSE;
1269 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1272 static BOOL WINAPI
1273 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1274 DWORD RequestedStringSDRevision,
1275 SECURITY_INFORMATION SecurityInformation,
1276 LPTSTR *StringSecurityDescriptor,
1277 PULONG StringSecurityDescriptorLen)
1279 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1280 BOOL retval;
1282 if (is_windows_9x () == TRUE)
1284 errno = ENOTSUP;
1285 return FALSE;
1288 if (g_b_init_convert_sd_to_sddl == 0)
1290 g_b_init_convert_sd_to_sddl = 1;
1291 #ifdef _UNICODE
1292 s_pfn_Convert_SD_To_SDDL =
1293 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1294 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1295 #else
1296 s_pfn_Convert_SD_To_SDDL =
1297 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1298 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1299 #endif
1301 if (s_pfn_Convert_SD_To_SDDL == NULL)
1303 errno = ENOTSUP;
1304 return FALSE;
1307 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1308 RequestedStringSDRevision,
1309 SecurityInformation,
1310 StringSecurityDescriptor,
1311 StringSecurityDescriptorLen);
1313 return retval;
1316 static BOOL WINAPI
1317 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1318 DWORD StringSDRevision,
1319 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1320 PULONG SecurityDescriptorSize)
1322 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1323 BOOL retval;
1325 if (is_windows_9x () == TRUE)
1327 errno = ENOTSUP;
1328 return FALSE;
1331 if (g_b_init_convert_sddl_to_sd == 0)
1333 g_b_init_convert_sddl_to_sd = 1;
1334 #ifdef _UNICODE
1335 s_pfn_Convert_SDDL_To_SD =
1336 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1337 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1338 #else
1339 s_pfn_Convert_SDDL_To_SD =
1340 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1341 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1342 #endif
1344 if (s_pfn_Convert_SDDL_To_SD == NULL)
1346 errno = ENOTSUP;
1347 return FALSE;
1350 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1351 StringSDRevision,
1352 SecurityDescriptor,
1353 SecurityDescriptorSize);
1355 return retval;
1358 static DWORD WINAPI
1359 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1361 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1362 HMODULE hm_iphlpapi = NULL;
1364 if (is_windows_9x () == TRUE)
1365 return ERROR_NOT_SUPPORTED;
1367 if (g_b_init_get_adapters_info == 0)
1369 g_b_init_get_adapters_info = 1;
1370 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1371 if (hm_iphlpapi)
1372 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1373 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1375 if (s_pfn_Get_Adapters_Info == NULL)
1376 return ERROR_NOT_SUPPORTED;
1377 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1382 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1383 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1385 This is called from alloc.c:valid_pointer_p. */
1387 w32_valid_pointer_p (void *p, int size)
1389 SIZE_T done;
1390 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1392 if (h)
1394 unsigned char *buf = alloca (size);
1395 int retval = ReadProcessMemory (h, p, buf, size, &done);
1397 CloseHandle (h);
1398 return retval;
1400 else
1401 return -1;
1406 /* Here's an overview of how the Windows build supports file names
1407 that cannot be encoded by the current system codepage.
1409 From the POV of Lisp and layers of C code above the functions here,
1410 Emacs on Windows pretends that its file names are encoded in UTF-8;
1411 see encode_file and decode_file on coding.c. Any file name that is
1412 passed as a unibyte string to C functions defined here is assumed
1413 to be in UTF-8 encoding. Any file name returned by functions
1414 defined here must be in UTF-8 encoding, with only a few exceptions
1415 reserved for a couple of special cases. (Be sure to use
1416 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1417 as they can be much longer than MAX_PATH!)
1419 The UTF-8 encoded file names cannot be passed to system APIs, as
1420 Windows does not support that. Therefore, they are converted
1421 either to UTF-16 or to the ANSI codepage, depending on the value of
1422 w32-unicode-filenames, before calling any system APIs or CRT library
1423 functions. The default value of that variable is determined by the
1424 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1425 user can change that default (although I don't see why would she
1426 want to).
1428 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1429 filename_from_utf16, and filename_from_ansi, are the workhorses of
1430 these conversions. They rely on Windows native APIs
1431 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1432 functions from coding.c here, because they allocate memory, which
1433 is a bad idea on the level of libc, which is what the functions
1434 here emulate. (If you worry about performance due to constant
1435 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1436 it was measured to take only a few microseconds on a not-so-fast
1437 machine, and second, that's exactly what the ANSI APIs we used
1438 before did anyway, because they are just thin wrappers around the
1439 Unicode APIs.)
1441 The variables file-name-coding-system and default-file-name-coding-system
1442 still exist, but are actually used only when a file name needs to
1443 be converted to the ANSI codepage. This happens all the time when
1444 w32-unicode-filenames is nil, but can also happen from time to time
1445 when it is t. Otherwise, these variables have no effect on file-name
1446 encoding when w32-unicode-filenames is t; this is similar to
1447 selection-coding-system.
1449 This arrangement works very well, but it has a few gotchas and
1450 limitations:
1452 . Lisp code that encodes or decodes file names manually should
1453 normally use 'utf-8' as the coding-system on Windows,
1454 disregarding file-name-coding-system. This is a somewhat
1455 unpleasant consequence, but it cannot be avoided. Fortunately,
1456 very few Lisp packages need to do that.
1458 More generally, passing to library functions (e.g., fopen or
1459 opendir) file names already encoded in the ANSI codepage is
1460 explicitly *verboten*, as all those functions, as shadowed and
1461 emulated here, assume they will receive UTF-8 encoded file names.
1463 For the same reasons, no CRT function or Win32 API can be called
1464 directly in Emacs sources, without either converting the file
1465 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1466 some shadowing function defined here.
1468 . Environment variables stored in Vprocess_environment are encoded
1469 in the ANSI codepage, so if getenv/egetenv is used for a variable
1470 whose value is a file name or a list of directories, it needs to
1471 be converted to UTF-8, before it is used as argument to functions
1472 or decoded into a Lisp string.
1474 . File names passed to external libraries, like the image libraries
1475 and GnuTLS, need special handling. These libraries generally
1476 don't support UTF-16 or UTF-8 file names, so they must get file
1477 names encoded in the ANSI codepage. To facilitate using these
1478 libraries with file names that are not encodable in the ANSI
1479 codepage, use the function ansi_encode_filename, which will try
1480 to use the short 8+3 alias of a file name if that file name is
1481 not encodable in the ANSI codepage. See image.c and gnutls.c for
1482 examples of how this should be done.
1484 . Running subprocesses in non-ASCII directories and with non-ASCII
1485 file arguments is limited to the current codepage (even though
1486 Emacs is perfectly capable of finding an executable program file
1487 in a directory whose name cannot be encoded in the current
1488 codepage). This is because the command-line arguments are
1489 encoded _before_ they get to the w32-specific level, and the
1490 encoding is not known in advance (it doesn't have to be the
1491 current ANSI codepage), so w32proc.c functions cannot re-encode
1492 them in UTF-16. This should be fixed, but will also require
1493 changes in cmdproxy. The current limitation is not terribly bad
1494 anyway, since very few, if any, Windows console programs that are
1495 likely to be invoked by Emacs support UTF-16 encoded command
1496 lines.
1498 . For similar reasons, server.el and emacsclient are also limited
1499 to the current ANSI codepage for now.
1501 . Emacs itself can only handle command-line arguments encoded in
1502 the current codepage.
1504 . Turning on w32-unicode-filename on Windows 9X (if it at all
1505 works) requires UNICOWS.DLL, which is thus a requirement even in
1506 non-GUI sessions, something the we previously avoided. */
1510 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1511 codepage defined by file-name-coding-system. */
1513 /* Current codepage for encoding file names. */
1514 static int file_name_codepage;
1516 /* Produce a Windows ANSI codepage suitable for encoding file names.
1517 Return the information about that codepage in CP_INFO. */
1519 codepage_for_filenames (CPINFO *cp_info)
1521 /* A simple cache to avoid calling GetCPInfo every time we need to
1522 encode/decode a file name. The file-name encoding is not
1523 supposed to be changed too frequently, if ever. */
1524 static Lisp_Object last_file_name_encoding;
1525 static CPINFO cp;
1526 Lisp_Object current_encoding;
1528 current_encoding = Vfile_name_coding_system;
1529 if (NILP (current_encoding))
1530 current_encoding = Vdefault_file_name_coding_system;
1532 if (!EQ (last_file_name_encoding, current_encoding))
1534 /* Default to the current ANSI codepage. */
1535 file_name_codepage = w32_ansi_code_page;
1537 if (NILP (current_encoding))
1539 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1540 char *cp = NULL, *end;
1541 int cpnum;
1543 if (strncmp (cpname, "cp", 2) == 0)
1544 cp = cpname + 2;
1545 else if (strncmp (cpname, "windows-", 8) == 0)
1546 cp = cpname + 8;
1548 if (cp)
1550 end = cp;
1551 cpnum = strtol (cp, &end, 10);
1552 if (cpnum && *end == '\0' && end - cp >= 2)
1553 file_name_codepage = cpnum;
1557 if (!file_name_codepage)
1558 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1560 if (!GetCPInfo (file_name_codepage, &cp))
1562 file_name_codepage = CP_ACP;
1563 if (!GetCPInfo (file_name_codepage, &cp))
1564 emacs_abort ();
1567 if (cp_info)
1568 *cp_info = cp;
1570 return file_name_codepage;
1574 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1576 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1577 -1, fn_out, MAX_PATH);
1579 if (!result)
1581 DWORD err = GetLastError ();
1583 switch (err)
1585 case ERROR_INVALID_FLAGS:
1586 case ERROR_INVALID_PARAMETER:
1587 errno = EINVAL;
1588 break;
1589 case ERROR_INSUFFICIENT_BUFFER:
1590 case ERROR_NO_UNICODE_TRANSLATION:
1591 default:
1592 errno = ENOENT;
1593 break;
1595 return -1;
1597 return 0;
1601 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1603 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1604 fn_out, MAX_UTF8_PATH, NULL, NULL);
1606 if (!result)
1608 DWORD err = GetLastError ();
1610 switch (err)
1612 case ERROR_INVALID_FLAGS:
1613 case ERROR_INVALID_PARAMETER:
1614 errno = EINVAL;
1615 break;
1616 case ERROR_INSUFFICIENT_BUFFER:
1617 case ERROR_NO_UNICODE_TRANSLATION:
1618 default:
1619 errno = ENOENT;
1620 break;
1622 return -1;
1624 return 0;
1628 filename_to_ansi (const char *fn_in, char *fn_out)
1630 wchar_t fn_utf16[MAX_PATH];
1632 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1634 int result;
1635 int codepage = codepage_for_filenames (NULL);
1637 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1638 fn_out, MAX_PATH, NULL, NULL);
1639 if (!result)
1641 DWORD err = GetLastError ();
1643 switch (err)
1645 case ERROR_INVALID_FLAGS:
1646 case ERROR_INVALID_PARAMETER:
1647 errno = EINVAL;
1648 break;
1649 case ERROR_INSUFFICIENT_BUFFER:
1650 case ERROR_NO_UNICODE_TRANSLATION:
1651 default:
1652 errno = ENOENT;
1653 break;
1655 return -1;
1657 return 0;
1659 return -1;
1663 filename_from_ansi (const char *fn_in, char *fn_out)
1665 wchar_t fn_utf16[MAX_PATH];
1666 int codepage = codepage_for_filenames (NULL);
1667 int result = pMultiByteToWideChar (codepage, multiByteToWideCharFlags, fn_in,
1668 -1, fn_utf16, MAX_PATH);
1670 if (!result)
1672 DWORD err = GetLastError ();
1674 switch (err)
1676 case ERROR_INVALID_FLAGS:
1677 case ERROR_INVALID_PARAMETER:
1678 errno = EINVAL;
1679 break;
1680 case ERROR_INSUFFICIENT_BUFFER:
1681 case ERROR_NO_UNICODE_TRANSLATION:
1682 default:
1683 errno = ENOENT;
1684 break;
1686 return -1;
1688 return filename_from_utf16 (fn_utf16, fn_out);
1693 /* The directory where we started, in UTF-8. */
1694 static char startup_dir[MAX_UTF8_PATH];
1696 /* Get the current working directory. */
1697 char *
1698 getcwd (char *dir, int dirsize)
1700 if (!dirsize)
1702 errno = EINVAL;
1703 return NULL;
1705 if (dirsize <= strlen (startup_dir))
1707 errno = ERANGE;
1708 return NULL;
1710 #if 0
1711 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1712 return dir;
1713 return NULL;
1714 #else
1715 /* Emacs doesn't actually change directory itself, it stays in the
1716 same directory where it was started. */
1717 strcpy (dir, startup_dir);
1718 return dir;
1719 #endif
1722 /* Emulate getloadavg. */
1724 struct load_sample {
1725 time_t sample_time;
1726 ULONGLONG idle;
1727 ULONGLONG kernel;
1728 ULONGLONG user;
1731 /* Number of processors on this machine. */
1732 static unsigned num_of_processors;
1734 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1735 static struct load_sample samples[16*60];
1736 static int first_idx = -1, last_idx = -1;
1737 static int max_idx = ARRAYELTS (samples);
1739 static int
1740 buf_next (int from)
1742 int next_idx = from + 1;
1744 if (next_idx >= max_idx)
1745 next_idx = 0;
1747 return next_idx;
1750 static int
1751 buf_prev (int from)
1753 int prev_idx = from - 1;
1755 if (prev_idx < 0)
1756 prev_idx = max_idx - 1;
1758 return prev_idx;
1761 static void
1762 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1764 SYSTEM_INFO sysinfo;
1765 FILETIME ft_idle, ft_user, ft_kernel;
1767 /* Initialize the number of processors on this machine. */
1768 if (num_of_processors <= 0)
1770 get_native_system_info (&sysinfo);
1771 num_of_processors = sysinfo.dwNumberOfProcessors;
1772 if (num_of_processors <= 0)
1774 GetSystemInfo (&sysinfo);
1775 num_of_processors = sysinfo.dwNumberOfProcessors;
1777 if (num_of_processors <= 0)
1778 num_of_processors = 1;
1781 /* TODO: Take into account threads that are ready to run, by
1782 sampling the "\System\Processor Queue Length" performance
1783 counter. The code below accounts only for threads that are
1784 actually running. */
1786 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1788 ULARGE_INTEGER uidle, ukernel, uuser;
1790 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1791 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1792 memcpy (&uuser, &ft_user, sizeof (ft_user));
1793 *idle = uidle.QuadPart;
1794 *kernel = ukernel.QuadPart;
1795 *user = uuser.QuadPart;
1797 else
1799 *idle = 0;
1800 *kernel = 0;
1801 *user = 0;
1805 /* Produce the load average for a given time interval, using the
1806 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1807 1-minute, 5-minute, or 15-minute average, respectively. */
1808 static double
1809 getavg (int which)
1811 double retval = -1.0;
1812 double tdiff;
1813 int idx;
1814 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1815 time_t now = samples[last_idx].sample_time;
1817 if (first_idx != last_idx)
1819 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1821 tdiff = difftime (now, samples[idx].sample_time);
1822 if (tdiff >= span - 2*DBL_EPSILON*now)
1824 long double sys =
1825 samples[last_idx].kernel + samples[last_idx].user
1826 - (samples[idx].kernel + samples[idx].user);
1827 long double idl = samples[last_idx].idle - samples[idx].idle;
1829 retval = (1.0 - idl / sys) * num_of_processors;
1830 break;
1832 if (idx == first_idx)
1833 break;
1837 return retval;
1841 getloadavg (double loadavg[], int nelem)
1843 int elem;
1844 ULONGLONG idle, kernel, user;
1845 time_t now = time (NULL);
1847 /* If system time jumped back for some reason, delete all samples
1848 whose time is later than the current wall-clock time. This
1849 prevents load average figures from becoming frozen for prolonged
1850 periods of time, when system time is reset backwards. */
1851 if (last_idx >= 0)
1853 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1855 if (last_idx == first_idx)
1857 first_idx = last_idx = -1;
1858 break;
1860 last_idx = buf_prev (last_idx);
1864 /* Store another sample. We ignore samples that are less than 1 sec
1865 apart. */
1866 if (last_idx < 0
1867 || (difftime (now, samples[last_idx].sample_time)
1868 >= 1.0 - 2*DBL_EPSILON*now))
1870 sample_system_load (&idle, &kernel, &user);
1871 last_idx = buf_next (last_idx);
1872 samples[last_idx].sample_time = now;
1873 samples[last_idx].idle = idle;
1874 samples[last_idx].kernel = kernel;
1875 samples[last_idx].user = user;
1876 /* If the buffer has more that 15 min worth of samples, discard
1877 the old ones. */
1878 if (first_idx == -1)
1879 first_idx = last_idx;
1880 while (first_idx != last_idx
1881 && (difftime (now, samples[first_idx].sample_time)
1882 >= 15.0*60 + 2*DBL_EPSILON*now))
1883 first_idx = buf_next (first_idx);
1886 for (elem = 0; elem < nelem; elem++)
1888 double avg = getavg (elem);
1890 if (avg < 0)
1891 break;
1892 loadavg[elem] = avg;
1895 return elem;
1898 /* Emulate getpwuid, getpwnam and others. */
1900 #define PASSWD_FIELD_SIZE 256
1902 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1903 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1904 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1905 static char dflt_passwd_dir[MAX_UTF8_PATH];
1906 static char dflt_passwd_shell[MAX_UTF8_PATH];
1908 static struct passwd dflt_passwd =
1910 dflt_passwd_name,
1911 dflt_passwd_passwd,
1915 dflt_passwd_gecos,
1916 dflt_passwd_dir,
1917 dflt_passwd_shell,
1920 static char dflt_group_name[GNLEN+1];
1922 static struct group dflt_group =
1924 /* When group information is not available, we return this as the
1925 group for all files. */
1926 dflt_group_name,
1930 unsigned
1931 getuid (void)
1933 return dflt_passwd.pw_uid;
1936 unsigned
1937 geteuid (void)
1939 /* I could imagine arguing for checking to see whether the user is
1940 in the Administrators group and returning a UID of 0 for that
1941 case, but I don't know how wise that would be in the long run. */
1942 return getuid ();
1945 unsigned
1946 getgid (void)
1948 return dflt_passwd.pw_gid;
1951 unsigned
1952 getegid (void)
1954 return getgid ();
1957 struct passwd *
1958 getpwuid (unsigned uid)
1960 if (uid == dflt_passwd.pw_uid)
1961 return &dflt_passwd;
1962 return NULL;
1965 struct group *
1966 getgrgid (gid_t gid)
1968 return &dflt_group;
1971 struct passwd *
1972 getpwnam (char *name)
1974 struct passwd *pw;
1976 pw = getpwuid (getuid ());
1977 if (!pw)
1978 return pw;
1980 if (xstrcasecmp (name, pw->pw_name))
1981 return NULL;
1983 return pw;
1986 static void
1987 init_user_info (void)
1989 /* Find the user's real name by opening the process token and
1990 looking up the name associated with the user-sid in that token.
1992 Use the relative portion of the identifier authority value from
1993 the user-sid as the user id value (same for group id using the
1994 primary group sid from the process token). */
1996 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1997 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1998 DWORD glength = sizeof (gname);
1999 HANDLE token = NULL;
2000 SID_NAME_USE user_type;
2001 unsigned char *buf = NULL;
2002 DWORD blen = 0;
2003 TOKEN_USER user_token;
2004 TOKEN_PRIMARY_GROUP group_token;
2005 BOOL result;
2007 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
2008 if (result)
2010 result = get_token_information (token, TokenUser, NULL, 0, &blen);
2011 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2013 buf = xmalloc (blen);
2014 result = get_token_information (token, TokenUser,
2015 (LPVOID)buf, blen, &needed);
2016 if (result)
2018 memcpy (&user_token, buf, sizeof (user_token));
2019 result = lookup_account_sid (NULL, user_token.User.Sid,
2020 uname, &ulength,
2021 domain, &dlength, &user_type);
2024 else
2025 result = FALSE;
2027 if (result)
2029 strcpy (dflt_passwd.pw_name, uname);
2030 /* Determine a reasonable uid value. */
2031 if (xstrcasecmp ("administrator", uname) == 0)
2033 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2034 dflt_passwd.pw_gid = 513; /* well-known None gid */
2036 else
2038 /* Use the last sub-authority value of the RID, the relative
2039 portion of the SID, as user/group ID. */
2040 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
2042 /* Get group id and name. */
2043 result = get_token_information (token, TokenPrimaryGroup,
2044 (LPVOID)buf, blen, &needed);
2045 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2047 buf = xrealloc (buf, blen = needed);
2048 result = get_token_information (token, TokenPrimaryGroup,
2049 (LPVOID)buf, blen, &needed);
2051 if (result)
2053 memcpy (&group_token, buf, sizeof (group_token));
2054 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
2055 dlength = sizeof (domain);
2056 /* If we can get at the real Primary Group name, use that.
2057 Otherwise, the default group name was already set to
2058 "None" in globals_of_w32. */
2059 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
2060 gname, &glength, NULL, &dlength,
2061 &user_type))
2062 strcpy (dflt_group_name, gname);
2064 else
2065 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2068 /* If security calls are not supported (presumably because we
2069 are running under Windows 9X), fallback to this: */
2070 else if (GetUserName (uname, &ulength))
2072 strcpy (dflt_passwd.pw_name, uname);
2073 if (xstrcasecmp ("administrator", uname) == 0)
2074 dflt_passwd.pw_uid = 0;
2075 else
2076 dflt_passwd.pw_uid = 123;
2077 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2079 else
2081 strcpy (dflt_passwd.pw_name, "unknown");
2082 dflt_passwd.pw_uid = 123;
2083 dflt_passwd.pw_gid = 123;
2085 dflt_group.gr_gid = dflt_passwd.pw_gid;
2087 /* Set dir and shell from environment variables. */
2088 if (w32_unicode_filenames)
2090 wchar_t *home = _wgetenv (L"HOME");
2091 wchar_t *shell = _wgetenv (L"SHELL");
2093 /* Ensure HOME and SHELL are defined. */
2094 if (home == NULL)
2095 emacs_abort ();
2096 if (shell == NULL)
2097 emacs_abort ();
2098 filename_from_utf16 (home, dflt_passwd.pw_dir);
2099 filename_from_utf16 (shell, dflt_passwd.pw_shell);
2101 else
2103 char *home = getenv ("HOME");
2104 char *shell = getenv ("SHELL");
2106 if (home == NULL)
2107 emacs_abort ();
2108 if (shell == NULL)
2109 emacs_abort ();
2110 filename_from_ansi (home, dflt_passwd.pw_dir);
2111 filename_from_ansi (shell, dflt_passwd.pw_shell);
2114 xfree (buf);
2115 if (token)
2116 CloseHandle (token);
2119 static HCRYPTPROV w32_crypto_hprov;
2120 static int
2121 w32_init_crypt_random (void)
2123 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2124 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2126 DebPrint (("CryptAcquireContext failed with error %x\n",
2127 GetLastError ()));
2128 w32_crypto_hprov = 0;
2129 return -1;
2131 return 0;
2135 w32_init_random (void *buf, ptrdiff_t buflen)
2137 if (!w32_crypto_hprov)
2138 w32_init_crypt_random ();
2139 if (w32_crypto_hprov)
2141 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2142 return 0;
2144 return -1;
2148 random (void)
2150 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2151 return ((rand () << 15) | rand ());
2154 void
2155 srandom (int seed)
2157 srand (seed);
2160 /* Return the maximum length in bytes of a multibyte character
2161 sequence encoded in the current ANSI codepage. This is required to
2162 correctly walk the encoded file names one character at a time. */
2163 static int
2164 max_filename_mbslen (void)
2166 CPINFO cp_info;
2168 codepage_for_filenames (&cp_info);
2169 return cp_info.MaxCharSize;
2172 /* Normalize filename by converting in-place all of its path
2173 separators to the separator specified by PATH_SEP. */
2175 static void
2176 normalize_filename (register char *fp, char path_sep)
2178 char *p2;
2180 /* Always lower-case drive letters a-z, even if the filesystem
2181 preserves case in filenames.
2182 This is so filenames can be compared by string comparison
2183 functions that are case-sensitive. Even case-preserving filesystems
2184 do not distinguish case in drive letters. */
2185 p2 = fp + 1;
2187 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2189 *fp += 'a' - 'A';
2190 fp += 2;
2193 while (*fp)
2195 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2196 *fp = path_sep;
2197 fp++;
2201 /* Destructively turn backslashes into slashes. */
2202 void
2203 dostounix_filename (register char *p)
2205 normalize_filename (p, '/');
2208 /* Destructively turn slashes into backslashes. */
2209 void
2210 unixtodos_filename (register char *p)
2212 normalize_filename (p, '\\');
2215 /* Remove all CR's that are followed by a LF.
2216 (From msdos.c...probably should figure out a way to share it,
2217 although this code isn't going to ever change.) */
2218 static int
2219 crlf_to_lf (register int n, register char *buf)
2221 unsigned char *np = (unsigned char *)buf;
2222 unsigned char *startp = np;
2223 char *endp = buf + n;
2225 if (n == 0)
2226 return n;
2227 while (buf < endp - 1)
2229 if (*buf == 0x0d)
2231 if (*(++buf) != 0x0a)
2232 *np++ = 0x0d;
2234 else
2235 *np++ = *buf++;
2237 if (buf < endp)
2238 *np++ = *buf++;
2239 return np - startp;
2242 /* Parse the root part of file name, if present. Return length and
2243 optionally store pointer to char after root. */
2244 static int
2245 parse_root (const char * name, const char ** pPath)
2247 const char * start = name;
2249 if (name == NULL)
2250 return 0;
2252 /* find the root name of the volume if given */
2253 if (isalpha (name[0]) && name[1] == ':')
2255 /* skip past drive specifier */
2256 name += 2;
2257 if (IS_DIRECTORY_SEP (name[0]))
2258 name++;
2260 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2262 int slashes = 2;
2264 name += 2;
2267 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2268 break;
2269 name++;
2271 while ( *name );
2272 if (IS_DIRECTORY_SEP (name[0]))
2273 name++;
2276 if (pPath)
2277 *pPath = name;
2279 return name - start;
2282 /* Get long base name for name; name is assumed to be absolute. */
2283 static int
2284 get_long_basename (char * name, char * buf, int size)
2286 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2287 char fname_utf8[MAX_UTF8_PATH];
2288 int len = 0;
2289 int cstatus = -1;
2291 /* Must be valid filename, no wild cards or other invalid characters. */
2292 if (strpbrk (name, "*?|<>\""))
2293 return 0;
2295 if (w32_unicode_filenames)
2297 wchar_t fname_utf16[MAX_PATH];
2298 WIN32_FIND_DATAW find_data_wide;
2300 filename_to_utf16 (name, fname_utf16);
2301 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
2302 if (dir_handle != INVALID_HANDLE_VALUE)
2303 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
2305 else
2307 char fname_ansi[MAX_PATH];
2308 WIN32_FIND_DATAA find_data_ansi;
2310 filename_to_ansi (name, fname_ansi);
2311 /* If the ANSI name includes ? characters, it is not encodable
2312 in the ANSI codepage. In that case, we deliver the question
2313 marks to the caller; calling FindFirstFileA in this case
2314 could return some unrelated file name in the same
2315 directory. */
2316 if (_mbspbrk (fname_ansi, "?"))
2318 /* Find the basename of fname_ansi. */
2319 char *p = strrchr (fname_ansi, '\\');
2321 if (!p)
2322 p = fname_ansi;
2323 else
2324 p++;
2325 cstatus = filename_from_ansi (p, fname_utf8);
2327 else
2329 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
2330 if (dir_handle != INVALID_HANDLE_VALUE)
2331 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
2335 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2336 memcpy (buf, fname_utf8, len + 1);
2337 else
2338 len = 0;
2340 if (dir_handle != INVALID_HANDLE_VALUE)
2341 FindClose (dir_handle);
2343 return len;
2346 /* Get long name for file, if possible (assumed to be absolute). */
2347 BOOL
2348 w32_get_long_filename (const char * name, char * buf, int size)
2350 char * o = buf;
2351 char * p;
2352 const char * q;
2353 char full[ MAX_UTF8_PATH ];
2354 int len;
2356 len = strlen (name);
2357 if (len >= MAX_UTF8_PATH)
2358 return FALSE;
2360 /* Use local copy for destructive modification. */
2361 memcpy (full, name, len+1);
2362 unixtodos_filename (full);
2364 /* Copy root part verbatim. */
2365 len = parse_root (full, (const char **)&p);
2366 memcpy (o, full, len);
2367 o += len;
2368 *o = '\0';
2369 size -= len;
2371 while (p != NULL && *p)
2373 q = p;
2374 p = strchr (q, '\\');
2375 if (p) *p = '\0';
2376 len = get_long_basename (full, o, size);
2377 if (len > 0)
2379 o += len;
2380 size -= len;
2381 if (p != NULL)
2383 *p++ = '\\';
2384 if (size < 2)
2385 return FALSE;
2386 *o++ = '\\';
2387 size--;
2388 *o = '\0';
2391 else
2392 return FALSE;
2395 return TRUE;
2398 unsigned int
2399 w32_get_short_filename (const char * name, char * buf, int size)
2401 if (w32_unicode_filenames)
2403 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2404 unsigned int retval;
2406 filename_to_utf16 (name, name_utf16);
2407 retval = GetShortPathNameW (name_utf16, short_name, size);
2408 if (retval && retval < size)
2409 filename_from_utf16 (short_name, buf);
2410 return retval;
2412 else
2414 char name_ansi[MAX_PATH];
2416 filename_to_ansi (name, name_ansi);
2417 return GetShortPathNameA (name_ansi, buf, size);
2421 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2422 MS-Windows ANSI codepage. If FILENAME includes characters not
2423 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2424 if it exists. This is needed because the w32 build wants to
2425 support file names outside of the system locale, but image
2426 libraries typically don't support wide (a.k.a. "Unicode") APIs
2427 required for that. */
2429 Lisp_Object
2430 ansi_encode_filename (Lisp_Object filename)
2432 Lisp_Object encoded_filename;
2433 char fname[MAX_PATH];
2435 filename_to_ansi (SSDATA (filename), fname);
2436 if (_mbspbrk (fname, "?"))
2438 char shortname[MAX_PATH];
2440 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2442 dostounix_filename (shortname);
2443 encoded_filename = build_string (shortname);
2445 else
2446 encoded_filename = build_unibyte_string (fname);
2448 else
2449 encoded_filename = build_unibyte_string (fname);
2450 return encoded_filename;
2453 static int
2454 is_unc_volume (const char *filename)
2456 const char *ptr = filename;
2458 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2459 return 0;
2461 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2462 return 0;
2464 return 1;
2467 /* Emulate the Posix unsetenv. */
2469 unsetenv (const char *name)
2471 char *var;
2472 size_t name_len;
2474 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2476 errno = EINVAL;
2477 return -1;
2479 name_len = strlen (name);
2480 /* MS docs says an environment variable cannot be longer than 32K. */
2481 if (name_len > 32767)
2483 errno = ENOMEM;
2484 return 0;
2486 /* It is safe to use 'alloca' with 32K size, since the stack is at
2487 least 2MB, and we set it to 8MB in the link command line. */
2488 var = alloca (name_len + 2);
2489 strncpy (var, name, name_len);
2490 var[name_len++] = '=';
2491 var[name_len] = '\0';
2492 return _putenv (var);
2495 /* MS _putenv doesn't support removing a variable when the argument
2496 does not include the '=' character, so we fix that here. */
2498 sys_putenv (char *str)
2500 const char *const name_end = strchr (str, '=');
2502 if (name_end == NULL)
2504 /* Remove the variable from the environment. */
2505 return unsetenv (str);
2508 if (strncmp (str, "TZ=<", 4) == 0)
2510 /* MS-Windows does not support POSIX.1-2001 angle-bracket TZ
2511 abbreviation syntax. Convert to POSIX.1-1988 syntax if possible,
2512 and to the undocumented placeholder "ZZZ" otherwise. */
2513 bool supported_abbr = true;
2514 for (char *p = str + 4; *p; p++)
2516 if (('0' <= *p && *p <= '9') || *p == '-' || *p == '+')
2517 supported_abbr = false;
2518 else if (*p == '>')
2520 ptrdiff_t abbrlen;
2521 if (supported_abbr)
2523 abbrlen = p - (str + 4);
2524 memmove (str + 3, str + 4, abbrlen);
2526 else
2528 abbrlen = 3;
2529 memset (str + 3, 'Z', abbrlen);
2531 memmove (str + 3 + abbrlen, p + 1, strlen (p));
2532 break;
2537 return _putenv (str);
2540 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2542 LPBYTE
2543 w32_get_resource (const char *key, LPDWORD lpdwtype)
2545 LPBYTE lpvalue;
2546 HKEY hrootkey = NULL;
2547 DWORD cbData;
2549 /* Check both the current user and the local machine to see if
2550 we have any resources. */
2552 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2554 lpvalue = NULL;
2556 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2557 && (lpvalue = xmalloc (cbData)) != NULL
2558 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2560 RegCloseKey (hrootkey);
2561 return (lpvalue);
2564 xfree (lpvalue);
2566 RegCloseKey (hrootkey);
2569 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2571 lpvalue = NULL;
2573 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2574 && (lpvalue = xmalloc (cbData)) != NULL
2575 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2577 RegCloseKey (hrootkey);
2578 return (lpvalue);
2581 xfree (lpvalue);
2583 RegCloseKey (hrootkey);
2586 return (NULL);
2589 /* The argv[] array holds ANSI-encoded strings, and so this function
2590 works with ANS_encoded strings. */
2591 void
2592 init_environment (char ** argv)
2594 static const char * const tempdirs[] = {
2595 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2598 int i;
2600 const int imax = ARRAYELTS (tempdirs);
2602 /* Implementation note: This function explicitly works with ANSI
2603 file names, not with UTF-8 encoded file names. This is because
2604 this function pushes variables into the Emacs's environment, and
2605 the environment variables are always assumed to be in the
2606 locale-specific encoding. Do NOT call any functions that accept
2607 UTF-8 file names from this function! */
2609 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2610 temporary files and assume "/tmp" if $TMPDIR is unset, which
2611 will break on DOS/Windows. Refuse to work if we cannot find
2612 a directory, not even "c:/", usable for that purpose. */
2613 for (i = 0; i < imax ; i++)
2615 const char *tmp = tempdirs[i];
2617 if (*tmp == '$')
2618 tmp = getenv (tmp + 1);
2619 /* Note that `access' can lie to us if the directory resides on a
2620 read-only filesystem, like CD-ROM or a write-protected floppy.
2621 The only way to be really sure is to actually create a file and
2622 see if it succeeds. But I think that's too much to ask. */
2624 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2625 if (tmp && sys_access (tmp, D_OK) == 0)
2627 char * var = alloca (strlen (tmp) + 8);
2628 sprintf (var, "TMPDIR=%s", tmp);
2629 _putenv (strdup (var));
2630 break;
2633 if (i >= imax)
2634 cmd_error_internal
2635 (Fcons (Qerror,
2636 Fcons (build_string ("no usable temporary directories found!!"),
2637 Qnil)),
2638 "While setting TMPDIR: ");
2640 /* Check for environment variables and use registry settings if they
2641 don't exist. Fallback on default values where applicable. */
2643 int i;
2644 LPBYTE lpval;
2645 DWORD dwType;
2646 char locale_name[32];
2647 char default_home[MAX_PATH];
2648 int appdata = 0;
2650 static const struct env_entry
2652 const char * name;
2653 const char * def_value;
2654 } dflt_envvars[] =
2656 /* If the default value is NULL, we will use the value from the
2657 outside environment or the Registry, but will not push the
2658 variable into the Emacs environment if it is defined neither
2659 in the Registry nor in the outside environment. */
2660 {"HOME", "C:/"},
2661 {"PRELOAD_WINSOCK", NULL},
2662 {"emacs_dir", "C:/emacs"},
2663 {"EMACSLOADPATH", NULL},
2664 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2665 {"EMACSDATA", NULL},
2666 {"EMACSPATH", NULL},
2667 {"INFOPATH", NULL},
2668 {"EMACSDOC", NULL},
2669 {"TERM", "cmd"},
2670 {"LANG", NULL},
2673 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2675 /* We need to copy dflt_envvars[] and work on the copy because we
2676 don't want the dumped Emacs to inherit the values of
2677 environment variables we saw during dumping (which could be on
2678 a different system). The defaults above must be left intact. */
2679 struct env_entry env_vars[N_ENV_VARS];
2681 for (i = 0; i < N_ENV_VARS; i++)
2682 env_vars[i] = dflt_envvars[i];
2684 /* For backwards compatibility, check if a .emacs file exists in C:/
2685 If not, then we can try to default to the appdata directory under the
2686 user's profile, which is more likely to be writable. */
2687 if (sys_access ("C:/.emacs", F_OK) != 0)
2689 HRESULT profile_result;
2690 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2691 of Windows 95 and NT4 that have not been updated to include
2692 MSIE 5. */
2693 ShGetFolderPath_fn get_folder_path;
2694 get_folder_path = (ShGetFolderPath_fn)
2695 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2697 if (get_folder_path != NULL)
2699 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2700 0, default_home);
2702 /* If we can't get the appdata dir, revert to old behavior. */
2703 if (profile_result == S_OK)
2705 env_vars[0].def_value = default_home;
2706 appdata = 1;
2711 /* Get default locale info and use it for LANG. */
2712 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2713 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2714 locale_name, sizeof (locale_name)))
2716 for (i = 0; i < N_ENV_VARS; i++)
2718 if (strcmp (env_vars[i].name, "LANG") == 0)
2720 env_vars[i].def_value = locale_name;
2721 break;
2726 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2728 /* Treat emacs_dir specially: set it unconditionally based on our
2729 location. */
2731 char *p;
2732 char modname[MAX_PATH];
2734 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2735 emacs_abort ();
2736 if ((p = _mbsrchr (modname, '\\')) == NULL)
2737 emacs_abort ();
2738 *p = 0;
2740 if ((p = _mbsrchr (modname, '\\'))
2741 /* From bin means installed Emacs, from src means uninstalled. */
2742 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2744 char buf[SET_ENV_BUF_SIZE];
2745 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2747 *p = 0;
2748 for (p = modname; *p; p = CharNext (p))
2749 if (*p == '\\') *p = '/';
2751 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2752 _putenv (strdup (buf));
2753 /* If we are running from the Posix-like build tree, define
2754 SHELL to point to our own cmdproxy. The loop below will
2755 then disregard PATH_EXEC and the default value. */
2756 if (within_build_tree)
2758 _snprintf (buf, sizeof (buf) - 1,
2759 "SHELL=%s/nt/cmdproxy.exe", modname);
2760 _putenv (strdup (buf));
2765 for (i = 0; i < N_ENV_VARS; i++)
2767 if (!getenv (env_vars[i].name))
2769 int dont_free = 0;
2770 char bufc[SET_ENV_BUF_SIZE];
2772 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2773 /* Also ignore empty environment variables. */
2774 || *lpval == 0)
2776 xfree (lpval);
2777 dont_free = 1;
2778 if (strcmp (env_vars[i].name, "SHELL") == 0)
2780 /* Look for cmdproxy.exe in every directory in
2781 PATH_EXEC. FIXME: This does not find cmdproxy
2782 in nt/ when we run uninstalled. */
2783 char fname[MAX_PATH];
2784 const char *pstart = PATH_EXEC, *pend;
2786 do {
2787 pend = _mbschr (pstart, ';');
2788 if (!pend)
2789 pend = pstart + strlen (pstart);
2790 /* Be defensive against series of ;;; characters. */
2791 if (pend > pstart)
2793 strncpy (fname, pstart, pend - pstart);
2794 fname[pend - pstart] = '/';
2795 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2796 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2797 sizeof (bufc));
2798 if (sys_access (bufc, F_OK) == 0)
2800 lpval = bufc;
2801 dwType = REG_SZ;
2802 break;
2805 if (*pend)
2806 pstart = pend + 1;
2807 else
2808 pstart = pend;
2809 if (!*pstart)
2811 /* If not found in any directory, use the
2812 default as the last resort. */
2813 lpval = (char *)env_vars[i].def_value;
2814 dwType = REG_EXPAND_SZ;
2816 } while (*pstart);
2818 else
2820 lpval = (char *)env_vars[i].def_value;
2821 dwType = REG_EXPAND_SZ;
2823 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2824 Vdelayed_warnings_list
2825 = Fcons
2826 (listn (CONSTYPE_HEAP, 2,
2827 intern ("initialization"), build_string
2828 ("Use of `C:\\.emacs' without defining `HOME'\n"
2829 "in the environment is deprecated, "
2830 "see `Windows HOME' in the Emacs manual.")),
2831 Vdelayed_warnings_list);
2834 if (lpval)
2836 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2838 if (dwType == REG_EXPAND_SZ)
2839 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2840 else if (dwType == REG_SZ)
2841 strcpy (buf1, (char *)lpval);
2842 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2844 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2845 buf1);
2846 _putenv (strdup (buf2));
2849 if (!dont_free)
2850 xfree (lpval);
2856 /* Rebuild system configuration to reflect invoking system. */
2857 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2859 /* Another special case: on NT, the PATH variable is actually named
2860 "Path" although cmd.exe (perhaps NT itself) arranges for
2861 environment variable lookup and setting to be case insensitive.
2862 However, Emacs assumes a fully case sensitive environment, so we
2863 need to change "Path" to "PATH" to match the expectations of
2864 various elisp packages. We do this by the sneaky method of
2865 modifying the string in the C runtime environ entry.
2867 The same applies to COMSPEC. */
2869 char ** envp;
2871 for (envp = environ; *envp; envp++)
2872 if (_strnicmp (*envp, "PATH=", 5) == 0)
2873 memcpy (*envp, "PATH=", 5);
2874 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2875 memcpy (*envp, "COMSPEC=", 8);
2878 /* Remember the initial working directory for getcwd. */
2879 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2880 Does it matter anywhere in Emacs? */
2881 if (w32_unicode_filenames)
2883 wchar_t wstartup_dir[MAX_PATH];
2885 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2886 emacs_abort ();
2887 filename_from_utf16 (wstartup_dir, startup_dir);
2889 else
2891 char astartup_dir[MAX_PATH];
2893 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2894 emacs_abort ();
2895 filename_from_ansi (astartup_dir, startup_dir);
2899 static char modname[MAX_PATH];
2901 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2902 emacs_abort ();
2903 argv[0] = modname;
2906 /* Determine if there is a middle mouse button, to allow parse_button
2907 to decide whether right mouse events should be mouse-2 or
2908 mouse-3. */
2909 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2911 init_user_info ();
2914 /* Called from expand-file-name when default-directory is not a string. */
2916 char *
2917 emacs_root_dir (void)
2919 static char root_dir[MAX_UTF8_PATH];
2920 const char *p;
2922 p = getenv ("emacs_dir");
2923 if (p == NULL)
2924 emacs_abort ();
2925 filename_from_ansi (p, root_dir);
2926 root_dir[parse_root (root_dir, NULL)] = '\0';
2927 dostounix_filename (root_dir);
2928 return root_dir;
2931 #include <sys/timeb.h>
2933 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2935 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2937 struct _timeb tb;
2938 _ftime (&tb);
2940 tv->tv_sec = tb.time;
2941 tv->tv_usec = tb.millitm * 1000L;
2942 /* Implementation note: _ftime sometimes doesn't update the dstflag
2943 according to the new timezone when the system timezone is
2944 changed. We could fix that by using GetSystemTime and
2945 GetTimeZoneInformation, but that doesn't seem necessary, since
2946 Emacs always calls gettimeofday with the 2nd argument NULL (see
2947 current_emacs_time). */
2948 if (tz)
2950 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2951 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2953 return 0;
2956 /* Emulate fdutimens. */
2958 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2959 TIMESPEC[0] and TIMESPEC[1], respectively.
2960 FD must be either negative -- in which case it is ignored --
2961 or a file descriptor that is open on FILE.
2962 If FD is nonnegative, then FILE can be NULL, which means
2963 use just futimes instead of utimes.
2964 If TIMESPEC is null, FAIL.
2965 Return 0 on success, -1 (setting errno) on failure. */
2968 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2970 if (!timespec)
2972 errno = ENOSYS;
2973 return -1;
2975 if (fd < 0 && !file)
2977 errno = EBADF;
2978 return -1;
2980 /* _futime's prototype defines 2nd arg as having the type 'struct
2981 _utimbuf', while utime needs to accept 'struct utimbuf' for
2982 compatibility with Posix. So we need to use 2 different (but
2983 equivalent) types to avoid compiler warnings, sigh. */
2984 if (fd >= 0)
2986 struct _utimbuf _ut;
2988 _ut.actime = timespec[0].tv_sec;
2989 _ut.modtime = timespec[1].tv_sec;
2990 return _futime (fd, &_ut);
2992 else
2994 struct utimbuf ut;
2996 ut.actime = timespec[0].tv_sec;
2997 ut.modtime = timespec[1].tv_sec;
2998 /* Call 'utime', which is implemented below, not the MS library
2999 function, which fails on directories. */
3000 return utime (file, &ut);
3005 /* ------------------------------------------------------------------------- */
3006 /* IO support and wrapper functions for the Windows API. */
3007 /* ------------------------------------------------------------------------- */
3009 /* Place a wrapper around the MSVC version of ctime. It returns NULL
3010 on network directories, so we handle that case here.
3011 (Ulrich Leodolter, 1/11/95). */
3012 char *
3013 sys_ctime (const time_t *t)
3015 char *str = (char *) ctime (t);
3016 return (str ? str : (char *)"Sun Jan 01 00:00:00 1970");
3019 /* Emulate sleep...we could have done this with a define, but that
3020 would necessitate including windows.h in the files that used it.
3021 This is much easier. */
3022 void
3023 sys_sleep (int seconds)
3025 Sleep (seconds * 1000);
3028 /* Internal MSVC functions for low-level descriptor munging */
3029 extern int __cdecl _set_osfhnd (int fd, long h);
3030 extern int __cdecl _free_osfhnd (int fd);
3032 /* parallel array of private info on file handles */
3033 filedesc fd_info [ MAXDESC ];
3035 typedef struct volume_info_data {
3036 struct volume_info_data * next;
3038 /* time when info was obtained */
3039 DWORD timestamp;
3041 /* actual volume info */
3042 char * root_dir;
3043 DWORD serialnum;
3044 DWORD maxcomp;
3045 DWORD flags;
3046 char * name;
3047 char * type;
3048 } volume_info_data;
3050 /* Global referenced by various functions. */
3051 static volume_info_data volume_info;
3053 /* Vector to indicate which drives are local and fixed (for which cached
3054 data never expires). */
3055 static BOOL fixed_drives[26];
3057 /* Consider cached volume information to be stale if older than 10s,
3058 at least for non-local drives. Info for fixed drives is never stale. */
3059 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3060 #define VOLINFO_STILL_VALID( root_dir, info ) \
3061 ( ( isalpha (root_dir[0]) && \
3062 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3063 || GetTickCount () - info->timestamp < 10000 )
3065 /* Cache support functions. */
3067 /* Simple linked list with linear search is sufficient. */
3068 static volume_info_data *volume_cache = NULL;
3070 static volume_info_data *
3071 lookup_volume_info (char * root_dir)
3073 volume_info_data * info;
3075 for (info = volume_cache; info; info = info->next)
3076 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3077 break;
3078 return info;
3081 static void
3082 add_volume_info (char * root_dir, volume_info_data * info)
3084 info->root_dir = xstrdup (root_dir);
3085 unixtodos_filename (info->root_dir);
3086 info->next = volume_cache;
3087 volume_cache = info;
3091 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3092 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3093 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3094 static volume_info_data *
3095 GetCachedVolumeInformation (char * root_dir)
3097 volume_info_data * info;
3098 char default_root[ MAX_UTF8_PATH ];
3099 char name[MAX_PATH+1];
3100 char type[MAX_PATH+1];
3102 /* NULL for root_dir means use root from current directory. */
3103 if (root_dir == NULL)
3105 if (w32_unicode_filenames)
3107 wchar_t curdirw[MAX_PATH];
3109 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3110 return NULL;
3111 filename_from_utf16 (curdirw, default_root);
3113 else
3115 char curdira[MAX_PATH];
3117 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3118 return NULL;
3119 filename_from_ansi (curdira, default_root);
3121 parse_root (default_root, (const char **)&root_dir);
3122 *root_dir = 0;
3123 root_dir = default_root;
3126 /* Local fixed drives can be cached permanently. Removable drives
3127 cannot be cached permanently, since the volume name and serial
3128 number (if nothing else) can change. Remote drives should be
3129 treated as if they are removable, since there is no sure way to
3130 tell whether they are or not. Also, the UNC association of drive
3131 letters mapped to remote volumes can be changed at any time (even
3132 by other processes) without notice.
3134 As a compromise, so we can benefit from caching info for remote
3135 volumes, we use a simple expiry mechanism to invalidate cache
3136 entries that are more than ten seconds old. */
3138 #if 0
3139 /* No point doing this, because WNetGetConnection is even slower than
3140 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3141 GetDriveType is about the only call of this type which does not
3142 involve network access, and so is extremely quick). */
3144 /* Map drive letter to UNC if remote. */
3145 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3147 char remote_name[ 256 ];
3148 char drive[3] = { root_dir[0], ':' };
3150 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3151 == NO_ERROR)
3152 /* do something */ ;
3154 #endif
3156 info = lookup_volume_info (root_dir);
3158 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3160 DWORD serialnum;
3161 DWORD maxcomp;
3162 DWORD flags;
3164 /* Info is not cached, or is stale. */
3165 if (w32_unicode_filenames)
3167 wchar_t root_w[MAX_PATH];
3168 wchar_t name_w[MAX_PATH+1];
3169 wchar_t type_w[MAX_PATH+1];
3171 filename_to_utf16 (root_dir, root_w);
3172 if (!GetVolumeInformationW (root_w,
3173 name_w, sizeof (name_w),
3174 &serialnum,
3175 &maxcomp,
3176 &flags,
3177 type_w, sizeof (type_w)))
3178 return NULL;
3179 /* Hmm... not really 100% correct, as these 2 are not file
3180 names... */
3181 filename_from_utf16 (name_w, name);
3182 filename_from_utf16 (type_w, type);
3184 else
3186 char root_a[MAX_PATH];
3187 char name_a[MAX_PATH+1];
3188 char type_a[MAX_PATH+1];
3190 filename_to_ansi (root_dir, root_a);
3191 if (!GetVolumeInformationA (root_a,
3192 name_a, sizeof (name_a),
3193 &serialnum,
3194 &maxcomp,
3195 &flags,
3196 type_a, sizeof (type_a)))
3197 return NULL;
3198 filename_from_ansi (name_a, name);
3199 filename_from_ansi (type_a, type);
3202 /* Cache the volume information for future use, overwriting existing
3203 entry if present. */
3204 if (info == NULL)
3206 info = xmalloc (sizeof (volume_info_data));
3207 add_volume_info (root_dir, info);
3209 else
3211 xfree (info->name);
3212 xfree (info->type);
3215 info->name = xstrdup (name);
3216 unixtodos_filename (info->name);
3217 info->serialnum = serialnum;
3218 info->maxcomp = maxcomp;
3219 info->flags = flags;
3220 info->type = xstrdup (type);
3221 info->timestamp = GetTickCount ();
3224 return info;
3227 /* Get information on the volume where NAME is held; set path pointer to
3228 start of pathname in NAME (past UNC header\volume header if present),
3229 if pPath is non-NULL.
3231 Note: if NAME includes symlinks, the information is for the volume
3232 of the symlink, not of its target. That's because, even though
3233 GetVolumeInformation returns information about the symlink target
3234 of its argument, we only pass the root directory to
3235 GetVolumeInformation, not the full NAME. */
3236 static int
3237 get_volume_info (const char * name, const char ** pPath)
3239 char temp[MAX_UTF8_PATH];
3240 char *rootname = NULL; /* default to current volume */
3241 volume_info_data * info;
3242 int root_len = parse_root (name, pPath);
3244 if (name == NULL)
3245 return FALSE;
3247 /* Copy the root name of the volume, if given. */
3248 if (root_len)
3250 strncpy (temp, name, root_len);
3251 temp[root_len] = '\0';
3252 unixtodos_filename (temp);
3253 rootname = temp;
3256 info = GetCachedVolumeInformation (rootname);
3257 if (info != NULL)
3259 /* Set global referenced by other functions. */
3260 volume_info = *info;
3261 return TRUE;
3263 return FALSE;
3266 /* Determine if volume is FAT format (ie. only supports short 8.3
3267 names); also set path pointer to start of pathname in name, if
3268 pPath is non-NULL. */
3269 static int
3270 is_fat_volume (const char * name, const char ** pPath)
3272 if (get_volume_info (name, pPath))
3273 return (volume_info.maxcomp == 12);
3274 return FALSE;
3277 /* Convert all slashes in a filename to backslashes, and map filename
3278 to a valid 8.3 name if necessary. The result is a pointer to a
3279 static buffer, so CAVEAT EMPTOR! */
3280 const char *map_w32_filename (const char *, const char **);
3282 const char *
3283 map_w32_filename (const char * name, const char ** pPath)
3285 static char shortname[MAX_UTF8_PATH];
3286 char * str = shortname;
3287 char c;
3288 char * path;
3289 const char * save_name = name;
3291 if (strlen (name) >= sizeof (shortname))
3293 /* Return a filename which will cause callers to fail. */
3294 strcpy (shortname, "?");
3295 return shortname;
3298 if (!fatal_error_in_progress /* disable fancy processing during crash */
3299 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3301 register int left = 8; /* maximum number of chars in part */
3302 register int extn = 0; /* extension added? */
3303 register int dots = 2; /* maximum number of dots allowed */
3305 while (name < path)
3306 *str++ = *name++; /* skip past UNC header */
3308 while ((c = *name++))
3310 switch ( c )
3312 case ':':
3313 case '\\':
3314 case '/':
3315 *str++ = (c == ':' ? ':' : '\\');
3316 extn = 0; /* reset extension flags */
3317 dots = 2; /* max 2 dots */
3318 left = 8; /* max length 8 for main part */
3319 break;
3320 case '.':
3321 if ( dots )
3323 /* Convert path components of the form .xxx to _xxx,
3324 but leave . and .. as they are. This allows .emacs
3325 to be read as _emacs, for example. */
3327 if (! *name ||
3328 *name == '.' ||
3329 IS_DIRECTORY_SEP (*name))
3331 *str++ = '.';
3332 dots--;
3334 else
3336 *str++ = '_';
3337 left--;
3338 dots = 0;
3341 else if ( !extn )
3343 *str++ = '.';
3344 extn = 1; /* we've got an extension */
3345 left = 3; /* 3 chars in extension */
3347 else
3349 /* any embedded dots after the first are converted to _ */
3350 *str++ = '_';
3352 break;
3353 case '~':
3354 case '#': /* don't lose these, they're important */
3355 if ( ! left )
3356 str[-1] = c; /* replace last character of part */
3357 /* FALLTHRU */
3358 default:
3359 if ( left && 'A' <= c && c <= 'Z' )
3361 *str++ = tolower (c); /* map to lower case (looks nicer) */
3362 left--;
3363 dots = 0; /* started a path component */
3365 break;
3368 *str = '\0';
3370 else
3372 strcpy (shortname, name);
3373 unixtodos_filename (shortname);
3376 if (pPath)
3377 *pPath = shortname + (path - save_name);
3379 return shortname;
3382 static int
3383 is_exec (const char * name)
3385 char * p = strrchr (name, '.');
3386 return
3387 (p != NULL
3388 && (xstrcasecmp (p, ".exe") == 0 ||
3389 xstrcasecmp (p, ".com") == 0 ||
3390 xstrcasecmp (p, ".bat") == 0 ||
3391 xstrcasecmp (p, ".cmd") == 0));
3394 /* Emulate the Unix directory procedures opendir, closedir, and
3395 readdir. We rename them to sys_* names because some versions of
3396 MinGW startup code call opendir and readdir to glob wildcards, and
3397 the code that calls them doesn't grok UTF-8 encoded file names we
3398 produce in dirent->d_name[]. */
3400 struct dirent dir_static; /* simulated directory contents */
3401 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3402 static int dir_is_fat;
3403 static char dir_pathname[MAX_UTF8_PATH];
3404 static WIN32_FIND_DATAW dir_find_data_w;
3405 static WIN32_FIND_DATAA dir_find_data_a;
3406 #define DIR_FIND_DATA_W 1
3407 #define DIR_FIND_DATA_A 2
3408 static int last_dir_find_data = -1;
3410 /* Support shares on a network resource as subdirectories of a read-only
3411 root directory. */
3412 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3413 static HANDLE open_unc_volume (const char *);
3414 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3415 static void close_unc_volume (HANDLE);
3417 DIR *
3418 sys_opendir (const char *filename)
3420 DIR *dirp;
3422 /* Opening is done by FindFirstFile. However, a read is inherent to
3423 this operation, so we defer the open until read time. */
3425 if (dir_find_handle != INVALID_HANDLE_VALUE)
3426 return NULL;
3427 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3428 return NULL;
3430 /* Note: We don't support traversal of UNC volumes via symlinks.
3431 Doing so would mean punishing 99.99% of use cases by resolving
3432 all the possible symlinks in FILENAME, recursively. */
3433 if (is_unc_volume (filename))
3435 wnet_enum_handle = open_unc_volume (filename);
3436 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3437 return NULL;
3440 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3441 return NULL;
3443 dirp->dd_fd = 0;
3444 dirp->dd_loc = 0;
3445 dirp->dd_size = 0;
3447 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3448 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3449 /* Note: We don't support symlinks to file names on FAT volumes.
3450 Doing so would mean punishing 99.99% of use cases by resolving
3451 all the possible symlinks in FILENAME, recursively. */
3452 dir_is_fat = is_fat_volume (filename, NULL);
3454 return dirp;
3457 void
3458 sys_closedir (DIR *dirp)
3460 /* If we have a find-handle open, close it. */
3461 if (dir_find_handle != INVALID_HANDLE_VALUE)
3463 FindClose (dir_find_handle);
3464 dir_find_handle = INVALID_HANDLE_VALUE;
3466 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3468 close_unc_volume (wnet_enum_handle);
3469 wnet_enum_handle = INVALID_HANDLE_VALUE;
3471 xfree ((char *) dirp);
3474 struct dirent *
3475 sys_readdir (DIR *dirp)
3477 int downcase = !NILP (Vw32_downcase_file_names);
3479 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3481 if (!read_unc_volume (wnet_enum_handle,
3482 dir_find_data_w.cFileName,
3483 dir_find_data_a.cFileName,
3484 MAX_PATH))
3485 return NULL;
3487 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3488 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3490 char filename[MAX_UTF8_PATH];
3491 int ln;
3492 bool last_slash = true;
3494 /* Note: We don't need to worry about dir_pathname being longer
3495 than MAX_UTF8_PATH, as sys_opendir already took care of that
3496 when it called map_w32_filename: that function will put a "?"
3497 in its return value in that case, thus failing all the calls
3498 below. */
3499 strcpy (filename, dir_pathname);
3500 ln = strlen (filename);
3501 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3502 last_slash = false;
3504 /* Note: No need to resolve symlinks in FILENAME, because
3505 FindFirst opens the directory that is the target of a
3506 symlink. */
3507 if (w32_unicode_filenames)
3509 wchar_t fnw[MAX_PATH + 2];
3511 filename_to_utf16 (filename, fnw);
3512 if (!last_slash)
3513 wcscat (fnw, L"\\");
3514 wcscat (fnw, L"*");
3515 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3517 else
3519 char fna[MAX_PATH + 2];
3521 filename_to_ansi (filename, fna);
3522 if (!last_slash)
3523 strcat (fna, "\\");
3524 strcat (fna, "*");
3525 /* If FILENAME is not representable by the current ANSI
3526 codepage, we don't want FindFirstFileA to interpret the
3527 '?' characters as a wildcard. */
3528 if (_mbspbrk (fna, "?"))
3529 dir_find_handle = INVALID_HANDLE_VALUE;
3530 else
3531 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3534 if (dir_find_handle == INVALID_HANDLE_VALUE)
3536 /* Any changes in the value of errno here should be in sync
3537 with what directory_files_internal does when it calls
3538 readdir. */
3539 switch (GetLastError ())
3541 /* Windows uses this value when FindFirstFile finds no
3542 files that match the wildcard. This is not supposed
3543 to happen, since our wildcard is "*", but just in
3544 case, if there's some weird empty directory with not
3545 even "." and ".." entries... */
3546 case ERROR_FILE_NOT_FOUND:
3547 errno = 0;
3548 /* FALLTHRU */
3549 default:
3550 break;
3551 case ERROR_ACCESS_DENIED:
3552 case ERROR_NETWORK_ACCESS_DENIED:
3553 errno = EACCES;
3554 break;
3555 case ERROR_PATH_NOT_FOUND:
3556 case ERROR_INVALID_DRIVE:
3557 case ERROR_NOT_READY:
3558 case ERROR_BAD_NETPATH:
3559 case ERROR_BAD_NET_NAME:
3560 errno = ENOENT;
3561 break;
3563 return NULL;
3566 else if (w32_unicode_filenames)
3568 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3570 errno = 0;
3571 return NULL;
3574 else
3576 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3578 errno = 0;
3579 return NULL;
3583 /* Emacs never uses this value, so don't bother making it match
3584 value returned by stat(). */
3585 dir_static.d_ino = 1;
3587 if (w32_unicode_filenames)
3589 if (downcase || dir_is_fat)
3591 wchar_t tem[MAX_PATH];
3593 wcscpy (tem, dir_find_data_w.cFileName);
3594 CharLowerW (tem);
3595 filename_from_utf16 (tem, dir_static.d_name);
3597 else
3598 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3599 last_dir_find_data = DIR_FIND_DATA_W;
3601 else
3603 char tem[MAX_PATH];
3605 /* If the file name in cFileName[] includes `?' characters, it
3606 means the original file name used characters that cannot be
3607 represented by the current ANSI codepage. To avoid total
3608 lossage, retrieve the short 8+3 alias of the long file
3609 name. */
3610 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3612 strcpy (tem, dir_find_data_a.cAlternateFileName);
3613 /* 8+3 aliases are returned in all caps, which could break
3614 various alists that look at filenames' extensions. */
3615 downcase = 1;
3617 else if (downcase || dir_is_fat)
3618 strcpy (tem, dir_find_data_a.cFileName);
3619 else
3620 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3621 if (downcase || dir_is_fat)
3623 _mbslwr (tem);
3624 filename_from_ansi (tem, dir_static.d_name);
3626 last_dir_find_data = DIR_FIND_DATA_A;
3629 dir_static.d_namlen = strlen (dir_static.d_name);
3630 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3631 dir_static.d_namlen - dir_static.d_namlen % 4;
3633 return &dir_static;
3636 static HANDLE
3637 open_unc_volume (const char *path)
3639 const char *fn = map_w32_filename (path, NULL);
3640 DWORD result;
3641 HANDLE henum;
3643 if (w32_unicode_filenames)
3645 NETRESOURCEW nrw;
3646 wchar_t fnw[MAX_PATH];
3648 nrw.dwScope = RESOURCE_GLOBALNET;
3649 nrw.dwType = RESOURCETYPE_DISK;
3650 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3651 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3652 nrw.lpLocalName = NULL;
3653 filename_to_utf16 (fn, fnw);
3654 nrw.lpRemoteName = fnw;
3655 nrw.lpComment = NULL;
3656 nrw.lpProvider = NULL;
3658 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3659 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3661 else
3663 NETRESOURCEA nra;
3664 char fna[MAX_PATH];
3666 nra.dwScope = RESOURCE_GLOBALNET;
3667 nra.dwType = RESOURCETYPE_DISK;
3668 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3669 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3670 nra.lpLocalName = NULL;
3671 filename_to_ansi (fn, fna);
3672 nra.lpRemoteName = fna;
3673 nra.lpComment = NULL;
3674 nra.lpProvider = NULL;
3676 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3677 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3679 if (result == NO_ERROR)
3680 return henum;
3681 else
3683 /* Make sure directory_files_internal reports a sensible error. */
3684 errno = ENOENT;
3685 return INVALID_HANDLE_VALUE;
3689 static void *
3690 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3692 DWORD count;
3693 int result;
3694 char *buffer;
3695 DWORD bufsize = 512;
3696 void *retval;
3698 count = 1;
3699 if (w32_unicode_filenames)
3701 wchar_t *ptrw;
3703 bufsize *= 2;
3704 buffer = alloca (bufsize);
3705 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3706 if (result != NO_ERROR)
3707 return NULL;
3708 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3709 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3710 ptrw += 2;
3711 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3712 ptrw++;
3713 wcsncpy (fname_w, ptrw, size);
3714 retval = fname_w;
3716 else
3718 int dbcs_p = max_filename_mbslen () > 1;
3719 char *ptra;
3721 buffer = alloca (bufsize);
3722 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3723 if (result != NO_ERROR)
3724 return NULL;
3725 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3726 ptra += 2;
3727 if (!dbcs_p)
3728 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3729 else
3731 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3732 ptra = CharNextExA (file_name_codepage, ptra, 0);
3734 ptra++;
3735 strncpy (fname_a, ptra, size);
3736 retval = fname_a;
3739 return retval;
3742 static void
3743 close_unc_volume (HANDLE henum)
3745 if (henum != INVALID_HANDLE_VALUE)
3746 WNetCloseEnum (henum);
3749 static DWORD
3750 unc_volume_file_attributes (const char *path)
3752 HANDLE henum;
3753 DWORD attrs;
3755 henum = open_unc_volume (path);
3756 if (henum == INVALID_HANDLE_VALUE)
3757 return -1;
3759 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3761 close_unc_volume (henum);
3763 return attrs;
3766 /* Ensure a network connection is authenticated. */
3767 static void
3768 logon_network_drive (const char *path)
3770 char share[MAX_UTF8_PATH];
3771 int n_slashes;
3772 char drive[4];
3773 UINT drvtype;
3774 char *p;
3775 DWORD val;
3777 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3778 drvtype = DRIVE_REMOTE;
3779 else if (path[0] == '\0' || path[1] != ':')
3780 drvtype = GetDriveType (NULL);
3781 else
3783 drive[0] = path[0];
3784 drive[1] = ':';
3785 drive[2] = '\\';
3786 drive[3] = '\0';
3787 drvtype = GetDriveType (drive);
3790 /* Only logon to networked drives. */
3791 if (drvtype != DRIVE_REMOTE)
3792 return;
3794 n_slashes = 2;
3795 strncpy (share, path, MAX_UTF8_PATH);
3796 /* Truncate to just server and share name. */
3797 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3799 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3801 *p = '\0';
3802 break;
3806 if (w32_unicode_filenames)
3808 NETRESOURCEW resourcew;
3809 wchar_t share_w[MAX_PATH];
3811 resourcew.dwScope = RESOURCE_GLOBALNET;
3812 resourcew.dwType = RESOURCETYPE_DISK;
3813 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3814 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3815 resourcew.lpLocalName = NULL;
3816 filename_to_utf16 (share, share_w);
3817 resourcew.lpRemoteName = share_w;
3818 resourcew.lpProvider = NULL;
3820 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3822 else
3824 NETRESOURCEA resourcea;
3825 char share_a[MAX_PATH];
3827 resourcea.dwScope = RESOURCE_GLOBALNET;
3828 resourcea.dwType = RESOURCETYPE_DISK;
3829 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3830 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3831 resourcea.lpLocalName = NULL;
3832 filename_to_ansi (share, share_a);
3833 resourcea.lpRemoteName = share_a;
3834 resourcea.lpProvider = NULL;
3836 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3839 switch (val)
3841 case NO_ERROR:
3842 case ERROR_ALREADY_ASSIGNED:
3843 break;
3844 case ERROR_ACCESS_DENIED:
3845 case ERROR_LOGON_FAILURE:
3846 errno = EACCES;
3847 break;
3848 case ERROR_BUSY:
3849 errno = EAGAIN;
3850 break;
3851 case ERROR_BAD_NET_NAME:
3852 case ERROR_NO_NET_OR_BAD_PATH:
3853 case ERROR_NO_NETWORK:
3854 case ERROR_CANCELLED:
3855 default:
3856 errno = ENOENT;
3857 break;
3861 /* Emulate faccessat(2). */
3863 faccessat (int dirfd, const char * path, int mode, int flags)
3865 DWORD attributes;
3867 if (dirfd != AT_FDCWD
3868 && !(IS_DIRECTORY_SEP (path[0])
3869 || IS_DEVICE_SEP (path[1])))
3871 errno = EBADF;
3872 return -1;
3875 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3876 newer versions blow up when passed D_OK. */
3877 path = map_w32_filename (path, NULL);
3878 /* If the last element of PATH is a symlink, we need to resolve it
3879 to get the attributes of its target file. Note: any symlinks in
3880 PATH elements other than the last one are transparently resolved
3881 by GetFileAttributes below. */
3882 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3883 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3884 path = chase_symlinks (path);
3886 if (w32_unicode_filenames)
3888 wchar_t path_w[MAX_PATH];
3890 filename_to_utf16 (path, path_w);
3891 attributes = GetFileAttributesW (path_w);
3893 else
3895 char path_a[MAX_PATH];
3897 filename_to_ansi (path, path_a);
3898 attributes = GetFileAttributesA (path_a);
3901 if (attributes == -1)
3903 DWORD w32err = GetLastError ();
3905 switch (w32err)
3907 case ERROR_INVALID_NAME:
3908 case ERROR_BAD_PATHNAME:
3909 if (is_unc_volume (path))
3911 attributes = unc_volume_file_attributes (path);
3912 if (attributes == -1)
3914 errno = EACCES;
3915 return -1;
3917 goto check_attrs;
3919 /* FALLTHROUGH */
3920 case ERROR_FILE_NOT_FOUND:
3921 case ERROR_BAD_NETPATH:
3922 errno = ENOENT;
3923 break;
3924 default:
3925 errno = EACCES;
3926 break;
3928 return -1;
3931 check_attrs:
3932 if ((mode & X_OK) != 0
3933 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3935 errno = EACCES;
3936 return -1;
3938 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3940 errno = EACCES;
3941 return -1;
3943 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3945 errno = EACCES;
3946 return -1;
3948 return 0;
3951 /* A special test for DIRNAME being a directory accessible by the
3952 current user. This is needed because the security permissions in
3953 directory's ACLs are not visible in the Posix-style mode bits
3954 returned by 'stat' and in attributes returned by GetFileAttributes.
3955 So a directory would seem like it's readable by the current user,
3956 but will in fact error out with EACCES when they actually try. */
3958 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3960 char pattern[MAX_UTF8_PATH];
3961 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3962 HANDLE dh;
3964 /* Network volumes need a different reading method. */
3965 if (is_unc_volume (dirname))
3967 void *read_result = NULL;
3968 wchar_t fnw[MAX_PATH];
3969 char fna[MAX_PATH];
3971 dh = open_unc_volume (dirname);
3972 if (dh != INVALID_HANDLE_VALUE)
3974 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
3975 close_unc_volume (dh);
3977 /* Treat empty volumes as accessible. */
3978 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
3981 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3982 MAX_UTF8_PATH. */
3983 strcpy (pattern, map_w32_filename (dirname, NULL));
3985 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3986 opens the directory that is the target of a symlink. */
3987 if (w32_unicode_filenames)
3989 wchar_t pat_w[MAX_PATH + 2];
3990 WIN32_FIND_DATAW dfd_w;
3992 filename_to_utf16 (pattern, pat_w);
3993 if (!last_slash)
3994 wcscat (pat_w, L"\\");
3995 wcscat (pat_w, L"*");
3996 dh = FindFirstFileW (pat_w, &dfd_w);
3998 else
4000 char pat_a[MAX_PATH + 2];
4001 WIN32_FIND_DATAA dfd_a;
4003 filename_to_ansi (pattern, pat_a);
4004 if (!last_slash)
4005 strcpy (pat_a, "\\");
4006 strcat (pat_a, "*");
4007 /* In case DIRNAME cannot be expressed in characters from the
4008 current ANSI codepage. */
4009 if (_mbspbrk (pat_a, "?"))
4010 dh = INVALID_HANDLE_VALUE;
4011 else
4012 dh = FindFirstFileA (pat_a, &dfd_a);
4015 if (dh == INVALID_HANDLE_VALUE)
4016 return 0;
4017 FindClose (dh);
4018 return 1;
4021 /* A version of 'access' to be used locally with file names in
4022 locale-specific encoding. Does not resolve symlinks and does not
4023 support file names on FAT12 and FAT16 volumes, but that's OK, since
4024 we only invoke this function for files inside the Emacs source or
4025 installation tree, on directories (so any symlinks should have the
4026 directory bit set), and on short file names such as "C:/.emacs". */
4027 static int
4028 sys_access (const char *fname, int mode)
4030 char fname_copy[MAX_PATH], *p;
4031 DWORD attributes;
4033 strcpy (fname_copy, fname);
4034 /* Do the equivalent of unixtodos_filename. */
4035 for (p = fname_copy; *p; p = CharNext (p))
4036 if (*p == '/')
4037 *p = '\\';
4039 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4041 DWORD w32err = GetLastError ();
4043 switch (w32err)
4045 case ERROR_INVALID_NAME:
4046 case ERROR_BAD_PATHNAME:
4047 case ERROR_FILE_NOT_FOUND:
4048 case ERROR_BAD_NETPATH:
4049 errno = ENOENT;
4050 break;
4051 default:
4052 errno = EACCES;
4053 break;
4055 return -1;
4057 if ((mode & X_OK) != 0
4058 && !(is_exec (fname_copy)
4059 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4061 errno = EACCES;
4062 return -1;
4064 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4066 errno = EACCES;
4067 return -1;
4069 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4071 errno = EACCES;
4072 return -1;
4074 return 0;
4077 /* Shadow some MSVC runtime functions to map requests for long filenames
4078 to reasonable short names if necessary. This was originally added to
4079 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4080 long file names. */
4083 sys_chdir (const char * path)
4085 path = map_w32_filename (path, NULL);
4086 if (w32_unicode_filenames)
4088 wchar_t newdir_w[MAX_PATH];
4090 if (filename_to_utf16 (path, newdir_w) == 0)
4091 return _wchdir (newdir_w);
4092 return -1;
4094 else
4096 char newdir_a[MAX_PATH];
4098 if (filename_to_ansi (path, newdir_a) == 0)
4099 return _chdir (newdir_a);
4100 return -1;
4105 sys_chmod (const char * path, int mode)
4107 path = chase_symlinks (map_w32_filename (path, NULL));
4108 if (w32_unicode_filenames)
4110 wchar_t path_w[MAX_PATH];
4112 filename_to_utf16 (path, path_w);
4113 return _wchmod (path_w, mode);
4115 else
4117 char path_a[MAX_PATH];
4119 filename_to_ansi (path, path_a);
4120 return _chmod (path_a, mode);
4125 sys_creat (const char * path, int mode)
4127 path = map_w32_filename (path, NULL);
4128 if (w32_unicode_filenames)
4130 wchar_t path_w[MAX_PATH];
4132 filename_to_utf16 (path, path_w);
4133 return _wcreat (path_w, mode);
4135 else
4137 char path_a[MAX_PATH];
4139 filename_to_ansi (path, path_a);
4140 return _creat (path_a, mode);
4144 FILE *
4145 sys_fopen (const char * path, const char * mode)
4147 int fd;
4148 int oflag;
4149 const char * mode_save = mode;
4151 /* Force all file handles to be non-inheritable. This is necessary to
4152 ensure child processes don't unwittingly inherit handles that might
4153 prevent future file access. */
4155 if (mode[0] == 'r')
4156 oflag = O_RDONLY;
4157 else if (mode[0] == 'w' || mode[0] == 'a')
4158 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4159 else
4160 return NULL;
4162 /* Only do simplistic option parsing. */
4163 while (*++mode)
4164 if (mode[0] == '+')
4166 oflag &= ~(O_RDONLY | O_WRONLY);
4167 oflag |= O_RDWR;
4169 else if (mode[0] == 'b')
4171 oflag &= ~O_TEXT;
4172 oflag |= O_BINARY;
4174 else if (mode[0] == 't')
4176 oflag &= ~O_BINARY;
4177 oflag |= O_TEXT;
4179 else break;
4181 path = map_w32_filename (path, NULL);
4182 if (w32_unicode_filenames)
4184 wchar_t path_w[MAX_PATH];
4186 filename_to_utf16 (path, path_w);
4187 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4189 else
4191 char path_a[MAX_PATH];
4193 filename_to_ansi (path, path_a);
4194 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4196 if (fd < 0)
4197 return NULL;
4199 return _fdopen (fd, mode_save);
4202 /* This only works on NTFS volumes, but is useful to have. */
4204 sys_link (const char * old, const char * new)
4206 HANDLE fileh;
4207 int result = -1;
4208 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4209 wchar_t oldname_w[MAX_PATH];
4210 char oldname_a[MAX_PATH];
4212 if (old == NULL || new == NULL)
4214 errno = ENOENT;
4215 return -1;
4218 strcpy (oldname, map_w32_filename (old, NULL));
4219 strcpy (newname, map_w32_filename (new, NULL));
4221 if (w32_unicode_filenames)
4223 filename_to_utf16 (oldname, oldname_w);
4224 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4225 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4227 else
4229 filename_to_ansi (oldname, oldname_a);
4230 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4231 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4233 if (fileh != INVALID_HANDLE_VALUE)
4235 int wlen;
4237 /* Confusingly, the "alternate" stream name field does not apply
4238 when restoring a hard link, and instead contains the actual
4239 stream data for the link (ie. the name of the link to create).
4240 The WIN32_STREAM_ID structure before the cStreamName field is
4241 the stream header, which is then immediately followed by the
4242 stream data. */
4244 struct {
4245 WIN32_STREAM_ID wid;
4246 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4247 } data;
4249 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4250 indicates that flag is unsupported for CP_UTF8, and OTOH says
4251 it is the default anyway. */
4252 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4253 data.wid.cStreamName, MAX_PATH);
4254 if (wlen > 0)
4256 LPVOID context = NULL;
4257 DWORD wbytes = 0;
4259 data.wid.dwStreamId = BACKUP_LINK;
4260 data.wid.dwStreamAttributes = 0;
4261 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4262 data.wid.Size.HighPart = 0;
4263 data.wid.dwStreamNameSize = 0;
4265 if (BackupWrite (fileh, (LPBYTE)&data,
4266 offsetof (WIN32_STREAM_ID, cStreamName)
4267 + data.wid.Size.LowPart,
4268 &wbytes, FALSE, FALSE, &context)
4269 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4271 /* succeeded */
4272 result = 0;
4274 else
4276 DWORD err = GetLastError ();
4277 DWORD attributes;
4279 switch (err)
4281 case ERROR_ACCESS_DENIED:
4282 /* This is what happens when OLDNAME is a directory,
4283 since Windows doesn't support hard links to
4284 directories. Posix says to set errno to EPERM in
4285 that case. */
4286 if (w32_unicode_filenames)
4287 attributes = GetFileAttributesW (oldname_w);
4288 else
4289 attributes = GetFileAttributesA (oldname_a);
4290 if (attributes != -1
4291 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4292 errno = EPERM;
4293 else if (attributes == -1
4294 && is_unc_volume (oldname)
4295 && unc_volume_file_attributes (oldname) != -1)
4296 errno = EPERM;
4297 else
4298 errno = EACCES;
4299 break;
4300 case ERROR_TOO_MANY_LINKS:
4301 errno = EMLINK;
4302 break;
4303 case ERROR_NOT_SAME_DEVICE:
4304 errno = EXDEV;
4305 break;
4306 default:
4307 errno = EINVAL;
4308 break;
4313 CloseHandle (fileh);
4315 else
4316 errno = ENOENT;
4318 return result;
4322 sys_mkdir (const char * path)
4324 path = map_w32_filename (path, NULL);
4326 if (w32_unicode_filenames)
4328 wchar_t path_w[MAX_PATH];
4330 filename_to_utf16 (path, path_w);
4331 return _wmkdir (path_w);
4333 else
4335 char path_a[MAX_PATH];
4337 filename_to_ansi (path, path_a);
4338 return _mkdir (path_a);
4343 sys_open (const char * path, int oflag, int mode)
4345 const char* mpath = map_w32_filename (path, NULL);
4346 int res = -1;
4348 if (w32_unicode_filenames)
4350 wchar_t mpath_w[MAX_PATH];
4352 filename_to_utf16 (mpath, mpath_w);
4353 /* If possible, try to open file without _O_CREAT, to be able to
4354 write to existing hidden and system files. Force all file
4355 handles to be non-inheritable. */
4356 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4357 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4358 if (res < 0)
4359 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4361 else
4363 char mpath_a[MAX_PATH];
4365 filename_to_ansi (mpath, mpath_a);
4366 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4367 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4368 if (res < 0)
4369 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4372 return res;
4375 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4376 when using mktemp.
4378 Standard algorithm for generating a temporary file name seems to be
4379 use pid or tid with a letter on the front (in place of the 6 X's)
4380 and cycle through the letters to find a unique name. We extend
4381 that to allow any reasonable character as the first of the 6 X's,
4382 so that the number of simultaneously used temporary files will be
4383 greater. */
4386 mkostemp (char * template, int flags)
4388 char * p;
4389 int i, fd = -1;
4390 unsigned uid = GetCurrentThreadId ();
4391 int save_errno = errno;
4392 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4394 errno = EINVAL;
4395 if (template == NULL)
4396 return -1;
4398 p = template + strlen (template);
4399 i = 5;
4400 /* replace up to the last 5 X's with uid in decimal */
4401 while (--p >= template && p[0] == 'X' && --i >= 0)
4403 p[0] = '0' + uid % 10;
4404 uid /= 10;
4407 if (i < 0 && p[0] == 'X')
4409 i = 0;
4412 p[0] = first_char[i];
4413 if ((fd = sys_open (template,
4414 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4415 S_IRUSR | S_IWUSR)) >= 0
4416 || errno != EEXIST)
4418 if (fd >= 0)
4419 errno = save_errno;
4420 return fd;
4423 while (++i < sizeof (first_char));
4426 /* Template is badly formed or else we can't generate a unique name. */
4427 return -1;
4431 fchmod (int fd, mode_t mode)
4433 return 0;
4437 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4439 BOOL result;
4440 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4441 int newname_dev;
4442 int oldname_dev;
4443 bool have_temp_a = false;
4445 /* MoveFile on Windows 95 doesn't correctly change the short file name
4446 alias in a number of circumstances (it is not easy to predict when
4447 just by looking at oldname and newname, unfortunately). In these
4448 cases, renaming through a temporary name avoids the problem.
4450 A second problem on Windows 95 is that renaming through a temp name when
4451 newname is uppercase fails (the final long name ends up in
4452 lowercase, although the short alias might be uppercase) UNLESS the
4453 long temp name is not 8.3.
4455 So, on Windows 95 we always rename through a temp name, and we make sure
4456 the temp name has a long extension to ensure correct renaming. */
4458 strcpy (temp, map_w32_filename (oldname, NULL));
4460 /* volume_info is set indirectly by map_w32_filename. */
4461 oldname_dev = volume_info.serialnum;
4463 if (os_subtype == OS_9X)
4465 char * o;
4466 char * p;
4467 int i = 0;
4468 char oldname_a[MAX_PATH];
4470 oldname = map_w32_filename (oldname, NULL);
4471 filename_to_ansi (oldname, oldname_a);
4472 filename_to_ansi (temp, temp_a);
4473 if ((o = strrchr (oldname_a, '\\')))
4474 o++;
4475 else
4476 o = (char *) oldname_a;
4478 if ((p = strrchr (temp_a, '\\')))
4479 p++;
4480 else
4481 p = temp_a;
4485 /* Force temp name to require a manufactured 8.3 alias - this
4486 seems to make the second rename work properly. */
4487 sprintf (p, "_.%s.%d", o, i);
4488 i++;
4489 result = rename (oldname_a, temp_a);
4491 /* This loop must surely terminate! */
4492 while (result < 0 && errno == EEXIST);
4493 if (result < 0)
4494 return -1;
4495 have_temp_a = true;
4498 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4499 (at least if it is a file; don't do this for directories).
4501 Since we mustn't do this if we are just changing the case of the
4502 file name (we would end up deleting the file we are trying to
4503 rename!), we let rename detect if the destination file already
4504 exists - that way we avoid the possible pitfalls of trying to
4505 determine ourselves whether two names really refer to the same
4506 file, which is not always possible in the general case. (Consider
4507 all the permutations of shared or subst'd drives, etc.) */
4509 newname = map_w32_filename (newname, NULL);
4511 /* volume_info is set indirectly by map_w32_filename. */
4512 newname_dev = volume_info.serialnum;
4514 if (w32_unicode_filenames)
4516 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4518 filename_to_utf16 (temp, temp_w);
4519 filename_to_utf16 (newname, newname_w);
4520 result = _wrename (temp_w, newname_w);
4521 if (result < 0 && force)
4523 DWORD w32err = GetLastError ();
4525 if (errno == EACCES
4526 && newname_dev != oldname_dev)
4528 /* The implementation of `rename' on Windows does not return
4529 errno = EXDEV when you are moving a directory to a
4530 different storage device (ex. logical disk). It returns
4531 EACCES instead. So here we handle such situations and
4532 return EXDEV. */
4533 DWORD attributes;
4535 if ((attributes = GetFileAttributesW (temp_w)) != -1
4536 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4537 errno = EXDEV;
4539 else if (errno == EEXIST)
4541 if (_wchmod (newname_w, 0666) != 0)
4542 return result;
4543 if (_wunlink (newname_w) != 0)
4544 return result;
4545 result = _wrename (temp_w, newname_w);
4547 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4548 && is_symlink (temp))
4550 /* This is Windows prohibiting the user from creating a
4551 symlink in another place, since that requires
4552 privileges. */
4553 errno = EPERM;
4557 else
4559 char newname_a[MAX_PATH];
4561 if (!have_temp_a)
4562 filename_to_ansi (temp, temp_a);
4563 filename_to_ansi (newname, newname_a);
4564 result = rename (temp_a, newname_a);
4565 if (result < 0 && force)
4567 DWORD w32err = GetLastError ();
4569 if (errno == EACCES
4570 && newname_dev != oldname_dev)
4572 DWORD attributes;
4574 if ((attributes = GetFileAttributesA (temp_a)) != -1
4575 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4576 errno = EXDEV;
4578 else if (errno == EEXIST)
4580 if (_chmod (newname_a, 0666) != 0)
4581 return result;
4582 if (_unlink (newname_a) != 0)
4583 return result;
4584 result = rename (temp_a, newname_a);
4586 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4587 && is_symlink (temp))
4588 errno = EPERM;
4592 return result;
4596 sys_rename (char const *old, char const *new)
4598 return sys_rename_replace (old, new, TRUE);
4602 sys_rmdir (const char * path)
4604 path = map_w32_filename (path, NULL);
4606 if (w32_unicode_filenames)
4608 wchar_t path_w[MAX_PATH];
4610 filename_to_utf16 (path, path_w);
4611 return _wrmdir (path_w);
4613 else
4615 char path_a[MAX_PATH];
4617 filename_to_ansi (path, path_a);
4618 return _rmdir (path_a);
4623 sys_unlink (const char * path)
4625 int rmstatus, e;
4627 path = map_w32_filename (path, NULL);
4629 if (w32_unicode_filenames)
4631 wchar_t path_w[MAX_PATH];
4633 filename_to_utf16 (path, path_w);
4634 /* On Unix, unlink works without write permission. */
4635 _wchmod (path_w, 0666);
4636 rmstatus = _wunlink (path_w);
4637 e = errno;
4638 /* Symlinks to directories can only be deleted by _rmdir;
4639 _unlink returns EACCES. */
4640 if (rmstatus != 0
4641 && errno == EACCES
4642 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4643 rmstatus = _wrmdir (path_w);
4644 else
4645 errno = e;
4647 else
4649 char path_a[MAX_PATH];
4651 filename_to_ansi (path, path_a);
4652 _chmod (path_a, 0666);
4653 rmstatus = _unlink (path_a);
4654 e = errno;
4655 if (rmstatus != 0
4656 && errno == EACCES
4657 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4658 rmstatus = _rmdir (path_a);
4659 else
4660 errno = e;
4663 return rmstatus;
4666 static FILETIME utc_base_ft;
4667 static ULONGLONG utc_base; /* In 100ns units */
4668 static int init = 0;
4670 #define FILETIME_TO_U64(result, ft) \
4671 do { \
4672 ULARGE_INTEGER uiTemp; \
4673 uiTemp.LowPart = (ft).dwLowDateTime; \
4674 uiTemp.HighPart = (ft).dwHighDateTime; \
4675 result = uiTemp.QuadPart; \
4676 } while (0)
4678 static void
4679 initialize_utc_base (void)
4681 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4682 SYSTEMTIME st;
4684 st.wYear = 1970;
4685 st.wMonth = 1;
4686 st.wDay = 1;
4687 st.wHour = 0;
4688 st.wMinute = 0;
4689 st.wSecond = 0;
4690 st.wMilliseconds = 0;
4692 SystemTimeToFileTime (&st, &utc_base_ft);
4693 FILETIME_TO_U64 (utc_base, utc_base_ft);
4696 static time_t
4697 convert_time (FILETIME ft)
4699 ULONGLONG tmp;
4701 if (!init)
4703 initialize_utc_base ();
4704 init = 1;
4707 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4708 return 0;
4710 FILETIME_TO_U64 (tmp, ft);
4711 return (time_t) ((tmp - utc_base) / 10000000L);
4714 static void
4715 convert_from_time_t (time_t time, FILETIME * pft)
4717 ULARGE_INTEGER tmp;
4719 if (!init)
4721 initialize_utc_base ();
4722 init = 1;
4725 /* time in 100ns units since 1-Jan-1601 */
4726 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4727 pft->dwHighDateTime = tmp.HighPart;
4728 pft->dwLowDateTime = tmp.LowPart;
4731 static PSECURITY_DESCRIPTOR
4732 get_file_security_desc_by_handle (HANDLE h)
4734 PSECURITY_DESCRIPTOR psd = NULL;
4735 DWORD err;
4736 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4737 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4739 err = get_security_info (h, SE_FILE_OBJECT, si,
4740 NULL, NULL, NULL, NULL, &psd);
4741 if (err != ERROR_SUCCESS)
4742 return NULL;
4744 return psd;
4747 static PSECURITY_DESCRIPTOR
4748 get_file_security_desc_by_name (const char *fname)
4750 PSECURITY_DESCRIPTOR psd = NULL;
4751 DWORD sd_len, err;
4752 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4753 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4755 if (!get_file_security (fname, si, psd, 0, &sd_len))
4757 err = GetLastError ();
4758 if (err != ERROR_INSUFFICIENT_BUFFER)
4759 return NULL;
4762 psd = xmalloc (sd_len);
4763 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4765 xfree (psd);
4766 return NULL;
4769 return psd;
4772 static DWORD
4773 get_rid (PSID sid)
4775 unsigned n_subauthorities;
4777 /* Use the last sub-authority value of the RID, the relative
4778 portion of the SID, as user/group ID. */
4779 n_subauthorities = *get_sid_sub_authority_count (sid);
4780 if (n_subauthorities < 1)
4781 return 0; /* the "World" RID */
4782 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4785 /* Caching SID and account values for faster lokup. */
4787 struct w32_id {
4788 unsigned rid;
4789 struct w32_id *next;
4790 char name[GNLEN+1];
4791 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4794 static struct w32_id *w32_idlist;
4796 static int
4797 w32_cached_id (PSID sid, unsigned *id, char *name)
4799 struct w32_id *tail, *found;
4801 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4803 if (equal_sid ((PSID)tail->sid, sid))
4805 found = tail;
4806 break;
4809 if (found)
4811 *id = found->rid;
4812 strcpy (name, found->name);
4813 return 1;
4815 else
4816 return 0;
4819 static void
4820 w32_add_to_cache (PSID sid, unsigned id, char *name)
4822 DWORD sid_len;
4823 struct w32_id *new_entry;
4825 /* We don't want to leave behind stale cache from when Emacs was
4826 dumped. */
4827 if (initialized)
4829 sid_len = get_length_sid (sid);
4830 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4831 if (new_entry)
4833 new_entry->rid = id;
4834 strcpy (new_entry->name, name);
4835 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4836 new_entry->next = w32_idlist;
4837 w32_idlist = new_entry;
4842 #define UID 1
4843 #define GID 2
4845 static int
4846 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4848 PSID sid = NULL;
4849 BOOL dflt;
4850 SID_NAME_USE ignore;
4851 char name[UNLEN+1];
4852 DWORD name_len = sizeof (name);
4853 char domain[1024];
4854 DWORD domain_len = sizeof (domain);
4855 int use_dflt = 0;
4856 int result;
4858 if (what == UID)
4859 result = get_security_descriptor_owner (psd, &sid, &dflt);
4860 else if (what == GID)
4861 result = get_security_descriptor_group (psd, &sid, &dflt);
4862 else
4863 result = 0;
4865 if (!result || !is_valid_sid (sid))
4866 use_dflt = 1;
4867 else if (!w32_cached_id (sid, id, nm))
4869 if (!lookup_account_sid (NULL, sid, name, &name_len,
4870 domain, &domain_len, &ignore)
4871 || name_len > UNLEN+1)
4872 use_dflt = 1;
4873 else
4875 *id = get_rid (sid);
4876 strcpy (nm, name);
4877 w32_add_to_cache (sid, *id, name);
4880 return use_dflt;
4883 static void
4884 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4886 int dflt_usr = 0, dflt_grp = 0;
4888 if (!psd)
4890 dflt_usr = 1;
4891 dflt_grp = 1;
4893 else
4895 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4896 dflt_usr = 1;
4897 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4898 dflt_grp = 1;
4900 /* Consider files to belong to current user/group, if we cannot get
4901 more accurate information. */
4902 if (dflt_usr)
4904 st->st_uid = dflt_passwd.pw_uid;
4905 strcpy (st->st_uname, dflt_passwd.pw_name);
4907 if (dflt_grp)
4909 st->st_gid = dflt_passwd.pw_gid;
4910 strcpy (st->st_gname, dflt_group.gr_name);
4914 /* Return non-zero if NAME is a potentially slow filesystem. */
4915 int is_slow_fs (const char *);
4918 is_slow_fs (const char *name)
4920 char drive_root[4];
4921 UINT devtype;
4923 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4924 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4925 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4926 devtype = GetDriveType (NULL); /* use root of current drive */
4927 else
4929 /* GetDriveType needs the root directory of the drive. */
4930 strncpy (drive_root, name, 2);
4931 drive_root[2] = '\\';
4932 drive_root[3] = '\0';
4933 devtype = GetDriveType (drive_root);
4935 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4938 /* If this is non-zero, the caller wants accurate information about
4939 file's owner and group, which could be expensive to get. dired.c
4940 uses this flag when needed for the job at hand. */
4941 int w32_stat_get_owner_group;
4943 /* MSVC stat function can't cope with UNC names and has other bugs, so
4944 replace it with our own. This also allows us to calculate consistent
4945 inode values and owner/group without hacks in the main Emacs code,
4946 and support file names encoded in UTF-8. */
4948 static int
4949 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4951 char *name, *save_name, *r;
4952 WIN32_FIND_DATAW wfd_w;
4953 WIN32_FIND_DATAA wfd_a;
4954 HANDLE fh;
4955 unsigned __int64 fake_inode = 0;
4956 int permission;
4957 int len;
4958 int rootdir = FALSE;
4959 PSECURITY_DESCRIPTOR psd = NULL;
4960 int is_a_symlink = 0;
4961 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4962 DWORD access_rights = 0;
4963 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4964 FILETIME ctime, atime, wtime;
4965 wchar_t name_w[MAX_PATH];
4966 char name_a[MAX_PATH];
4968 if (path == NULL || buf == NULL)
4970 errno = EFAULT;
4971 return -1;
4974 save_name = name = (char *) map_w32_filename (path, &path);
4975 /* Must be valid filename, no wild cards or other invalid
4976 characters. */
4977 if (strpbrk (name, "*?|<>\""))
4979 errno = ENOENT;
4980 return -1;
4983 len = strlen (name);
4984 /* Allocate 1 extra byte so that we could append a slash to a root
4985 directory, down below. */
4986 name = strcpy (alloca (len + 2), name);
4988 /* Avoid a somewhat costly call to is_symlink if the filesystem
4989 doesn't support symlinks. */
4990 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4991 is_a_symlink = is_symlink (name);
4993 /* Plan A: Open the file and get all the necessary information via
4994 the resulting handle. This solves several issues in one blow:
4996 . retrieves attributes for the target of a symlink, if needed
4997 . gets attributes of root directories and symlinks pointing to
4998 root directories, thus avoiding the need for special-casing
4999 these and detecting them by examining the file-name format
5000 . retrieves more accurate attributes (e.g., non-zero size for
5001 some directories, esp. directories that are junction points)
5002 . correctly resolves "c:/..", "/.." and similar file names
5003 . avoids run-time penalties for 99% of use cases
5005 Plan A is always tried first, unless the user asked not to (but
5006 if the file is a symlink and we need to follow links, we try Plan
5007 A even if the user asked not to).
5009 If Plan A fails, we go to Plan B (below), where various
5010 potentially expensive techniques must be used to handle "special"
5011 files such as UNC volumes etc. */
5012 if (!(NILP (Vw32_get_true_file_attributes)
5013 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
5014 /* Following symlinks requires getting the info by handle. */
5015 || (is_a_symlink && follow_symlinks))
5017 BY_HANDLE_FILE_INFORMATION info;
5019 if (is_a_symlink && !follow_symlinks)
5020 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5021 /* READ_CONTROL access rights are required to get security info
5022 by handle. But if the OS doesn't support security in the
5023 first place, we don't need to try. */
5024 if (is_windows_9x () != TRUE)
5025 access_rights |= READ_CONTROL;
5027 if (w32_unicode_filenames)
5029 filename_to_utf16 (name, name_w);
5030 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
5031 file_flags, NULL);
5032 /* If CreateFile fails with READ_CONTROL, try again with
5033 zero as access rights. */
5034 if (fh == INVALID_HANDLE_VALUE && access_rights)
5035 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
5036 file_flags, NULL);
5038 else
5040 filename_to_ansi (name, name_a);
5041 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5042 file_flags, NULL);
5043 if (fh == INVALID_HANDLE_VALUE && access_rights)
5044 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5045 file_flags, NULL);
5047 if (fh == INVALID_HANDLE_VALUE)
5048 goto no_true_file_attributes;
5050 /* This is more accurate in terms of getting the correct number
5051 of links, but is quite slow (it is noticeable when Emacs is
5052 making a list of file name completions). */
5053 if (GetFileInformationByHandle (fh, &info))
5055 nlinks = info.nNumberOfLinks;
5056 /* Might as well use file index to fake inode values, but this
5057 is not guaranteed to be unique unless we keep a handle open
5058 all the time (even then there are situations where it is
5059 not unique). Reputedly, there are at most 48 bits of info
5060 (on NTFS, presumably less on FAT). */
5061 fake_inode = info.nFileIndexHigh;
5062 fake_inode <<= 32;
5063 fake_inode += info.nFileIndexLow;
5064 serialnum = info.dwVolumeSerialNumber;
5065 fs_high = info.nFileSizeHigh;
5066 fs_low = info.nFileSizeLow;
5067 ctime = info.ftCreationTime;
5068 atime = info.ftLastAccessTime;
5069 wtime = info.ftLastWriteTime;
5070 fattrs = info.dwFileAttributes;
5072 else
5074 /* We don't go to Plan B here, because it's not clear that
5075 it's a good idea. The only known use case where
5076 CreateFile succeeds, but GetFileInformationByHandle fails
5077 (with ERROR_INVALID_FUNCTION) is for character devices
5078 such as NUL, PRN, etc. For these, switching to Plan B is
5079 a net loss, because we lose the character device
5080 attribute returned by GetFileType below (FindFirstFile
5081 doesn't set that bit in the attributes), and the other
5082 fields don't make sense for character devices anyway.
5083 Emacs doesn't really care for non-file entities in the
5084 context of l?stat, so neither do we. */
5086 /* w32err is assigned so one could put a breakpoint here and
5087 examine its value, when GetFileInformationByHandle
5088 fails. */
5089 DWORD w32err = GetLastError ();
5091 switch (w32err)
5093 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5094 errno = ENOENT;
5095 return -1;
5099 /* Test for a symlink before testing for a directory, since
5100 symlinks to directories have the directory bit set, but we
5101 don't want them to appear as directories. */
5102 if (is_a_symlink && !follow_symlinks)
5103 buf->st_mode = S_IFLNK;
5104 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5105 buf->st_mode = S_IFDIR;
5106 else
5108 DWORD ftype = GetFileType (fh);
5110 switch (ftype)
5112 case FILE_TYPE_DISK:
5113 buf->st_mode = S_IFREG;
5114 break;
5115 case FILE_TYPE_PIPE:
5116 buf->st_mode = S_IFIFO;
5117 break;
5118 case FILE_TYPE_CHAR:
5119 case FILE_TYPE_UNKNOWN:
5120 default:
5121 buf->st_mode = S_IFCHR;
5124 /* We produce the fallback owner and group data, based on the
5125 current user that runs Emacs, in the following cases:
5127 . caller didn't request owner and group info
5128 . this is Windows 9X
5129 . getting security by handle failed, and we need to produce
5130 information for the target of a symlink (this is better
5131 than producing a potentially misleading info about the
5132 symlink itself)
5134 If getting security by handle fails, and we don't need to
5135 resolve symlinks, we try getting security by name. */
5136 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5137 get_file_owner_and_group (NULL, buf);
5138 else
5140 psd = get_file_security_desc_by_handle (fh);
5141 if (psd)
5143 get_file_owner_and_group (psd, buf);
5144 LocalFree (psd);
5146 else if (!(is_a_symlink && follow_symlinks))
5148 psd = get_file_security_desc_by_name (name);
5149 get_file_owner_and_group (psd, buf);
5150 xfree (psd);
5152 else
5153 get_file_owner_and_group (NULL, buf);
5155 CloseHandle (fh);
5157 else
5159 no_true_file_attributes:
5160 /* Plan B: Either getting a handle on the file failed, or the
5161 caller explicitly asked us to not bother making this
5162 information more accurate.
5164 Implementation note: In Plan B, we never bother to resolve
5165 symlinks, even if we got here because we tried Plan A and
5166 failed. That's because, even if the caller asked for extra
5167 precision by setting Vw32_get_true_file_attributes to t,
5168 resolving symlinks requires acquiring a file handle to the
5169 symlink, which we already know will fail. And if the user
5170 did not ask for extra precision, resolving symlinks will fly
5171 in the face of that request, since the user then wants the
5172 lightweight version of the code. */
5173 rootdir = (path >= save_name + len - 1
5174 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5176 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5177 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5178 if (IS_DIRECTORY_SEP (r[0])
5179 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5180 r[1] = r[2] = '\0';
5182 /* Note: If NAME is a symlink to the root of a UNC volume
5183 (i.e. "\\SERVER"), we will not detect that here, and we will
5184 return data about the symlink as result of FindFirst below.
5185 This is unfortunate, but that marginal use case does not
5186 justify a call to chase_symlinks which would impose a penalty
5187 on all the other use cases. (We get here for symlinks to
5188 roots of UNC volumes because CreateFile above fails for them,
5189 unlike with symlinks to root directories X:\ of drives.) */
5190 if (is_unc_volume (name))
5192 fattrs = unc_volume_file_attributes (name);
5193 if (fattrs == -1)
5194 return -1;
5196 ctime = atime = wtime = utc_base_ft;
5198 else if (rootdir)
5200 /* Make sure root directories end in a slash. */
5201 if (!IS_DIRECTORY_SEP (name[len-1]))
5202 strcpy (name + len, "\\");
5203 if (GetDriveType (name) < 2)
5205 errno = ENOENT;
5206 return -1;
5209 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5210 ctime = atime = wtime = utc_base_ft;
5212 else
5214 int have_wfd = -1;
5216 /* Make sure non-root directories do NOT end in a slash,
5217 otherwise FindFirstFile might fail. */
5218 if (IS_DIRECTORY_SEP (name[len-1]))
5219 name[len - 1] = 0;
5221 /* (This is hacky, but helps when doing file completions on
5222 network drives.) Optimize by using information available from
5223 active readdir if possible. */
5224 len = strlen (dir_pathname);
5225 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5226 len--;
5227 if (dir_find_handle != INVALID_HANDLE_VALUE
5228 && last_dir_find_data != -1
5229 && !(is_a_symlink && follow_symlinks)
5230 /* The 2 file-name comparisons below support only ASCII
5231 characters, and will lose (compare not equal) when
5232 the file names include non-ASCII characters that are
5233 the same but for the case. However, doing this
5234 properly involves: (a) converting both file names to
5235 UTF-16, (b) lower-casing both names using CharLowerW,
5236 and (c) comparing the results; this would be quite a
5237 bit slower, whereas Plan B is for users who want
5238 lightweight albeit inaccurate version of 'stat'. */
5239 && c_strncasecmp (save_name, dir_pathname, len) == 0
5240 && IS_DIRECTORY_SEP (name[len])
5241 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5243 have_wfd = last_dir_find_data;
5244 /* This was the last entry returned by readdir. */
5245 if (last_dir_find_data == DIR_FIND_DATA_W)
5246 wfd_w = dir_find_data_w;
5247 else
5248 wfd_a = dir_find_data_a;
5250 else
5252 logon_network_drive (name);
5254 if (w32_unicode_filenames)
5256 filename_to_utf16 (name, name_w);
5257 fh = FindFirstFileW (name_w, &wfd_w);
5258 have_wfd = DIR_FIND_DATA_W;
5260 else
5262 filename_to_ansi (name, name_a);
5263 /* If NAME includes characters not representable by
5264 the current ANSI codepage, filename_to_ansi
5265 usually replaces them with a '?'. We don't want
5266 to let FindFirstFileA interpret those as wildcards,
5267 and "succeed", returning us data from some random
5268 file in the same directory. */
5269 if (_mbspbrk (name_a, "?"))
5270 fh = INVALID_HANDLE_VALUE;
5271 else
5272 fh = FindFirstFileA (name_a, &wfd_a);
5273 have_wfd = DIR_FIND_DATA_A;
5275 if (fh == INVALID_HANDLE_VALUE)
5277 errno = ENOENT;
5278 return -1;
5280 FindClose (fh);
5282 /* Note: if NAME is a symlink, the information we get from
5283 FindFirstFile is for the symlink, not its target. */
5284 if (have_wfd == DIR_FIND_DATA_W)
5286 fattrs = wfd_w.dwFileAttributes;
5287 ctime = wfd_w.ftCreationTime;
5288 atime = wfd_w.ftLastAccessTime;
5289 wtime = wfd_w.ftLastWriteTime;
5290 fs_high = wfd_w.nFileSizeHigh;
5291 fs_low = wfd_w.nFileSizeLow;
5293 else
5295 fattrs = wfd_a.dwFileAttributes;
5296 ctime = wfd_a.ftCreationTime;
5297 atime = wfd_a.ftLastAccessTime;
5298 wtime = wfd_a.ftLastWriteTime;
5299 fs_high = wfd_a.nFileSizeHigh;
5300 fs_low = wfd_a.nFileSizeLow;
5302 fake_inode = 0;
5303 nlinks = 1;
5304 serialnum = volume_info.serialnum;
5306 if (is_a_symlink && !follow_symlinks)
5307 buf->st_mode = S_IFLNK;
5308 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5309 buf->st_mode = S_IFDIR;
5310 else
5311 buf->st_mode = S_IFREG;
5313 get_file_owner_and_group (NULL, buf);
5316 buf->st_ino = fake_inode;
5318 buf->st_dev = serialnum;
5319 buf->st_rdev = serialnum;
5321 buf->st_size = fs_high;
5322 buf->st_size <<= 32;
5323 buf->st_size += fs_low;
5324 buf->st_nlink = nlinks;
5326 /* Convert timestamps to Unix format. */
5327 buf->st_mtime = convert_time (wtime);
5328 buf->st_atime = convert_time (atime);
5329 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5330 buf->st_ctime = convert_time (ctime);
5331 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5333 /* determine rwx permissions */
5334 if (is_a_symlink && !follow_symlinks)
5335 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5336 else
5338 if (fattrs & FILE_ATTRIBUTE_READONLY)
5339 permission = S_IREAD;
5340 else
5341 permission = S_IREAD | S_IWRITE;
5343 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5344 permission |= S_IEXEC;
5345 else if (is_exec (name))
5346 permission |= S_IEXEC;
5349 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5351 return 0;
5355 stat (const char * path, struct stat * buf)
5357 return stat_worker (path, buf, 1);
5361 lstat (const char * path, struct stat * buf)
5363 return stat_worker (path, buf, 0);
5367 fstatat (int fd, char const *name, struct stat *st, int flags)
5369 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5370 This is good enough for the current usage in Emacs, but is fragile.
5372 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5373 Gnulib does this and can serve as a model. */
5374 char fullname[MAX_UTF8_PATH];
5376 if (fd != AT_FDCWD)
5378 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5380 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5381 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5382 < 0)
5384 errno = ENAMETOOLONG;
5385 return -1;
5387 name = fullname;
5390 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5393 /* Provide fstat and utime as well as stat for consistent handling of
5394 file timestamps. */
5396 fstat (int desc, struct stat * buf)
5398 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5399 BY_HANDLE_FILE_INFORMATION info;
5400 unsigned __int64 fake_inode;
5401 int permission;
5403 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5405 case FILE_TYPE_DISK:
5406 buf->st_mode = S_IFREG;
5407 if (!GetFileInformationByHandle (fh, &info))
5409 errno = EACCES;
5410 return -1;
5412 break;
5413 case FILE_TYPE_PIPE:
5414 buf->st_mode = S_IFIFO;
5415 goto non_disk;
5416 case FILE_TYPE_CHAR:
5417 case FILE_TYPE_UNKNOWN:
5418 default:
5419 buf->st_mode = S_IFCHR;
5420 non_disk:
5421 memset (&info, 0, sizeof (info));
5422 info.dwFileAttributes = 0;
5423 info.ftCreationTime = utc_base_ft;
5424 info.ftLastAccessTime = utc_base_ft;
5425 info.ftLastWriteTime = utc_base_ft;
5428 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5429 buf->st_mode = S_IFDIR;
5431 buf->st_nlink = info.nNumberOfLinks;
5432 /* Might as well use file index to fake inode values, but this
5433 is not guaranteed to be unique unless we keep a handle open
5434 all the time (even then there are situations where it is
5435 not unique). Reputedly, there are at most 48 bits of info
5436 (on NTFS, presumably less on FAT). */
5437 fake_inode = info.nFileIndexHigh;
5438 fake_inode <<= 32;
5439 fake_inode += info.nFileIndexLow;
5441 /* MSVC defines _ino_t to be short; other libc's might not. */
5442 if (sizeof (buf->st_ino) == 2)
5443 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5444 else
5445 buf->st_ino = fake_inode;
5447 /* If the caller so requested, get the true file owner and group.
5448 Otherwise, consider the file to belong to the current user. */
5449 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5450 get_file_owner_and_group (NULL, buf);
5451 else
5453 PSECURITY_DESCRIPTOR psd = NULL;
5455 psd = get_file_security_desc_by_handle (fh);
5456 if (psd)
5458 get_file_owner_and_group (psd, buf);
5459 LocalFree (psd);
5461 else
5462 get_file_owner_and_group (NULL, buf);
5465 buf->st_dev = info.dwVolumeSerialNumber;
5466 buf->st_rdev = info.dwVolumeSerialNumber;
5468 buf->st_size = info.nFileSizeHigh;
5469 buf->st_size <<= 32;
5470 buf->st_size += info.nFileSizeLow;
5472 /* Convert timestamps to Unix format. */
5473 buf->st_mtime = convert_time (info.ftLastWriteTime);
5474 buf->st_atime = convert_time (info.ftLastAccessTime);
5475 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5476 buf->st_ctime = convert_time (info.ftCreationTime);
5477 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5479 /* determine rwx permissions */
5480 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5481 permission = S_IREAD;
5482 else
5483 permission = S_IREAD | S_IWRITE;
5485 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5486 permission |= S_IEXEC;
5487 else
5489 #if 0 /* no way of knowing the filename */
5490 char * p = strrchr (name, '.');
5491 if (p != NULL &&
5492 (xstrcasecmp (p, ".exe") == 0 ||
5493 xstrcasecmp (p, ".com") == 0 ||
5494 xstrcasecmp (p, ".bat") == 0 ||
5495 xstrcasecmp (p, ".cmd") == 0))
5496 permission |= S_IEXEC;
5497 #endif
5500 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5502 return 0;
5505 /* A version of 'utime' which handles directories as well as
5506 files. */
5509 utime (const char *name, struct utimbuf *times)
5511 struct utimbuf deftime;
5512 HANDLE fh;
5513 FILETIME mtime;
5514 FILETIME atime;
5516 if (times == NULL)
5518 deftime.modtime = deftime.actime = time (NULL);
5519 times = &deftime;
5522 if (w32_unicode_filenames)
5524 wchar_t name_utf16[MAX_PATH];
5526 if (filename_to_utf16 (name, name_utf16) != 0)
5527 return -1; /* errno set by filename_to_utf16 */
5529 /* Need write access to set times. */
5530 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5531 /* If NAME specifies a directory, FILE_SHARE_DELETE
5532 allows other processes to delete files inside it,
5533 while we have the directory open. */
5534 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5535 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5537 else
5539 char name_ansi[MAX_PATH];
5541 if (filename_to_ansi (name, name_ansi) != 0)
5542 return -1; /* errno set by filename_to_ansi */
5544 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5545 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5546 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5548 if (fh != INVALID_HANDLE_VALUE)
5550 convert_from_time_t (times->actime, &atime);
5551 convert_from_time_t (times->modtime, &mtime);
5552 if (!SetFileTime (fh, NULL, &atime, &mtime))
5554 CloseHandle (fh);
5555 errno = EACCES;
5556 return -1;
5558 CloseHandle (fh);
5560 else
5562 DWORD err = GetLastError ();
5564 switch (err)
5566 case ERROR_FILE_NOT_FOUND:
5567 case ERROR_PATH_NOT_FOUND:
5568 case ERROR_INVALID_DRIVE:
5569 case ERROR_BAD_NETPATH:
5570 case ERROR_DEV_NOT_EXIST:
5571 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5572 file name includes ?s, i.e. translation to ANSI failed. */
5573 case ERROR_INVALID_NAME:
5574 errno = ENOENT;
5575 break;
5576 case ERROR_TOO_MANY_OPEN_FILES:
5577 errno = ENFILE;
5578 break;
5579 case ERROR_ACCESS_DENIED:
5580 case ERROR_SHARING_VIOLATION:
5581 errno = EACCES;
5582 break;
5583 default:
5584 errno = EINVAL;
5585 break;
5587 return -1;
5589 return 0;
5593 sys_umask (int mode)
5595 static int current_mask;
5596 int retval, arg = 0;
5598 /* The only bit we really support is the write bit. Files are
5599 always readable on MS-Windows, and the execute bit does not exist
5600 at all. */
5601 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5602 to prevent access by other users on NTFS. */
5603 if ((mode & S_IWRITE) != 0)
5604 arg |= S_IWRITE;
5606 retval = _umask (arg);
5607 /* Merge into the return value the bits they've set the last time,
5608 which msvcrt.dll ignores and never returns. Emacs insists on its
5609 notion of mask being identical to what we return. */
5610 retval |= (current_mask & ~S_IWRITE);
5611 current_mask = mode;
5613 return retval;
5617 /* Symlink-related functions. */
5618 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5619 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5620 #endif
5623 symlink (char const *filename, char const *linkname)
5625 char linkfn[MAX_UTF8_PATH], *tgtfn;
5626 DWORD flags = 0;
5627 int dir_access, filename_ends_in_slash;
5629 /* Diagnostics follows Posix as much as possible. */
5630 if (filename == NULL || linkname == NULL)
5632 errno = EFAULT;
5633 return -1;
5635 if (!*filename)
5637 errno = ENOENT;
5638 return -1;
5640 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5642 errno = ENAMETOOLONG;
5643 return -1;
5646 strcpy (linkfn, map_w32_filename (linkname, NULL));
5647 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5649 errno = EPERM;
5650 return -1;
5653 /* Note: since empty FILENAME was already rejected, we can safely
5654 refer to FILENAME[1]. */
5655 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5657 /* Non-absolute FILENAME is understood as being relative to
5658 LINKNAME's directory. We need to prepend that directory to
5659 FILENAME to get correct results from faccessat below, since
5660 otherwise it will interpret FILENAME relative to the
5661 directory where the Emacs process runs. Note that
5662 make-symbolic-link always makes sure LINKNAME is a fully
5663 expanded file name. */
5664 char tem[MAX_UTF8_PATH];
5665 char *p = linkfn + strlen (linkfn);
5667 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5668 p--;
5669 if (p > linkfn)
5670 strncpy (tem, linkfn, p - linkfn);
5671 strcpy (tem + (p - linkfn), filename);
5672 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5674 else
5675 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5677 /* Since Windows distinguishes between symlinks to directories and
5678 to files, we provide a kludgy feature: if FILENAME doesn't
5679 exist, but ends in a slash, we create a symlink to directory. If
5680 FILENAME exists and is a directory, we always create a symlink to
5681 directory. */
5682 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5683 if (dir_access == 0 || filename_ends_in_slash)
5684 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5686 tgtfn = (char *)map_w32_filename (filename, NULL);
5687 if (filename_ends_in_slash)
5688 tgtfn[strlen (tgtfn) - 1] = '\0';
5690 errno = 0;
5691 if (!create_symbolic_link (linkfn, tgtfn, flags))
5693 /* ENOSYS is set by create_symbolic_link, when it detects that
5694 the OS doesn't support the CreateSymbolicLink API. */
5695 if (errno != ENOSYS)
5697 DWORD w32err = GetLastError ();
5699 switch (w32err)
5701 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5702 TGTFN point to the same file name, go figure. */
5703 case ERROR_SUCCESS:
5704 case ERROR_FILE_EXISTS:
5705 errno = EEXIST;
5706 break;
5707 case ERROR_ACCESS_DENIED:
5708 errno = EACCES;
5709 break;
5710 case ERROR_FILE_NOT_FOUND:
5711 case ERROR_PATH_NOT_FOUND:
5712 case ERROR_BAD_NETPATH:
5713 case ERROR_INVALID_REPARSE_DATA:
5714 errno = ENOENT;
5715 break;
5716 case ERROR_DIRECTORY:
5717 errno = EISDIR;
5718 break;
5719 case ERROR_PRIVILEGE_NOT_HELD:
5720 case ERROR_NOT_ALL_ASSIGNED:
5721 errno = EPERM;
5722 break;
5723 case ERROR_DISK_FULL:
5724 errno = ENOSPC;
5725 break;
5726 default:
5727 errno = EINVAL;
5728 break;
5731 return -1;
5733 return 0;
5736 /* A quick inexpensive test of whether FILENAME identifies a file that
5737 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5738 must already be in the normalized form returned by
5739 map_w32_filename. If the symlink is to a directory, the
5740 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5742 Note: for repeated operations on many files, it is best to test
5743 whether the underlying volume actually supports symlinks, by
5744 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5745 avoid the call to this function if it doesn't. That's because the
5746 call to GetFileAttributes takes a non-negligible time, especially
5747 on non-local or removable filesystems. See stat_worker for an
5748 example of how to do that. */
5749 static int
5750 is_symlink (const char *filename)
5752 DWORD attrs;
5753 wchar_t filename_w[MAX_PATH];
5754 char filename_a[MAX_PATH];
5755 WIN32_FIND_DATAW wfdw;
5756 WIN32_FIND_DATAA wfda;
5757 HANDLE fh;
5758 int attrs_mean_symlink;
5760 if (w32_unicode_filenames)
5762 filename_to_utf16 (filename, filename_w);
5763 attrs = GetFileAttributesW (filename_w);
5765 else
5767 filename_to_ansi (filename, filename_a);
5768 attrs = GetFileAttributesA (filename_a);
5770 if (attrs == -1)
5772 DWORD w32err = GetLastError ();
5774 switch (w32err)
5776 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5777 break;
5778 case ERROR_ACCESS_DENIED:
5779 errno = EACCES;
5780 break;
5781 case ERROR_FILE_NOT_FOUND:
5782 case ERROR_PATH_NOT_FOUND:
5783 default:
5784 errno = ENOENT;
5785 break;
5787 return 0;
5789 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5790 return 0;
5791 logon_network_drive (filename);
5792 if (w32_unicode_filenames)
5794 fh = FindFirstFileW (filename_w, &wfdw);
5795 attrs_mean_symlink =
5796 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5797 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5798 if (attrs_mean_symlink)
5799 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5801 else if (_mbspbrk (filename_a, "?"))
5803 /* filename_to_ansi failed to convert the file name. */
5804 errno = ENOENT;
5805 return 0;
5807 else
5809 fh = FindFirstFileA (filename_a, &wfda);
5810 attrs_mean_symlink =
5811 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5812 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5813 if (attrs_mean_symlink)
5814 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5816 if (fh == INVALID_HANDLE_VALUE)
5817 return 0;
5818 FindClose (fh);
5819 return attrs_mean_symlink;
5822 /* If NAME identifies a symbolic link, copy into BUF the file name of
5823 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5824 null-terminate the target name, even if it fits. Return the number
5825 of bytes copied, or -1 if NAME is not a symlink or any error was
5826 encountered while resolving it. The file name copied into BUF is
5827 encoded in the current ANSI codepage. */
5828 ssize_t
5829 readlink (const char *name, char *buf, size_t buf_size)
5831 const char *path;
5832 TOKEN_PRIVILEGES privs;
5833 int restore_privs = 0;
5834 HANDLE sh;
5835 ssize_t retval;
5836 char resolved[MAX_UTF8_PATH];
5838 if (name == NULL)
5840 errno = EFAULT;
5841 return -1;
5843 if (!*name)
5845 errno = ENOENT;
5846 return -1;
5849 path = map_w32_filename (name, NULL);
5851 if (strlen (path) > MAX_UTF8_PATH)
5853 errno = ENAMETOOLONG;
5854 return -1;
5857 errno = 0;
5858 if (is_windows_9x () == TRUE
5859 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5860 || !is_symlink (path))
5862 if (!errno)
5863 errno = EINVAL; /* not a symlink */
5864 return -1;
5867 /* Done with simple tests, now we're in for some _real_ work. */
5868 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5869 restore_privs = 1;
5870 /* Implementation note: From here and onward, don't return early,
5871 since that will fail to restore the original set of privileges of
5872 the calling thread. */
5874 retval = -1; /* not too optimistic, are we? */
5876 /* Note: In the next call to CreateFile, we use zero as the 2nd
5877 argument because, when the symlink is a hidden/system file,
5878 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5879 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5880 and directory symlinks. */
5881 if (w32_unicode_filenames)
5883 wchar_t path_w[MAX_PATH];
5885 filename_to_utf16 (path, path_w);
5886 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5887 FILE_FLAG_OPEN_REPARSE_POINT
5888 | FILE_FLAG_BACKUP_SEMANTICS,
5889 NULL);
5891 else
5893 char path_a[MAX_PATH];
5895 filename_to_ansi (path, path_a);
5896 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5897 FILE_FLAG_OPEN_REPARSE_POINT
5898 | FILE_FLAG_BACKUP_SEMANTICS,
5899 NULL);
5901 if (sh != INVALID_HANDLE_VALUE)
5903 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5904 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5905 DWORD retbytes;
5907 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5908 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5909 &retbytes, NULL))
5910 errno = EIO;
5911 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5912 errno = EINVAL;
5913 else
5915 /* Copy the link target name, in wide characters, from
5916 reparse_data, then convert it to multibyte encoding in
5917 the current locale's codepage. */
5918 WCHAR *lwname;
5919 size_t lname_size;
5920 USHORT lwname_len =
5921 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5922 WCHAR *lwname_src =
5923 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5924 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5925 size_t size_to_copy = buf_size;
5927 /* According to MSDN, PrintNameLength does not include the
5928 terminating null character. */
5929 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5930 memcpy (lwname, lwname_src, lwname_len);
5931 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5932 filename_from_utf16 (lwname, resolved);
5933 dostounix_filename (resolved);
5934 lname_size = strlen (resolved) + 1;
5935 if (lname_size <= buf_size)
5936 size_to_copy = lname_size;
5937 strncpy (buf, resolved, size_to_copy);
5938 /* Success! */
5939 retval = size_to_copy;
5941 CloseHandle (sh);
5943 else
5945 /* CreateFile failed. */
5946 DWORD w32err2 = GetLastError ();
5948 switch (w32err2)
5950 case ERROR_FILE_NOT_FOUND:
5951 case ERROR_PATH_NOT_FOUND:
5952 errno = ENOENT;
5953 break;
5954 case ERROR_ACCESS_DENIED:
5955 case ERROR_TOO_MANY_OPEN_FILES:
5956 errno = EACCES;
5957 break;
5958 default:
5959 errno = EPERM;
5960 break;
5963 if (restore_privs)
5965 restore_privilege (&privs);
5966 revert_to_self ();
5969 return retval;
5972 ssize_t
5973 readlinkat (int fd, char const *name, char *buffer,
5974 size_t buffer_size)
5976 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5977 as in fstatat. FIXME: Add proper support for readlinkat. */
5978 char fullname[MAX_UTF8_PATH];
5980 if (fd != AT_FDCWD)
5982 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5983 < 0)
5985 errno = ENAMETOOLONG;
5986 return -1;
5988 name = fullname;
5991 return readlink (name, buffer, buffer_size);
5994 /* If FILE is a symlink, return its target (stored in a static
5995 buffer); otherwise return FILE.
5997 This function repeatedly resolves symlinks in the last component of
5998 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5999 until it arrives at a file whose last component is not a symlink,
6000 or some error occurs. It returns the target of the last
6001 successfully resolved symlink in the chain. If it succeeds to
6002 resolve even a single symlink, the value returned is an absolute
6003 file name with backslashes (result of GetFullPathName). By
6004 contrast, if the original FILE is returned, it is unaltered.
6006 Note: This function can set errno even if it succeeds.
6008 Implementation note: we only resolve the last portion ("basename")
6009 of the argument FILE and of each following file in the chain,
6010 disregarding any possible symlinks in its leading directories.
6011 This is because Windows system calls and library functions
6012 transparently resolve symlinks in leading directories and return
6013 correct information, as long as the basename is not a symlink. */
6014 static char *
6015 chase_symlinks (const char *file)
6017 static char target[MAX_UTF8_PATH];
6018 char link[MAX_UTF8_PATH];
6019 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
6020 char target_a[MAX_PATH], link_a[MAX_PATH];
6021 ssize_t res, link_len;
6022 int loop_count = 0;
6024 if (is_windows_9x () == TRUE || !is_symlink (file))
6025 return (char *)file;
6027 if (w32_unicode_filenames)
6029 wchar_t file_w[MAX_PATH];
6031 filename_to_utf16 (file, file_w);
6032 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
6033 return (char *)file;
6034 filename_from_utf16 (link_w, link);
6036 else
6038 char file_a[MAX_PATH];
6040 filename_to_ansi (file, file_a);
6041 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6042 return (char *)file;
6043 filename_from_ansi (link_a, link);
6045 link_len = strlen (link);
6047 target[0] = '\0';
6048 do {
6050 /* Remove trailing slashes, as we want to resolve the last
6051 non-trivial part of the link name. */
6052 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6053 link[link_len--] = '\0';
6055 res = readlink (link, target, MAX_UTF8_PATH);
6056 if (res > 0)
6058 target[res] = '\0';
6059 if (!(IS_DEVICE_SEP (target[1])
6060 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6062 /* Target is relative. Append it to the directory part of
6063 the symlink, then copy the result back to target. */
6064 char *p = link + link_len;
6066 while (p > link && !IS_ANY_SEP (p[-1]))
6067 p--;
6068 strcpy (p, target);
6069 strcpy (target, link);
6071 /* Resolve any "." and ".." to get a fully-qualified file name
6072 in link[] again. */
6073 if (w32_unicode_filenames)
6075 filename_to_utf16 (target, target_w);
6076 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6077 if (link_len > 0)
6078 filename_from_utf16 (link_w, link);
6080 else
6082 filename_to_ansi (target, target_a);
6083 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6084 if (link_len > 0)
6085 filename_from_ansi (link_a, link);
6087 link_len = strlen (link);
6089 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6091 if (loop_count > 100)
6092 errno = ELOOP;
6094 if (target[0] == '\0') /* not a single call to readlink succeeded */
6095 return (char *)file;
6096 return target;
6100 /* Posix ACL emulation. */
6103 acl_valid (acl_t acl)
6105 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6108 char *
6109 acl_to_text (acl_t acl, ssize_t *size)
6111 LPTSTR str_acl;
6112 SECURITY_INFORMATION flags =
6113 OWNER_SECURITY_INFORMATION |
6114 GROUP_SECURITY_INFORMATION |
6115 DACL_SECURITY_INFORMATION;
6116 char *retval = NULL;
6117 ULONG local_size;
6118 int e = errno;
6120 errno = 0;
6122 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6124 errno = e;
6125 /* We don't want to mix heaps, so we duplicate the string in our
6126 heap and free the one allocated by the API. */
6127 retval = xstrdup (str_acl);
6128 if (size)
6129 *size = local_size;
6130 LocalFree (str_acl);
6132 else if (errno != ENOTSUP)
6133 errno = EINVAL;
6135 return retval;
6138 acl_t
6139 acl_from_text (const char *acl_str)
6141 PSECURITY_DESCRIPTOR psd, retval = NULL;
6142 ULONG sd_size;
6143 int e = errno;
6145 errno = 0;
6147 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6149 errno = e;
6150 retval = xmalloc (sd_size);
6151 memcpy (retval, psd, sd_size);
6152 LocalFree (psd);
6154 else if (errno != ENOTSUP)
6155 errno = EINVAL;
6157 return retval;
6161 acl_free (void *ptr)
6163 xfree (ptr);
6164 return 0;
6167 acl_t
6168 acl_get_file (const char *fname, acl_type_t type)
6170 PSECURITY_DESCRIPTOR psd = NULL;
6171 const char *filename;
6173 if (type == ACL_TYPE_ACCESS)
6175 DWORD sd_len, err;
6176 SECURITY_INFORMATION si =
6177 OWNER_SECURITY_INFORMATION |
6178 GROUP_SECURITY_INFORMATION |
6179 DACL_SECURITY_INFORMATION ;
6180 int e = errno;
6182 filename = map_w32_filename (fname, NULL);
6183 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6184 fname = chase_symlinks (filename);
6185 else
6186 fname = filename;
6188 errno = 0;
6189 if (!get_file_security (fname, si, psd, 0, &sd_len)
6190 && errno != ENOTSUP)
6192 err = GetLastError ();
6193 if (err == ERROR_INSUFFICIENT_BUFFER)
6195 psd = xmalloc (sd_len);
6196 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6198 xfree (psd);
6199 errno = EIO;
6200 psd = NULL;
6203 else if (err == ERROR_FILE_NOT_FOUND
6204 || err == ERROR_PATH_NOT_FOUND
6205 /* ERROR_INVALID_NAME is what we get if
6206 w32-unicode-filenames is nil and the file cannot
6207 be encoded in the current ANSI codepage. */
6208 || err == ERROR_INVALID_NAME)
6209 errno = ENOENT;
6210 else
6211 errno = EIO;
6213 else if (!errno)
6214 errno = e;
6216 else if (type != ACL_TYPE_DEFAULT)
6217 errno = EINVAL;
6219 return psd;
6223 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6225 TOKEN_PRIVILEGES old1, old2;
6226 DWORD err;
6227 int st = 0, retval = -1;
6228 SECURITY_INFORMATION flags = 0;
6229 PSID psidOwner, psidGroup;
6230 PACL pacl;
6231 BOOL dflt;
6232 BOOL dacl_present;
6233 int e;
6234 const char *filename;
6236 if (acl_valid (acl) != 0
6237 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6239 errno = EINVAL;
6240 return -1;
6243 if (type == ACL_TYPE_DEFAULT)
6245 errno = ENOSYS;
6246 return -1;
6249 filename = map_w32_filename (fname, NULL);
6250 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6251 fname = chase_symlinks (filename);
6252 else
6253 fname = filename;
6255 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6256 &dflt)
6257 && psidOwner)
6258 flags |= OWNER_SECURITY_INFORMATION;
6259 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6260 &dflt)
6261 && psidGroup)
6262 flags |= GROUP_SECURITY_INFORMATION;
6263 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6264 &pacl, &dflt)
6265 && dacl_present)
6266 flags |= DACL_SECURITY_INFORMATION;
6267 if (!flags)
6268 return 0;
6270 /* According to KB-245153, setting the owner will succeed if either:
6271 (1) the caller is the user who will be the new owner, and has the
6272 SE_TAKE_OWNERSHIP privilege, or
6273 (2) the caller has the SE_RESTORE privilege, in which case she can
6274 set any valid user or group as the owner
6276 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6277 privileges, and disregard any failures in obtaining them. If
6278 these privileges cannot be obtained, and do not already exist in
6279 the calling thread's security token, this function could fail
6280 with EPERM. */
6281 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6282 st++;
6283 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6284 st++;
6286 e = errno;
6287 errno = 0;
6288 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6289 DACL inheritance is involved, but it seems to preserve ownership
6290 better than SetNamedSecurityInfo, which is important e.g., in
6291 copy-file. */
6292 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6294 err = GetLastError ();
6296 if (errno != ENOTSUP)
6297 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6298 psidOwner, psidGroup, pacl, NULL);
6300 else
6301 err = ERROR_SUCCESS;
6302 if (err != ERROR_SUCCESS)
6304 if (errno == ENOTSUP)
6306 else if (err == ERROR_INVALID_OWNER
6307 || err == ERROR_NOT_ALL_ASSIGNED
6308 || err == ERROR_ACCESS_DENIED)
6310 /* Maybe the requested ACL and the one the file already has
6311 are identical, in which case we can silently ignore the
6312 failure. (And no, Windows doesn't.) */
6313 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6315 errno = EPERM;
6316 if (current_acl)
6318 char *acl_from = acl_to_text (current_acl, NULL);
6319 char *acl_to = acl_to_text (acl, NULL);
6321 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6323 retval = 0;
6324 errno = e;
6326 if (acl_from)
6327 acl_free (acl_from);
6328 if (acl_to)
6329 acl_free (acl_to);
6330 acl_free (current_acl);
6333 else if (err == ERROR_FILE_NOT_FOUND
6334 || err == ERROR_PATH_NOT_FOUND
6335 /* ERROR_INVALID_NAME is what we get if
6336 w32-unicode-filenames is nil and the file cannot be
6337 encoded in the current ANSI codepage. */
6338 || err == ERROR_INVALID_NAME)
6339 errno = ENOENT;
6340 else
6341 errno = EACCES;
6343 else
6345 retval = 0;
6346 errno = e;
6349 if (st)
6351 if (st >= 2)
6352 restore_privilege (&old2);
6353 restore_privilege (&old1);
6354 revert_to_self ();
6357 return retval;
6361 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6362 have a fixed max size for file names, so we don't need the kind of
6363 alloc/malloc/realloc dance the gnulib version does. We also don't
6364 support FD-relative symlinks. */
6365 char *
6366 careadlinkat (int fd, char const *filename,
6367 char *buffer, size_t buffer_size,
6368 struct allocator const *alloc,
6369 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6371 char linkname[MAX_UTF8_PATH];
6372 ssize_t link_size;
6374 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6376 if (link_size > 0)
6378 char *retval = buffer;
6380 linkname[link_size++] = '\0';
6381 if (link_size > buffer_size)
6382 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6383 if (retval)
6384 memcpy (retval, linkname, link_size);
6386 return retval;
6388 return NULL;
6392 w32_copy_file (const char *from, const char *to,
6393 int keep_time, int preserve_ownership, int copy_acls)
6395 acl_t acl = NULL;
6396 BOOL copy_result;
6397 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6398 char from_a[MAX_PATH], to_a[MAX_PATH];
6400 /* We ignore preserve_ownership for now. */
6401 preserve_ownership = preserve_ownership;
6403 if (copy_acls)
6405 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6406 if (acl == NULL && acl_errno_valid (errno))
6407 return -2;
6409 if (w32_unicode_filenames)
6411 filename_to_utf16 (from, from_w);
6412 filename_to_utf16 (to, to_w);
6413 copy_result = CopyFileW (from_w, to_w, FALSE);
6415 else
6417 filename_to_ansi (from, from_a);
6418 filename_to_ansi (to, to_a);
6419 copy_result = CopyFileA (from_a, to_a, FALSE);
6421 if (!copy_result)
6423 /* CopyFile doesn't set errno when it fails. By far the most
6424 "popular" reason is that the target is read-only. */
6425 DWORD err = GetLastError ();
6427 switch (err)
6429 case ERROR_FILE_NOT_FOUND:
6430 errno = ENOENT;
6431 break;
6432 case ERROR_ACCESS_DENIED:
6433 errno = EACCES;
6434 break;
6435 case ERROR_ENCRYPTION_FAILED:
6436 errno = EIO;
6437 break;
6438 default:
6439 errno = EPERM;
6440 break;
6443 if (acl)
6444 acl_free (acl);
6445 return -1;
6447 /* CopyFile retains the timestamp by default. However, see
6448 "Community Additions" for CopyFile: it sounds like that is not
6449 entirely true. Testing on Windows XP confirms that modified time
6450 is copied, but creation and last-access times are not.
6451 FIXME? */
6452 else if (!keep_time)
6454 struct timespec now;
6455 DWORD attributes;
6457 if (w32_unicode_filenames)
6459 /* Ensure file is writable while its times are set. */
6460 attributes = GetFileAttributesW (to_w);
6461 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6462 now = current_timespec ();
6463 if (set_file_times (-1, to, now, now))
6465 /* Restore original attributes. */
6466 SetFileAttributesW (to_w, attributes);
6467 if (acl)
6468 acl_free (acl);
6469 return -3;
6471 /* Restore original attributes. */
6472 SetFileAttributesW (to_w, attributes);
6474 else
6476 attributes = GetFileAttributesA (to_a);
6477 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6478 now = current_timespec ();
6479 if (set_file_times (-1, to, now, now))
6481 SetFileAttributesA (to_a, attributes);
6482 if (acl)
6483 acl_free (acl);
6484 return -3;
6486 SetFileAttributesA (to_a, attributes);
6489 if (acl != NULL)
6491 bool fail =
6492 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6493 acl_free (acl);
6494 if (fail && acl_errno_valid (errno))
6495 return -4;
6498 return 0;
6502 /* Support for browsing other processes and their attributes. See
6503 process.c for the Lisp bindings. */
6505 /* Helper wrapper functions. */
6507 static HANDLE WINAPI
6508 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6510 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6512 if (g_b_init_create_toolhelp32_snapshot == 0)
6514 g_b_init_create_toolhelp32_snapshot = 1;
6515 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6516 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6517 "CreateToolhelp32Snapshot");
6519 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6521 return INVALID_HANDLE_VALUE;
6523 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6526 static BOOL WINAPI
6527 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6529 static Process32First_Proc s_pfn_Process32_First = NULL;
6531 if (g_b_init_process32_first == 0)
6533 g_b_init_process32_first = 1;
6534 s_pfn_Process32_First = (Process32First_Proc)
6535 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6536 "Process32First");
6538 if (s_pfn_Process32_First == NULL)
6540 return FALSE;
6542 return (s_pfn_Process32_First (hSnapshot, lppe));
6545 static BOOL WINAPI
6546 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6548 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6550 if (g_b_init_process32_next == 0)
6552 g_b_init_process32_next = 1;
6553 s_pfn_Process32_Next = (Process32Next_Proc)
6554 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6555 "Process32Next");
6557 if (s_pfn_Process32_Next == NULL)
6559 return FALSE;
6561 return (s_pfn_Process32_Next (hSnapshot, lppe));
6564 static BOOL WINAPI
6565 open_thread_token (HANDLE ThreadHandle,
6566 DWORD DesiredAccess,
6567 BOOL OpenAsSelf,
6568 PHANDLE TokenHandle)
6570 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6571 HMODULE hm_advapi32 = NULL;
6572 if (is_windows_9x () == TRUE)
6574 SetLastError (ERROR_NOT_SUPPORTED);
6575 return FALSE;
6577 if (g_b_init_open_thread_token == 0)
6579 g_b_init_open_thread_token = 1;
6580 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6581 s_pfn_Open_Thread_Token =
6582 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6584 if (s_pfn_Open_Thread_Token == NULL)
6586 SetLastError (ERROR_NOT_SUPPORTED);
6587 return FALSE;
6589 return (
6590 s_pfn_Open_Thread_Token (
6591 ThreadHandle,
6592 DesiredAccess,
6593 OpenAsSelf,
6594 TokenHandle)
6598 static BOOL WINAPI
6599 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6601 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6602 HMODULE hm_advapi32 = NULL;
6603 if (is_windows_9x () == TRUE)
6605 return FALSE;
6607 if (g_b_init_impersonate_self == 0)
6609 g_b_init_impersonate_self = 1;
6610 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6611 s_pfn_Impersonate_Self =
6612 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6614 if (s_pfn_Impersonate_Self == NULL)
6616 return FALSE;
6618 return s_pfn_Impersonate_Self (ImpersonationLevel);
6621 static BOOL WINAPI
6622 revert_to_self (void)
6624 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6625 HMODULE hm_advapi32 = NULL;
6626 if (is_windows_9x () == TRUE)
6628 return FALSE;
6630 if (g_b_init_revert_to_self == 0)
6632 g_b_init_revert_to_self = 1;
6633 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6634 s_pfn_Revert_To_Self =
6635 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6637 if (s_pfn_Revert_To_Self == NULL)
6639 return FALSE;
6641 return s_pfn_Revert_To_Self ();
6644 static BOOL WINAPI
6645 get_process_memory_info (HANDLE h_proc,
6646 PPROCESS_MEMORY_COUNTERS mem_counters,
6647 DWORD bufsize)
6649 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6650 HMODULE hm_psapi = NULL;
6651 if (is_windows_9x () == TRUE)
6653 return FALSE;
6655 if (g_b_init_get_process_memory_info == 0)
6657 g_b_init_get_process_memory_info = 1;
6658 hm_psapi = LoadLibrary ("Psapi.dll");
6659 if (hm_psapi)
6660 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6661 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6663 if (s_pfn_Get_Process_Memory_Info == NULL)
6665 return FALSE;
6667 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6670 static BOOL WINAPI
6671 get_process_working_set_size (HANDLE h_proc,
6672 PSIZE_T minrss,
6673 PSIZE_T maxrss)
6675 static GetProcessWorkingSetSize_Proc
6676 s_pfn_Get_Process_Working_Set_Size = NULL;
6678 if (is_windows_9x () == TRUE)
6680 return FALSE;
6682 if (g_b_init_get_process_working_set_size == 0)
6684 g_b_init_get_process_working_set_size = 1;
6685 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6686 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6687 "GetProcessWorkingSetSize");
6689 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6691 return FALSE;
6693 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6696 static BOOL WINAPI
6697 global_memory_status (MEMORYSTATUS *buf)
6699 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6701 if (is_windows_9x () == TRUE)
6703 return FALSE;
6705 if (g_b_init_global_memory_status == 0)
6707 g_b_init_global_memory_status = 1;
6708 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6709 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6710 "GlobalMemoryStatus");
6712 if (s_pfn_Global_Memory_Status == NULL)
6714 return FALSE;
6716 return s_pfn_Global_Memory_Status (buf);
6719 static BOOL WINAPI
6720 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6722 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6724 if (is_windows_9x () == TRUE)
6726 return FALSE;
6728 if (g_b_init_global_memory_status_ex == 0)
6730 g_b_init_global_memory_status_ex = 1;
6731 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6732 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6733 "GlobalMemoryStatusEx");
6735 if (s_pfn_Global_Memory_Status_Ex == NULL)
6737 return FALSE;
6739 return s_pfn_Global_Memory_Status_Ex (buf);
6742 Lisp_Object
6743 list_system_processes (void)
6745 Lisp_Object proclist = Qnil;
6746 HANDLE h_snapshot;
6748 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6750 if (h_snapshot != INVALID_HANDLE_VALUE)
6752 PROCESSENTRY32 proc_entry;
6753 DWORD proc_id;
6754 BOOL res;
6756 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6757 for (res = process32_first (h_snapshot, &proc_entry); res;
6758 res = process32_next (h_snapshot, &proc_entry))
6760 proc_id = proc_entry.th32ProcessID;
6761 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6764 CloseHandle (h_snapshot);
6765 proclist = Fnreverse (proclist);
6768 return proclist;
6771 static int
6772 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6774 TOKEN_PRIVILEGES priv;
6775 DWORD priv_size = sizeof (priv);
6776 DWORD opriv_size = sizeof (*old_priv);
6777 HANDLE h_token = NULL;
6778 HANDLE h_thread = GetCurrentThread ();
6779 int ret_val = 0;
6780 BOOL res;
6782 res = open_thread_token (h_thread,
6783 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6784 FALSE, &h_token);
6785 if (!res && GetLastError () == ERROR_NO_TOKEN)
6787 if (impersonate_self (SecurityImpersonation))
6788 res = open_thread_token (h_thread,
6789 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6790 FALSE, &h_token);
6792 if (res)
6794 priv.PrivilegeCount = 1;
6795 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6796 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6797 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6798 old_priv, &opriv_size)
6799 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6800 ret_val = 1;
6802 if (h_token)
6803 CloseHandle (h_token);
6805 return ret_val;
6808 static int
6809 restore_privilege (TOKEN_PRIVILEGES *priv)
6811 DWORD priv_size = sizeof (*priv);
6812 HANDLE h_token = NULL;
6813 int ret_val = 0;
6815 if (open_thread_token (GetCurrentThread (),
6816 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6817 FALSE, &h_token))
6819 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6820 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6821 ret_val = 1;
6823 if (h_token)
6824 CloseHandle (h_token);
6826 return ret_val;
6829 static Lisp_Object
6830 ltime (ULONGLONG time_100ns)
6832 ULONGLONG time_sec = time_100ns / 10000000;
6833 int subsec = time_100ns % 10000000;
6834 return list4i (time_sec >> 16, time_sec & 0xffff,
6835 subsec / 10, subsec % 10 * 100000);
6838 #define U64_TO_LISP_TIME(time) ltime (time)
6840 static int
6841 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6842 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6843 double *pcpu)
6845 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6846 ULONGLONG tem1, tem2, tem3, tem;
6848 if (!h_proc
6849 || !get_process_times_fn
6850 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6851 &ft_kernel, &ft_user))
6852 return 0;
6854 GetSystemTimeAsFileTime (&ft_current);
6856 FILETIME_TO_U64 (tem1, ft_kernel);
6857 *stime = U64_TO_LISP_TIME (tem1);
6859 FILETIME_TO_U64 (tem2, ft_user);
6860 *utime = U64_TO_LISP_TIME (tem2);
6862 tem3 = tem1 + tem2;
6863 *ttime = U64_TO_LISP_TIME (tem3);
6865 FILETIME_TO_U64 (tem, ft_creation);
6866 /* Process no 4 (System) returns zero creation time. */
6867 if (tem)
6868 tem -= utc_base;
6869 *ctime = U64_TO_LISP_TIME (tem);
6871 if (tem)
6873 FILETIME_TO_U64 (tem3, ft_current);
6874 tem = (tem3 - utc_base) - tem;
6876 *etime = U64_TO_LISP_TIME (tem);
6878 if (tem)
6880 *pcpu = 100.0 * (tem1 + tem2) / tem;
6881 if (*pcpu > 100)
6882 *pcpu = 100.0;
6884 else
6885 *pcpu = 0;
6887 return 1;
6890 Lisp_Object
6891 system_process_attributes (Lisp_Object pid)
6893 Lisp_Object attrs = Qnil;
6894 Lisp_Object cmd_str, decoded_cmd, tem;
6895 HANDLE h_snapshot, h_proc;
6896 DWORD proc_id;
6897 int found_proc = 0;
6898 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6899 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6900 DWORD glength = sizeof (gname);
6901 HANDLE token = NULL;
6902 SID_NAME_USE user_type;
6903 unsigned char *buf = NULL;
6904 DWORD blen = 0;
6905 TOKEN_USER user_token;
6906 TOKEN_PRIMARY_GROUP group_token;
6907 unsigned euid;
6908 unsigned egid;
6909 PROCESS_MEMORY_COUNTERS mem;
6910 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6911 SIZE_T minrss, maxrss;
6912 MEMORYSTATUS memst;
6913 MEMORY_STATUS_EX memstex;
6914 double totphys = 0.0;
6915 Lisp_Object ctime, stime, utime, etime, ttime;
6916 double pcpu;
6917 BOOL result = FALSE;
6919 CHECK_NUMBER_OR_FLOAT (pid);
6920 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6922 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6924 if (h_snapshot != INVALID_HANDLE_VALUE)
6926 PROCESSENTRY32 pe;
6927 BOOL res;
6929 pe.dwSize = sizeof (PROCESSENTRY32);
6930 for (res = process32_first (h_snapshot, &pe); res;
6931 res = process32_next (h_snapshot, &pe))
6933 if (proc_id == pe.th32ProcessID)
6935 if (proc_id == 0)
6936 decoded_cmd = build_string ("Idle");
6937 else
6939 /* Decode the command name from locale-specific
6940 encoding. */
6941 cmd_str = build_unibyte_string (pe.szExeFile);
6943 decoded_cmd =
6944 code_convert_string_norecord (cmd_str,
6945 Vlocale_coding_system, 0);
6947 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6948 attrs = Fcons (Fcons (Qppid,
6949 make_fixnum_or_float (pe.th32ParentProcessID)),
6950 attrs);
6951 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6952 attrs);
6953 attrs = Fcons (Fcons (Qthcount,
6954 make_fixnum_or_float (pe.cntThreads)),
6955 attrs);
6956 found_proc = 1;
6957 break;
6961 CloseHandle (h_snapshot);
6964 if (!found_proc)
6965 return Qnil;
6967 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6968 FALSE, proc_id);
6969 /* If we were denied a handle to the process, try again after
6970 enabling the SeDebugPrivilege in our process. */
6971 if (!h_proc)
6973 TOKEN_PRIVILEGES priv_current;
6975 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6977 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6978 FALSE, proc_id);
6979 restore_privilege (&priv_current);
6980 revert_to_self ();
6983 if (h_proc)
6985 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6986 if (result)
6988 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6989 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6991 buf = xmalloc (blen);
6992 result = get_token_information (token, TokenUser,
6993 (LPVOID)buf, blen, &needed);
6994 if (result)
6996 memcpy (&user_token, buf, sizeof (user_token));
6997 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6999 euid = get_rid (user_token.User.Sid);
7000 result = lookup_account_sid (NULL, user_token.User.Sid,
7001 uname, &ulength,
7002 domain, &dlength,
7003 &user_type);
7004 if (result)
7005 w32_add_to_cache (user_token.User.Sid, euid, uname);
7006 else
7008 strcpy (uname, "unknown");
7009 result = TRUE;
7012 ulength = strlen (uname);
7016 if (result)
7018 /* Determine a reasonable euid and gid values. */
7019 if (xstrcasecmp ("administrator", uname) == 0)
7021 euid = 500; /* well-known Administrator uid */
7022 egid = 513; /* well-known None gid */
7024 else
7026 /* Get group id and name. */
7027 result = get_token_information (token, TokenPrimaryGroup,
7028 (LPVOID)buf, blen, &needed);
7029 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
7031 buf = xrealloc (buf, blen = needed);
7032 result = get_token_information (token, TokenPrimaryGroup,
7033 (LPVOID)buf, blen, &needed);
7035 if (result)
7037 memcpy (&group_token, buf, sizeof (group_token));
7038 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7040 egid = get_rid (group_token.PrimaryGroup);
7041 dlength = sizeof (domain);
7042 result =
7043 lookup_account_sid (NULL, group_token.PrimaryGroup,
7044 gname, &glength, NULL, &dlength,
7045 &user_type);
7046 if (result)
7047 w32_add_to_cache (group_token.PrimaryGroup,
7048 egid, gname);
7049 else
7051 strcpy (gname, "None");
7052 result = TRUE;
7055 glength = strlen (gname);
7059 xfree (buf);
7061 if (!result)
7063 if (!is_windows_9x ())
7065 /* We couldn't open the process token, presumably because of
7066 insufficient access rights. Assume this process is run
7067 by the system. */
7068 strcpy (uname, "SYSTEM");
7069 strcpy (gname, "None");
7070 euid = 18; /* SYSTEM */
7071 egid = 513; /* None */
7072 glength = strlen (gname);
7073 ulength = strlen (uname);
7075 /* If we are running under Windows 9X, where security calls are
7076 not supported, we assume all processes are run by the current
7077 user. */
7078 else if (GetUserName (uname, &ulength))
7080 if (xstrcasecmp ("administrator", uname) == 0)
7081 euid = 0;
7082 else
7083 euid = 123;
7084 egid = euid;
7085 strcpy (gname, "None");
7086 glength = strlen (gname);
7087 ulength = strlen (uname);
7089 else
7091 euid = 123;
7092 egid = 123;
7093 strcpy (uname, "administrator");
7094 ulength = strlen (uname);
7095 strcpy (gname, "None");
7096 glength = strlen (gname);
7098 if (token)
7099 CloseHandle (token);
7102 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7103 tem = make_unibyte_string (uname, ulength);
7104 attrs = Fcons (Fcons (Quser,
7105 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7106 attrs);
7107 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7108 tem = make_unibyte_string (gname, glength);
7109 attrs = Fcons (Fcons (Qgroup,
7110 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7111 attrs);
7113 if (global_memory_status_ex (&memstex))
7114 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7115 totphys = memstex.ullTotalPhys / 1024.0;
7116 #else
7117 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7118 double, so we need to do this for it... */
7120 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7121 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7122 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7124 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7126 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7127 else if (global_memory_status (&memst))
7128 totphys = memst.dwTotalPhys / 1024.0;
7130 if (h_proc
7131 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7132 sizeof (mem_ex)))
7134 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7136 attrs = Fcons (Fcons (Qmajflt,
7137 make_fixnum_or_float (mem_ex.PageFaultCount)),
7138 attrs);
7139 attrs = Fcons (Fcons (Qvsize,
7140 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7141 attrs);
7142 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7143 if (totphys)
7144 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7146 else if (h_proc
7147 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7149 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7151 attrs = Fcons (Fcons (Qmajflt,
7152 make_fixnum_or_float (mem.PageFaultCount)),
7153 attrs);
7154 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7155 if (totphys)
7156 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7158 else if (h_proc
7159 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7161 DWORD rss = maxrss / 1024;
7163 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7164 if (totphys)
7165 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7168 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7170 attrs = Fcons (Fcons (Qutime, utime), attrs);
7171 attrs = Fcons (Fcons (Qstime, stime), attrs);
7172 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7173 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7174 attrs = Fcons (Fcons (Qetime, etime), attrs);
7175 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7178 /* FIXME: Retrieve command line by walking the PEB of the process. */
7180 if (h_proc)
7181 CloseHandle (h_proc);
7182 return attrs;
7186 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7187 unsigned long long *totalswap, unsigned long long *freeswap)
7189 MEMORYSTATUS memst;
7190 MEMORY_STATUS_EX memstex;
7192 /* Use GlobalMemoryStatusEx if available, as it can report more than
7193 2GB of memory. */
7194 if (global_memory_status_ex (&memstex))
7196 *totalram = memstex.ullTotalPhys;
7197 *freeram = memstex.ullAvailPhys;
7198 *totalswap = memstex.ullTotalPageFile;
7199 *freeswap = memstex.ullAvailPageFile;
7200 return 0;
7202 else if (global_memory_status (&memst))
7204 *totalram = memst.dwTotalPhys;
7205 *freeram = memst.dwAvailPhys;
7206 *totalswap = memst.dwTotalPageFile;
7207 *freeswap = memst.dwAvailPageFile;
7208 return 0;
7210 else
7211 return -1;
7215 /* Wrappers for winsock functions to map between our file descriptors
7216 and winsock's handles; also set h_errno for convenience.
7218 To allow Emacs to run on systems which don't have winsock support
7219 installed, we dynamically link to winsock on startup if present, and
7220 otherwise provide the minimum necessary functionality
7221 (eg. gethostname). */
7223 /* function pointers for relevant socket functions */
7224 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7225 void (PASCAL *pfn_WSASetLastError) (int iError);
7226 int (PASCAL *pfn_WSAGetLastError) (void);
7227 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7228 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7229 WSANETWORKEVENTS *NetworkEvents);
7231 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7232 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7233 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7234 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7235 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7236 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7237 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7238 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7239 int (PASCAL *pfn_closesocket) (SOCKET s);
7240 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7241 int (PASCAL *pfn_WSACleanup) (void);
7243 u_short (PASCAL *pfn_htons) (u_short hostshort);
7244 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7245 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7246 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7247 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7248 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7249 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7250 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7251 const char * optval, int optlen);
7252 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7253 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7254 int * namelen);
7255 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7256 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7257 struct sockaddr * from, int * fromlen);
7258 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7259 const struct sockaddr * to, int tolen);
7261 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7262 const struct addrinfo *, struct addrinfo **);
7263 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7265 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7266 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7267 #ifndef HANDLE_FLAG_INHERIT
7268 #define HANDLE_FLAG_INHERIT 1
7269 #endif
7271 HANDLE winsock_lib;
7272 static int winsock_inuse;
7274 BOOL term_winsock (void);
7276 BOOL
7277 term_winsock (void)
7279 if (winsock_lib != NULL && winsock_inuse == 0)
7281 release_listen_threads ();
7282 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7283 after WSAStartup returns successfully, but it seems reasonable
7284 to allow unloading winsock anyway in that case. */
7285 if (pfn_WSACleanup () == 0 ||
7286 pfn_WSAGetLastError () == WSAENETDOWN)
7288 if (FreeLibrary (winsock_lib))
7289 winsock_lib = NULL;
7290 return TRUE;
7293 return FALSE;
7296 BOOL
7297 init_winsock (int load_now)
7299 WSADATA winsockData;
7301 if (winsock_lib != NULL)
7302 return TRUE;
7304 pfn_SetHandleInformation
7305 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7306 "SetHandleInformation");
7308 winsock_lib = LoadLibrary ("Ws2_32.dll");
7310 if (winsock_lib != NULL)
7312 /* dynamically link to socket functions */
7314 #define LOAD_PROC(fn) \
7315 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7316 goto fail;
7318 LOAD_PROC (WSAStartup);
7319 LOAD_PROC (WSASetLastError);
7320 LOAD_PROC (WSAGetLastError);
7321 LOAD_PROC (WSAEventSelect);
7322 LOAD_PROC (WSAEnumNetworkEvents);
7323 LOAD_PROC (WSACreateEvent);
7324 LOAD_PROC (WSACloseEvent);
7325 LOAD_PROC (socket);
7326 LOAD_PROC (bind);
7327 LOAD_PROC (connect);
7328 LOAD_PROC (ioctlsocket);
7329 LOAD_PROC (recv);
7330 LOAD_PROC (send);
7331 LOAD_PROC (closesocket);
7332 LOAD_PROC (shutdown);
7333 LOAD_PROC (htons);
7334 LOAD_PROC (ntohs);
7335 LOAD_PROC (inet_addr);
7336 LOAD_PROC (gethostname);
7337 LOAD_PROC (gethostbyname);
7338 LOAD_PROC (getservbyname);
7339 LOAD_PROC (getpeername);
7340 LOAD_PROC (WSACleanup);
7341 LOAD_PROC (setsockopt);
7342 LOAD_PROC (listen);
7343 LOAD_PROC (getsockname);
7344 LOAD_PROC (accept);
7345 LOAD_PROC (recvfrom);
7346 LOAD_PROC (sendto);
7347 #undef LOAD_PROC
7349 /* Try loading functions not available before XP. */
7350 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7351 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7352 /* Paranoia: these two functions should go together, so if one
7353 is absent, we cannot use the other. */
7354 if (pfn_getaddrinfo == NULL)
7355 pfn_freeaddrinfo = NULL;
7356 else if (pfn_freeaddrinfo == NULL)
7357 pfn_getaddrinfo = NULL;
7359 /* specify version 1.1 of winsock */
7360 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7362 if (winsockData.wVersion != 0x101)
7363 goto fail;
7365 if (!load_now)
7367 /* Report that winsock exists and is usable, but leave
7368 socket functions disabled. I am assuming that calling
7369 WSAStartup does not require any network interaction,
7370 and in particular does not cause or require a dial-up
7371 connection to be established. */
7373 pfn_WSACleanup ();
7374 FreeLibrary (winsock_lib);
7375 winsock_lib = NULL;
7377 winsock_inuse = 0;
7378 return TRUE;
7381 fail:
7382 FreeLibrary (winsock_lib);
7383 winsock_lib = NULL;
7386 return FALSE;
7390 int h_errno = 0;
7392 /* Function to map winsock error codes to errno codes for those errno
7393 code defined in errno.h (errno values not defined by errno.h are
7394 already in nt/inc/sys/socket.h). */
7395 static void
7396 set_errno (void)
7398 int wsa_err;
7400 h_errno = 0;
7401 if (winsock_lib == NULL)
7402 wsa_err = EINVAL;
7403 else
7404 wsa_err = pfn_WSAGetLastError ();
7406 switch (wsa_err)
7408 case WSAEACCES: errno = EACCES; break;
7409 case WSAEBADF: errno = EBADF; break;
7410 case WSAEFAULT: errno = EFAULT; break;
7411 case WSAEINTR: errno = EINTR; break;
7412 case WSAEINVAL: errno = EINVAL; break;
7413 case WSAEMFILE: errno = EMFILE; break;
7414 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7415 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7416 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7417 case WSAENOTCONN: errno = ENOTCONN; break;
7418 default: errno = wsa_err; break;
7422 static void
7423 check_errno (void)
7425 h_errno = 0;
7426 if (winsock_lib != NULL)
7427 pfn_WSASetLastError (0);
7430 /* Extend strerror to handle the winsock-specific error codes. */
7431 struct {
7432 int errnum;
7433 const char * msg;
7434 } _wsa_errlist[] = {
7435 {WSAEINTR , "Interrupted function call"},
7436 {WSAEBADF , "Bad file descriptor"},
7437 {WSAEACCES , "Permission denied"},
7438 {WSAEFAULT , "Bad address"},
7439 {WSAEINVAL , "Invalid argument"},
7440 {WSAEMFILE , "Too many open files"},
7442 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7443 {WSAEINPROGRESS , "Operation now in progress"},
7444 {WSAEALREADY , "Operation already in progress"},
7445 {WSAENOTSOCK , "Socket operation on non-socket"},
7446 {WSAEDESTADDRREQ , "Destination address required"},
7447 {WSAEMSGSIZE , "Message too long"},
7448 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7449 {WSAENOPROTOOPT , "Bad protocol option"},
7450 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7451 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7452 {WSAEOPNOTSUPP , "Operation not supported"},
7453 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7454 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7455 {WSAEADDRINUSE , "Address already in use"},
7456 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7457 {WSAENETDOWN , "Network is down"},
7458 {WSAENETUNREACH , "Network is unreachable"},
7459 {WSAENETRESET , "Network dropped connection on reset"},
7460 {WSAECONNABORTED , "Software caused connection abort"},
7461 {WSAECONNRESET , "Connection reset by peer"},
7462 {WSAENOBUFS , "No buffer space available"},
7463 {WSAEISCONN , "Socket is already connected"},
7464 {WSAENOTCONN , "Socket is not connected"},
7465 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7466 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7467 {WSAETIMEDOUT , "Connection timed out"},
7468 {WSAECONNREFUSED , "Connection refused"},
7469 {WSAELOOP , "Network loop"}, /* not sure */
7470 {WSAENAMETOOLONG , "Name is too long"},
7471 {WSAEHOSTDOWN , "Host is down"},
7472 {WSAEHOSTUNREACH , "No route to host"},
7473 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7474 {WSAEPROCLIM , "Too many processes"},
7475 {WSAEUSERS , "Too many users"}, /* not sure */
7476 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7477 {WSAESTALE , "Data is stale"}, /* not sure */
7478 {WSAEREMOTE , "Remote error"}, /* not sure */
7480 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7481 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7482 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7483 {WSAEDISCON , "Graceful shutdown in progress"},
7484 #ifdef WSAENOMORE
7485 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7486 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7487 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7488 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7489 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7490 {WSASYSCALLFAILURE , "System call failure"},
7491 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7492 {WSATYPE_NOT_FOUND , "Class type not found"},
7493 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7494 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7495 {WSAEREFUSED , "Operation refused"}, /* not sure */
7496 #endif
7498 {WSAHOST_NOT_FOUND , "Host not found"},
7499 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7500 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7501 {WSANO_DATA , "Valid name, no data record of requested type"},
7503 {-1, NULL}
7506 char *
7507 sys_strerror (int error_no)
7509 int i;
7510 static char unknown_msg[40];
7512 if (error_no >= 0 && error_no < sys_nerr)
7513 return sys_errlist[error_no];
7515 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7516 if (_wsa_errlist[i].errnum == error_no)
7517 return (char *)_wsa_errlist[i].msg;
7519 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7520 return unknown_msg;
7523 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7524 but I believe the method of keeping the socket handle separate (and
7525 insuring it is not inheritable) is the correct one. */
7527 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7529 static int socket_to_fd (SOCKET s);
7532 sys_socket (int af, int type, int protocol)
7534 SOCKET s;
7536 if (winsock_lib == NULL)
7538 errno = ENETDOWN;
7539 return -1;
7542 check_errno ();
7544 /* call the real socket function */
7545 s = pfn_socket (af, type, protocol);
7547 if (s != INVALID_SOCKET)
7548 return socket_to_fd (s);
7550 set_errno ();
7551 return -1;
7554 /* Convert a SOCKET to a file descriptor. */
7555 static int
7556 socket_to_fd (SOCKET s)
7558 int fd;
7559 child_process * cp;
7561 /* Although under NT 3.5 _open_osfhandle will accept a socket
7562 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7563 that does not work under NT 3.1. However, we can get the same
7564 effect by using a backdoor function to replace an existing
7565 descriptor handle with the one we want. */
7567 /* allocate a file descriptor (with appropriate flags) */
7568 fd = _open ("NUL:", _O_RDWR);
7569 if (fd >= 0)
7571 /* Make a non-inheritable copy of the socket handle. Note
7572 that it is possible that sockets aren't actually kernel
7573 handles, which appears to be the case on Windows 9x when
7574 the MS Proxy winsock client is installed. */
7576 /* Apparently there is a bug in NT 3.51 with some service
7577 packs, which prevents using DuplicateHandle to make a
7578 socket handle non-inheritable (causes WSACleanup to
7579 hang). The work-around is to use SetHandleInformation
7580 instead if it is available and implemented. */
7581 if (pfn_SetHandleInformation)
7583 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7585 else
7587 HANDLE parent = GetCurrentProcess ();
7588 HANDLE new_s = INVALID_HANDLE_VALUE;
7590 if (DuplicateHandle (parent,
7591 (HANDLE) s,
7592 parent,
7593 &new_s,
7595 FALSE,
7596 DUPLICATE_SAME_ACCESS))
7598 /* It is possible that DuplicateHandle succeeds even
7599 though the socket wasn't really a kernel handle,
7600 because a real handle has the same value. So
7601 test whether the new handle really is a socket. */
7602 unsigned long nonblocking = 0;
7603 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7605 pfn_closesocket (s);
7606 s = (SOCKET) new_s;
7608 else
7610 CloseHandle (new_s);
7615 eassert (fd < MAXDESC);
7616 fd_info[fd].hnd = (HANDLE) s;
7618 /* set our own internal flags */
7619 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7621 cp = new_child ();
7622 if (cp)
7624 cp->fd = fd;
7625 cp->status = STATUS_READ_ACKNOWLEDGED;
7627 /* attach child_process to fd_info */
7628 if (fd_info[ fd ].cp != NULL)
7630 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7631 emacs_abort ();
7634 fd_info[ fd ].cp = cp;
7636 /* success! */
7637 winsock_inuse++; /* count open sockets */
7638 return fd;
7641 /* clean up */
7642 _close (fd);
7644 else
7645 pfn_closesocket (s);
7646 errno = EMFILE;
7647 return -1;
7651 sys_bind (int s, const struct sockaddr * addr, int namelen)
7653 if (winsock_lib == NULL)
7655 errno = ENOTSOCK;
7656 return SOCKET_ERROR;
7659 check_errno ();
7660 if (fd_info[s].flags & FILE_SOCKET)
7662 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7663 if (rc == SOCKET_ERROR)
7664 set_errno ();
7665 return rc;
7667 errno = ENOTSOCK;
7668 return SOCKET_ERROR;
7672 sys_connect (int s, const struct sockaddr * name, int namelen)
7674 if (winsock_lib == NULL)
7676 errno = ENOTSOCK;
7677 return SOCKET_ERROR;
7680 check_errno ();
7681 if (fd_info[s].flags & FILE_SOCKET)
7683 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7684 if (rc == SOCKET_ERROR)
7686 set_errno ();
7687 /* If this is a non-blocking 'connect', set the bit in flags
7688 that will tell reader_thread to wait for connection
7689 before trying to read. */
7690 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7692 errno = EINPROGRESS; /* that's what process.c expects */
7693 fd_info[s].flags |= FILE_CONNECT;
7696 return rc;
7698 errno = ENOTSOCK;
7699 return SOCKET_ERROR;
7702 u_short
7703 sys_htons (u_short hostshort)
7705 return (winsock_lib != NULL) ?
7706 pfn_htons (hostshort) : hostshort;
7709 u_short
7710 sys_ntohs (u_short netshort)
7712 return (winsock_lib != NULL) ?
7713 pfn_ntohs (netshort) : netshort;
7716 unsigned long
7717 sys_inet_addr (const char * cp)
7719 return (winsock_lib != NULL) ?
7720 pfn_inet_addr (cp) : INADDR_NONE;
7724 sys_gethostname (char * name, int namelen)
7726 if (winsock_lib != NULL)
7728 int retval;
7730 check_errno ();
7731 retval = pfn_gethostname (name, namelen);
7732 if (retval == SOCKET_ERROR)
7733 set_errno ();
7734 return retval;
7737 if (namelen > MAX_COMPUTERNAME_LENGTH)
7738 return !GetComputerName (name, (DWORD *)&namelen);
7740 errno = EFAULT;
7741 return SOCKET_ERROR;
7744 struct hostent *
7745 sys_gethostbyname (const char * name)
7747 struct hostent * host;
7748 int h_err = h_errno;
7750 if (winsock_lib == NULL)
7752 h_errno = NO_RECOVERY;
7753 errno = ENETDOWN;
7754 return NULL;
7757 check_errno ();
7758 host = pfn_gethostbyname (name);
7759 if (!host)
7761 set_errno ();
7762 h_errno = errno;
7764 else
7765 h_errno = h_err;
7766 return host;
7769 struct servent *
7770 sys_getservbyname (const char * name, const char * proto)
7772 struct servent * serv;
7774 if (winsock_lib == NULL)
7776 errno = ENETDOWN;
7777 return NULL;
7780 check_errno ();
7781 serv = pfn_getservbyname (name, proto);
7782 if (!serv)
7783 set_errno ();
7784 return serv;
7788 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7790 if (winsock_lib == NULL)
7792 errno = ENETDOWN;
7793 return SOCKET_ERROR;
7796 check_errno ();
7797 if (fd_info[s].flags & FILE_SOCKET)
7799 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7800 if (rc == SOCKET_ERROR)
7801 set_errno ();
7802 return rc;
7804 errno = ENOTSOCK;
7805 return SOCKET_ERROR;
7809 sys_getaddrinfo (const char *node, const char *service,
7810 const struct addrinfo *hints, struct addrinfo **res)
7812 int rc;
7814 if (winsock_lib == NULL)
7816 errno = ENETDOWN;
7817 return SOCKET_ERROR;
7820 check_errno ();
7821 if (pfn_getaddrinfo)
7822 rc = pfn_getaddrinfo (node, service, hints, res);
7823 else
7825 int port = 0;
7826 struct hostent *host_info;
7827 struct gai_storage {
7828 struct addrinfo addrinfo;
7829 struct sockaddr_in sockaddr_in;
7830 } *gai_storage;
7832 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7833 if (hints && hints->ai_flags != 0)
7834 return WSAEINVAL;
7835 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7836 if (!node)
7837 return WSAHOST_NOT_FOUND;
7839 if (service)
7841 const char *protocol =
7842 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7843 struct servent *srv = sys_getservbyname (service, protocol);
7845 if (srv)
7846 port = srv->s_port;
7847 else if (*service >= '0' && *service <= '9')
7849 char *endp;
7851 port = strtoul (service, &endp, 10);
7852 if (*endp || port > 65536)
7853 return WSAHOST_NOT_FOUND;
7854 port = sys_htons ((unsigned short) port);
7856 else
7857 return WSAHOST_NOT_FOUND;
7860 gai_storage = xzalloc (sizeof *gai_storage);
7861 gai_storage->sockaddr_in.sin_port = port;
7862 host_info = sys_gethostbyname (node);
7863 if (host_info)
7865 memcpy (&gai_storage->sockaddr_in.sin_addr,
7866 host_info->h_addr, host_info->h_length);
7867 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7869 else
7871 /* Attempt to interpret host as numeric inet address. */
7872 unsigned long numeric_addr = sys_inet_addr (node);
7874 if (numeric_addr == -1)
7876 free (gai_storage);
7877 return WSAHOST_NOT_FOUND;
7880 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7881 sizeof (gai_storage->sockaddr_in.sin_addr));
7882 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7885 gai_storage->addrinfo.ai_addr =
7886 (struct sockaddr *)&gai_storage->sockaddr_in;
7887 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7888 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7889 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7890 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7891 gai_storage->addrinfo.ai_next = NULL;
7893 *res = &gai_storage->addrinfo;
7894 rc = 0;
7897 return rc;
7900 void
7901 sys_freeaddrinfo (struct addrinfo *ai)
7903 if (winsock_lib == NULL)
7905 errno = ENETDOWN;
7906 return;
7909 check_errno ();
7910 if (pfn_freeaddrinfo)
7911 pfn_freeaddrinfo (ai);
7912 else
7914 eassert (ai->ai_next == NULL);
7915 xfree (ai);
7920 sys_shutdown (int s, int how)
7922 if (winsock_lib == NULL)
7924 errno = ENETDOWN;
7925 return SOCKET_ERROR;
7928 check_errno ();
7929 if (fd_info[s].flags & FILE_SOCKET)
7931 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7932 if (rc == SOCKET_ERROR)
7933 set_errno ();
7934 return rc;
7936 errno = ENOTSOCK;
7937 return SOCKET_ERROR;
7941 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7943 if (winsock_lib == NULL)
7945 errno = ENETDOWN;
7946 return SOCKET_ERROR;
7949 check_errno ();
7950 if (fd_info[s].flags & FILE_SOCKET)
7952 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7953 (const char *)optval, optlen);
7954 if (rc == SOCKET_ERROR)
7955 set_errno ();
7956 return rc;
7958 errno = ENOTSOCK;
7959 return SOCKET_ERROR;
7963 sys_listen (int s, int backlog)
7965 if (winsock_lib == NULL)
7967 errno = ENETDOWN;
7968 return SOCKET_ERROR;
7971 check_errno ();
7972 if (fd_info[s].flags & FILE_SOCKET)
7974 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7975 if (rc == SOCKET_ERROR)
7976 set_errno ();
7977 else
7978 fd_info[s].flags |= FILE_LISTEN;
7979 return rc;
7981 errno = ENOTSOCK;
7982 return SOCKET_ERROR;
7986 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7988 if (winsock_lib == NULL)
7990 errno = ENETDOWN;
7991 return SOCKET_ERROR;
7994 check_errno ();
7995 if (fd_info[s].flags & FILE_SOCKET)
7997 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7998 if (rc == SOCKET_ERROR)
7999 set_errno ();
8000 return rc;
8002 errno = ENOTSOCK;
8003 return SOCKET_ERROR;
8007 sys_accept (int s, struct sockaddr * addr, int * addrlen)
8009 if (winsock_lib == NULL)
8011 errno = ENETDOWN;
8012 return -1;
8015 check_errno ();
8016 if (fd_info[s].flags & FILE_LISTEN)
8018 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
8019 int fd = -1;
8020 if (t == INVALID_SOCKET)
8021 set_errno ();
8022 else
8023 fd = socket_to_fd (t);
8025 if (fd >= 0)
8027 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
8028 ResetEvent (fd_info[s].cp->char_avail);
8030 return fd;
8032 errno = ENOTSOCK;
8033 return -1;
8037 sys_recvfrom (int s, char * buf, int len, int flags,
8038 struct sockaddr * from, int * fromlen)
8040 if (winsock_lib == NULL)
8042 errno = ENETDOWN;
8043 return SOCKET_ERROR;
8046 check_errno ();
8047 if (fd_info[s].flags & FILE_SOCKET)
8049 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8050 if (rc == SOCKET_ERROR)
8051 set_errno ();
8052 return rc;
8054 errno = ENOTSOCK;
8055 return SOCKET_ERROR;
8059 sys_sendto (int s, const char * buf, int len, int flags,
8060 const struct sockaddr * to, int tolen)
8062 if (winsock_lib == NULL)
8064 errno = ENETDOWN;
8065 return SOCKET_ERROR;
8068 check_errno ();
8069 if (fd_info[s].flags & FILE_SOCKET)
8071 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8072 if (rc == SOCKET_ERROR)
8073 set_errno ();
8074 return rc;
8076 errno = ENOTSOCK;
8077 return SOCKET_ERROR;
8080 /* Windows does not have an fcntl function. Provide an implementation
8081 good enough for Emacs. */
8083 fcntl (int s, int cmd, int options)
8085 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8086 invoked in a context where fd1 is closed and all descriptors less
8087 than fd1 are open, so sys_dup is an adequate implementation. */
8088 if (cmd == F_DUPFD_CLOEXEC)
8089 return sys_dup (s);
8091 check_errno ();
8092 if (fd_info[s].flags & FILE_SOCKET)
8094 if (winsock_lib == NULL)
8096 errno = ENETDOWN;
8097 return -1;
8100 if (cmd == F_SETFL && options == O_NONBLOCK)
8102 unsigned long nblock = 1;
8103 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8104 if (rc == SOCKET_ERROR)
8105 set_errno ();
8106 /* Keep track of the fact that we set this to non-blocking. */
8107 fd_info[s].flags |= FILE_NDELAY;
8108 return rc;
8110 else
8112 errno = EINVAL;
8113 return SOCKET_ERROR;
8116 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8117 == (FILE_PIPE | FILE_WRITE))
8119 /* Force our writes to pipes be non-blocking. */
8120 if (cmd == F_SETFL && options == O_NONBLOCK)
8122 HANDLE h = (HANDLE)_get_osfhandle (s);
8123 DWORD pipe_mode = PIPE_NOWAIT;
8125 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8127 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8128 return SOCKET_ERROR;
8130 fd_info[s].flags |= FILE_NDELAY;
8131 return 0;
8133 else
8135 errno = EINVAL;
8136 return SOCKET_ERROR;
8139 errno = ENOTSOCK;
8140 return SOCKET_ERROR;
8144 /* Shadow main io functions: we need to handle pipes and sockets more
8145 intelligently. */
8148 sys_close (int fd)
8150 int rc;
8152 if (fd < 0)
8154 errno = EBADF;
8155 return -1;
8158 if (fd < MAXDESC && fd_info[fd].cp)
8160 child_process * cp = fd_info[fd].cp;
8162 fd_info[fd].cp = NULL;
8164 if (CHILD_ACTIVE (cp))
8166 /* if last descriptor to active child_process then cleanup */
8167 int i;
8168 for (i = 0; i < MAXDESC; i++)
8170 if (i == fd)
8171 continue;
8172 if (fd_info[i].cp == cp)
8173 break;
8175 if (i == MAXDESC)
8177 if (fd_info[fd].flags & FILE_SOCKET)
8179 if (winsock_lib == NULL) emacs_abort ();
8181 pfn_shutdown (SOCK_HANDLE (fd), 2);
8182 rc = pfn_closesocket (SOCK_HANDLE (fd));
8184 winsock_inuse--; /* count open sockets */
8186 /* If the process handle is NULL, it's either a socket
8187 or serial connection, or a subprocess that was
8188 already reaped by reap_subprocess, but whose
8189 resources were not yet freed, because its output was
8190 not fully read yet by the time it was reaped. (This
8191 usually happens with async subprocesses whose output
8192 is being read by Emacs.) Otherwise, this process was
8193 not reaped yet, so we set its FD to a negative value
8194 to make sure sys_select will eventually get to
8195 calling the SIGCHLD handler for it, which will then
8196 invoke waitpid and reap_subprocess. */
8197 if (cp->procinfo.hProcess == NULL)
8198 delete_child (cp);
8199 else
8200 cp->fd = -1;
8205 if (fd >= 0 && fd < MAXDESC)
8206 fd_info[fd].flags = 0;
8208 /* Note that sockets do not need special treatment here (at least on
8209 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8210 closesocket is equivalent to CloseHandle, which is to be expected
8211 because socket handles are fully fledged kernel handles. */
8212 rc = _close (fd);
8214 return rc;
8218 sys_dup (int fd)
8220 int new_fd;
8222 new_fd = _dup (fd);
8223 if (new_fd >= 0 && new_fd < MAXDESC)
8225 /* duplicate our internal info as well */
8226 fd_info[new_fd] = fd_info[fd];
8228 return new_fd;
8232 sys_dup2 (int src, int dst)
8234 int rc;
8236 if (dst < 0 || dst >= MAXDESC)
8238 errno = EBADF;
8239 return -1;
8242 /* MS _dup2 seems to have weird side effect when invoked with 2
8243 identical arguments: an attempt to fclose the corresponding stdio
8244 stream after that hangs (we do close standard streams in
8245 init_ntproc). Attempt to avoid that by not calling _dup2 that
8246 way: if SRC is valid, we know that dup2 should be a no-op, so do
8247 nothing and return DST. */
8248 if (src == dst)
8250 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8252 errno = EBADF;
8253 return -1;
8255 return dst;
8258 /* Make sure we close the destination first if it's a pipe or socket. */
8259 if (fd_info[dst].flags != 0)
8260 sys_close (dst);
8262 rc = _dup2 (src, dst);
8263 if (rc == 0)
8265 /* Duplicate our internal info as well. */
8266 fd_info[dst] = fd_info[src];
8268 return rc == 0 ? dst : rc;
8272 pipe2 (int * phandles, int pipe2_flags)
8274 int rc;
8275 unsigned flags;
8276 unsigned pipe_size = 0;
8278 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8280 /* Allow Lisp to override the default buffer size of the pipe. */
8281 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8282 pipe_size = w32_pipe_buffer_size;
8284 /* make pipe handles non-inheritable; when we spawn a child, we
8285 replace the relevant handle with an inheritable one. Also put
8286 pipes into binary mode; we will do text mode translation ourselves
8287 if required. */
8288 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8290 if (rc == 0)
8292 /* Protect against overflow, since Windows can open more handles than
8293 our fd_info array has room for. */
8294 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8296 _close (phandles[0]);
8297 _close (phandles[1]);
8298 errno = EMFILE;
8299 rc = -1;
8301 else
8303 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8304 fd_info[phandles[0]].flags = flags;
8306 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8307 fd_info[phandles[1]].flags = flags;
8311 return rc;
8314 /* Function to do blocking read of one byte, needed to implement
8315 select. It is only allowed on communication ports, sockets, or
8316 pipes. */
8318 _sys_read_ahead (int fd)
8320 child_process * cp;
8321 int rc;
8323 if (fd < 0 || fd >= MAXDESC)
8324 return STATUS_READ_ERROR;
8326 cp = fd_info[fd].cp;
8328 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8329 return STATUS_READ_ERROR;
8331 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8332 || (fd_info[fd].flags & FILE_READ) == 0)
8334 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8335 emacs_abort ();
8338 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8339 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8340 cp->status = STATUS_READ_IN_PROGRESS;
8342 if (fd_info[fd].flags & FILE_PIPE)
8344 rc = _read (fd, &cp->chr, sizeof (char));
8346 /* Give subprocess time to buffer some more output for us before
8347 reporting that input is available; we need this because Windows 95
8348 connects DOS programs to pipes by making the pipe appear to be
8349 the normal console stdout - as a result most DOS programs will
8350 write to stdout without buffering, ie. one character at a
8351 time. Even some W32 programs do this - "dir" in a command
8352 shell on NT is very slow if we don't do this. */
8353 if (rc > 0)
8355 int wait = w32_pipe_read_delay;
8357 if (wait > 0)
8358 Sleep (wait);
8359 else if (wait < 0)
8360 while (++wait <= 0)
8361 /* Yield remainder of our time slice, effectively giving a
8362 temporary priority boost to the child process. */
8363 Sleep (0);
8366 else if (fd_info[fd].flags & FILE_SERIAL)
8368 HANDLE hnd = fd_info[fd].hnd;
8369 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8370 COMMTIMEOUTS ct;
8372 /* Configure timeouts for blocking read. */
8373 if (!GetCommTimeouts (hnd, &ct))
8375 cp->status = STATUS_READ_ERROR;
8376 return STATUS_READ_ERROR;
8378 ct.ReadIntervalTimeout = 0;
8379 ct.ReadTotalTimeoutMultiplier = 0;
8380 ct.ReadTotalTimeoutConstant = 0;
8381 if (!SetCommTimeouts (hnd, &ct))
8383 cp->status = STATUS_READ_ERROR;
8384 return STATUS_READ_ERROR;
8387 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8389 if (GetLastError () != ERROR_IO_PENDING)
8391 cp->status = STATUS_READ_ERROR;
8392 return STATUS_READ_ERROR;
8394 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8396 cp->status = STATUS_READ_ERROR;
8397 return STATUS_READ_ERROR;
8401 else if (fd_info[fd].flags & FILE_SOCKET)
8403 unsigned long nblock = 0;
8404 /* We always want this to block, so temporarily disable NDELAY. */
8405 if (fd_info[fd].flags & FILE_NDELAY)
8406 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8408 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8410 if (fd_info[fd].flags & FILE_NDELAY)
8412 nblock = 1;
8413 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8417 if (rc == sizeof (char))
8418 cp->status = STATUS_READ_SUCCEEDED;
8419 else
8420 cp->status = STATUS_READ_FAILED;
8422 return cp->status;
8426 _sys_wait_accept (int fd)
8428 HANDLE hEv;
8429 child_process * cp;
8430 int rc;
8432 if (fd < 0 || fd >= MAXDESC)
8433 return STATUS_READ_ERROR;
8435 cp = fd_info[fd].cp;
8437 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8438 return STATUS_READ_ERROR;
8440 cp->status = STATUS_READ_FAILED;
8442 hEv = pfn_WSACreateEvent ();
8443 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8444 if (rc != SOCKET_ERROR)
8446 do {
8447 rc = WaitForSingleObject (hEv, 500);
8448 Sleep (5);
8449 } while (rc == WAIT_TIMEOUT
8450 && cp->status != STATUS_READ_ERROR
8451 && cp->char_avail);
8452 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8453 if (rc == WAIT_OBJECT_0)
8454 cp->status = STATUS_READ_SUCCEEDED;
8456 pfn_WSACloseEvent (hEv);
8458 return cp->status;
8462 _sys_wait_connect (int fd)
8464 HANDLE hEv;
8465 child_process * cp;
8466 int rc;
8468 if (fd < 0 || fd >= MAXDESC)
8469 return STATUS_READ_ERROR;
8471 cp = fd_info[fd].cp;
8472 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8473 return STATUS_READ_ERROR;
8475 cp->status = STATUS_READ_FAILED;
8477 hEv = pfn_WSACreateEvent ();
8478 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8479 if (rc != SOCKET_ERROR)
8481 do {
8482 rc = WaitForSingleObject (hEv, 500);
8483 Sleep (5);
8484 } while (rc == WAIT_TIMEOUT
8485 && cp->status != STATUS_READ_ERROR
8486 && cp->char_avail);
8487 if (rc == WAIT_OBJECT_0)
8489 /* We've got an event, but it could be a successful
8490 connection, or it could be a failure. Find out
8491 which one is it. */
8492 WSANETWORKEVENTS events;
8494 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8495 if ((events.lNetworkEvents & FD_CONNECT) != 0
8496 && events.iErrorCode[FD_CONNECT_BIT])
8498 cp->status = STATUS_CONNECT_FAILED;
8499 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8501 else
8503 cp->status = STATUS_READ_SUCCEEDED;
8504 cp->errcode = 0;
8507 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8509 else
8510 pfn_WSACloseEvent (hEv);
8512 return cp->status;
8516 sys_read (int fd, char * buffer, unsigned int count)
8518 int nchars;
8519 int to_read;
8520 DWORD waiting;
8521 char * orig_buffer = buffer;
8523 if (fd < 0)
8525 errno = EBADF;
8526 return -1;
8529 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8531 child_process *cp = fd_info[fd].cp;
8533 if ((fd_info[fd].flags & FILE_READ) == 0)
8535 errno = EBADF;
8536 return -1;
8539 nchars = 0;
8541 /* re-read CR carried over from last read */
8542 if (fd_info[fd].flags & FILE_LAST_CR)
8544 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8545 *buffer++ = 0x0d;
8546 count--;
8547 nchars++;
8548 fd_info[fd].flags &= ~FILE_LAST_CR;
8551 /* presence of a child_process structure means we are operating in
8552 non-blocking mode - otherwise we just call _read directly.
8553 Note that the child_process structure might be missing because
8554 reap_subprocess has been called; in this case the pipe is
8555 already broken, so calling _read on it is okay. */
8556 if (cp)
8558 int current_status = cp->status;
8560 switch (current_status)
8562 case STATUS_READ_FAILED:
8563 case STATUS_READ_ERROR:
8564 /* report normal EOF if nothing in buffer */
8565 if (nchars <= 0)
8566 fd_info[fd].flags |= FILE_AT_EOF;
8567 return nchars;
8569 case STATUS_READ_READY:
8570 case STATUS_READ_IN_PROGRESS:
8571 #if 0
8572 /* This happens all the time during GnuTLS handshake
8573 with the remote, evidently because GnuTLS waits for
8574 the read to complete by retrying the read operation
8575 upon EAGAIN. So I'm disabling the DebPrint to avoid
8576 wasting cycles on something that is not a real
8577 problem. Enable if you need to debug something that
8578 bumps into this. */
8579 DebPrint (("sys_read called when read is in progress %d\n",
8580 current_status));
8581 #endif
8582 errno = EWOULDBLOCK;
8583 return -1;
8585 case STATUS_READ_SUCCEEDED:
8586 /* consume read-ahead char */
8587 *buffer++ = cp->chr;
8588 count--;
8589 nchars++;
8590 cp->status = STATUS_READ_ACKNOWLEDGED;
8591 ResetEvent (cp->char_avail);
8593 case STATUS_READ_ACKNOWLEDGED:
8594 case STATUS_CONNECT_FAILED:
8595 break;
8597 default:
8598 DebPrint (("sys_read: bad status %d\n", current_status));
8599 errno = EBADF;
8600 return -1;
8603 if (fd_info[fd].flags & FILE_PIPE)
8605 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8606 to_read = min (waiting, (DWORD) count);
8608 if (to_read > 0)
8609 nchars += _read (fd, buffer, to_read);
8611 else if (fd_info[fd].flags & FILE_SERIAL)
8613 HANDLE hnd = fd_info[fd].hnd;
8614 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8615 int rc = 0;
8616 COMMTIMEOUTS ct;
8618 if (count > 0)
8620 /* Configure timeouts for non-blocking read. */
8621 if (!GetCommTimeouts (hnd, &ct))
8623 errno = EIO;
8624 return -1;
8626 ct.ReadIntervalTimeout = MAXDWORD;
8627 ct.ReadTotalTimeoutMultiplier = 0;
8628 ct.ReadTotalTimeoutConstant = 0;
8629 if (!SetCommTimeouts (hnd, &ct))
8631 errno = EIO;
8632 return -1;
8635 if (!ResetEvent (ovl->hEvent))
8637 errno = EIO;
8638 return -1;
8640 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8642 if (GetLastError () != ERROR_IO_PENDING)
8644 errno = EIO;
8645 return -1;
8647 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8649 errno = EIO;
8650 return -1;
8653 nchars += rc;
8656 else /* FILE_SOCKET */
8658 if (winsock_lib == NULL) emacs_abort ();
8660 /* When a non-blocking 'connect' call fails,
8661 wait_reading_process_output detects this by calling
8662 'getpeername', and then attempts to obtain the connection
8663 error code by trying to read 1 byte from the socket. If
8664 we try to serve that read by calling 'recv' below, the
8665 error we get is a generic WSAENOTCONN, not the actual
8666 connection error. So instead, we use the actual error
8667 code stashed by '_sys_wait_connect' in cp->errcode.
8668 Alternatively, we could have used 'getsockopt', like on
8669 GNU/Linux, but: (a) I have no idea whether the winsock
8670 version could hang, as it does "on some systems" (see the
8671 comment in process.c); and (b) 'getsockopt' on Windows is
8672 documented to clear the socket error for the entire
8673 process, which I'm not sure is TRT; FIXME. */
8674 if (current_status == STATUS_CONNECT_FAILED
8675 && (fd_info[fd].flags & FILE_CONNECT) != 0
8676 && cp->errcode != 0)
8678 pfn_WSASetLastError (cp->errcode);
8679 set_errno ();
8680 return -1;
8682 /* Do the equivalent of a non-blocking read. */
8683 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8684 if (waiting == 0 && nchars == 0)
8686 errno = EWOULDBLOCK;
8687 return -1;
8690 if (waiting)
8692 /* always use binary mode for sockets */
8693 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8694 if (res == SOCKET_ERROR)
8696 set_errno ();
8697 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8698 errno, SOCK_HANDLE (fd)));
8699 return -1;
8701 nchars += res;
8705 else
8707 int nread = _read (fd, buffer, count);
8708 if (nread >= 0)
8709 nchars += nread;
8710 else if (nchars == 0)
8711 nchars = nread;
8714 if (nchars <= 0)
8715 fd_info[fd].flags |= FILE_AT_EOF;
8716 /* Perform text mode translation if required. */
8717 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8719 nchars = crlf_to_lf (nchars, orig_buffer);
8720 /* If buffer contains only CR, return that. To be absolutely
8721 sure we should attempt to read the next char, but in
8722 practice a CR to be followed by LF would not appear by
8723 itself in the buffer. */
8724 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8726 fd_info[fd].flags |= FILE_LAST_CR;
8727 nchars--;
8731 else
8732 nchars = _read (fd, buffer, count);
8734 return nchars;
8737 /* From w32xfns.c */
8738 extern HANDLE interrupt_handle;
8741 sys_write (int fd, const void * buffer, unsigned int count)
8743 int nchars;
8744 USE_SAFE_ALLOCA;
8746 if (fd < 0)
8748 errno = EBADF;
8749 return -1;
8752 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8754 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8756 errno = EBADF;
8757 return -1;
8760 /* Perform text mode translation if required. */
8761 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8763 char * tmpbuf;
8764 const unsigned char * src = buffer;
8765 unsigned char * dst;
8766 int nbytes = count;
8768 SAFE_NALLOCA (tmpbuf, 2, count);
8769 dst = (unsigned char *)tmpbuf;
8771 while (1)
8773 unsigned char *next;
8774 /* Copy next line or remaining bytes. */
8775 next = _memccpy (dst, src, '\n', nbytes);
8776 if (next)
8778 /* Copied one line ending with '\n'. */
8779 int copied = next - dst;
8780 nbytes -= copied;
8781 src += copied;
8782 /* Insert '\r' before '\n'. */
8783 next[-1] = '\r';
8784 next[0] = '\n';
8785 dst = next + 1;
8786 count++;
8788 else
8789 /* Copied remaining partial line -> now finished. */
8790 break;
8792 buffer = tmpbuf;
8796 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8798 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8799 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8800 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8801 DWORD active = 0;
8803 /* This is async (a.k.a. "overlapped") I/O, so the return value
8804 of FALSE from WriteFile means either an error or the output
8805 will be completed asynchronously (ERROR_IO_PENDING). */
8806 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8808 if (GetLastError () != ERROR_IO_PENDING)
8810 errno = EIO;
8811 nchars = -1;
8813 else
8815 /* Wait for the write to complete, and watch C-g while
8816 at that. */
8817 if (detect_input_pending ())
8818 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8819 INFINITE, QS_ALLINPUT);
8820 else
8821 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8822 switch (active)
8824 case WAIT_OBJECT_0:
8825 /* User pressed C-g, cancel write, then leave.
8826 Don't bother cleaning up as we may only get stuck
8827 in buggy drivers. */
8828 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8829 CancelIo (hnd);
8830 errno = EIO; /* Why not EINTR? */
8831 nchars = -1;
8832 break;
8833 case WAIT_OBJECT_0 + 1:
8834 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8836 errno = EIO;
8837 nchars = -1;
8839 break;
8844 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8846 unsigned long nblock = 0;
8847 if (winsock_lib == NULL) emacs_abort ();
8849 child_process *cp = fd_info[fd].cp;
8851 /* If this is a non-blocking socket whose connection is in
8852 progress or terminated with an error already, return the
8853 proper error code to the caller. */
8854 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8856 /* In case connection is in progress, ENOTCONN that would
8857 result from calling pfn_send is not what callers expect. */
8858 if (cp->status != STATUS_CONNECT_FAILED)
8860 errno = EWOULDBLOCK;
8861 return -1;
8863 /* In case connection failed, use the actual error code
8864 stashed by '_sys_wait_connect' in cp->errcode. */
8865 else if (cp->errcode != 0)
8867 pfn_WSASetLastError (cp->errcode);
8868 set_errno ();
8869 return -1;
8873 /* TODO: implement select() properly so non-blocking I/O works. */
8874 /* For now, make sure the write blocks. */
8875 if (fd_info[fd].flags & FILE_NDELAY)
8876 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8878 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8880 if (nchars == SOCKET_ERROR)
8882 set_errno ();
8883 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8884 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8887 /* Set the socket back to non-blocking if it was before,
8888 for other operations that support it. */
8889 if (fd_info[fd].flags & FILE_NDELAY)
8891 nblock = 1;
8892 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8895 else
8897 /* Some networked filesystems don't like too large writes, so
8898 break them into smaller chunks. See the Comments section of
8899 the MSDN documentation of WriteFile for details behind the
8900 choice of the value of CHUNK below. See also the thread
8901 http://thread.gmane.org/gmane.comp.version-control.git/145294
8902 in the git mailing list. */
8903 const unsigned char *p = buffer;
8904 const bool is_pipe = (fd < MAXDESC
8905 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8906 == (FILE_PIPE | FILE_NDELAY)));
8907 /* Some programs, notably Node.js's node.exe, seem to never
8908 completely empty the pipe, so writing more than the size of
8909 the pipe's buffer always returns ENOSPC, and we loop forever
8910 between send_process and here. As a workaround, write no
8911 more than the pipe's buffer can hold. */
8912 DWORD pipe_buffer_size;
8913 if (is_pipe)
8915 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8916 NULL, &pipe_buffer_size, NULL, NULL))
8918 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8919 pipe_buffer_size = 4096;
8922 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8924 nchars = 0;
8925 errno = 0;
8926 while (count > 0)
8928 unsigned this_chunk = count < chunk ? count : chunk;
8929 int n = _write (fd, p, this_chunk);
8931 if (n > 0)
8932 nchars += n;
8933 if (n < 0)
8935 /* When there's no buffer space in a pipe that is in the
8936 non-blocking mode, _write returns ENOSPC. We return
8937 EAGAIN instead, which should trigger the logic in
8938 send_process that enters waiting loop and calls
8939 wait_reading_process_output to allow process input to
8940 be accepted during the wait. Those calls to
8941 wait_reading_process_output allow sys_select to
8942 notice when process input becomes available, thus
8943 avoiding deadlock whereby each side of the pipe is
8944 blocked on write, waiting for the other party to read
8945 its end of the pipe. */
8946 if (errno == ENOSPC && is_pipe)
8947 errno = EAGAIN;
8948 if (nchars == 0)
8949 nchars = -1;
8950 break;
8952 else if (n < this_chunk)
8953 break;
8954 count -= n;
8955 p += n;
8959 SAFE_FREE ();
8960 return nchars;
8964 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8966 /* Return information about network interface IFNAME, or about all
8967 interfaces (if IFNAME is nil). */
8968 static Lisp_Object
8969 network_interface_get_info (Lisp_Object ifname)
8971 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8972 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8973 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8974 Lisp_Object res = Qnil;
8976 if (retval == ERROR_BUFFER_OVERFLOW)
8978 ainfo = xrealloc (ainfo, ainfo_len);
8979 retval = get_adapters_info (ainfo, &ainfo_len);
8982 if (retval == ERROR_SUCCESS)
8984 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8985 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8986 int if_num;
8987 struct sockaddr_in sa;
8989 /* For the below, we need some winsock functions, so make sure
8990 the winsock DLL is loaded. If we cannot successfully load
8991 it, they will have no use of the information we provide,
8992 anyway, so punt. */
8993 if (!winsock_lib && !init_winsock (1))
8994 goto done;
8996 for (adapter = ainfo; adapter; adapter = adapter->Next)
8998 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8999 u_long ip_addr;
9000 /* Present Unix-compatible interface names, instead of the
9001 Windows names, which are really GUIDs not readable by
9002 humans. */
9003 static const char *ifmt[] = {
9004 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
9005 "lo", "ifx%d"
9007 enum {
9008 NONE = -1,
9009 ETHERNET = 0,
9010 TOKENRING = 1,
9011 FDDI = 2,
9012 PPP = 3,
9013 SLIP = 4,
9014 WLAN = 5,
9015 LOOPBACK = 6,
9016 OTHER_IF = 7
9017 } ifmt_idx;
9019 switch (adapter->Type)
9021 case MIB_IF_TYPE_ETHERNET:
9022 /* Windows before Vista reports wireless adapters as
9023 Ethernet. Work around by looking at the Description
9024 string. */
9025 if (strstr (adapter->Description, "Wireless "))
9027 ifmt_idx = WLAN;
9028 if_num = wlan_count++;
9030 else
9032 ifmt_idx = ETHERNET;
9033 if_num = eth_count++;
9035 break;
9036 case MIB_IF_TYPE_TOKENRING:
9037 ifmt_idx = TOKENRING;
9038 if_num = tr_count++;
9039 break;
9040 case MIB_IF_TYPE_FDDI:
9041 ifmt_idx = FDDI;
9042 if_num = fddi_count++;
9043 break;
9044 case MIB_IF_TYPE_PPP:
9045 ifmt_idx = PPP;
9046 if_num = ppp_count++;
9047 break;
9048 case MIB_IF_TYPE_SLIP:
9049 ifmt_idx = SLIP;
9050 if_num = sl_count++;
9051 break;
9052 case IF_TYPE_IEEE80211:
9053 ifmt_idx = WLAN;
9054 if_num = wlan_count++;
9055 break;
9056 case MIB_IF_TYPE_LOOPBACK:
9057 if (lo_count < 0)
9059 ifmt_idx = LOOPBACK;
9060 if_num = lo_count++;
9062 else
9063 ifmt_idx = NONE;
9064 break;
9065 default:
9066 ifmt_idx = OTHER_IF;
9067 if_num = ifx_count++;
9068 break;
9070 if (ifmt_idx == NONE)
9071 continue;
9072 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9074 sa.sin_family = AF_INET;
9075 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9076 if (ip_addr == INADDR_NONE)
9078 /* Bogus address, skip this interface. */
9079 continue;
9081 sa.sin_addr.s_addr = ip_addr;
9082 sa.sin_port = 0;
9083 if (NILP (ifname))
9084 res = Fcons (Fcons (build_string (namebuf),
9085 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9086 sizeof (struct sockaddr))),
9087 res);
9088 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9090 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9091 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9092 Lisp_Object flags = Qnil;
9093 int n;
9094 u_long net_mask;
9096 /* Flags. We guess most of them by type, since the
9097 Windows flags are different and hard to get by. */
9098 flags = Fcons (intern ("up"), flags);
9099 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9101 flags = Fcons (intern ("broadcast"), flags);
9102 flags = Fcons (intern ("multicast"), flags);
9104 flags = Fcons (intern ("running"), flags);
9105 if (ifmt_idx == PPP)
9107 flags = Fcons (intern ("pointopoint"), flags);
9108 flags = Fcons (intern ("noarp"), flags);
9110 if (adapter->HaveWins)
9111 flags = Fcons (intern ("WINS"), flags);
9112 if (adapter->DhcpEnabled)
9113 flags = Fcons (intern ("dynamic"), flags);
9115 res = Fcons (flags, res);
9117 /* Hardware address and its family. */
9118 for (n = 0; n < adapter->AddressLength; n++)
9119 p->contents[n] = make_number ((int) adapter->Address[n]);
9120 /* Windows does not support AF_LINK or AF_PACKET family
9121 of addresses. Use an arbitrary family number that is
9122 identical to what GNU/Linux returns. */
9123 res = Fcons (Fcons (make_number (1), hwaddr), res);
9125 /* Network mask. */
9126 sa.sin_family = AF_INET;
9127 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9128 if (net_mask != INADDR_NONE)
9130 sa.sin_addr.s_addr = net_mask;
9131 sa.sin_port = 0;
9132 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9133 sizeof (struct sockaddr)),
9134 res);
9136 else
9137 res = Fcons (Qnil, res);
9139 sa.sin_family = AF_INET;
9140 if (ip_addr != INADDR_NONE)
9142 /* Broadcast address is only reported by
9143 GetAdaptersAddresses, which is of limited
9144 availability. Generate it on our own. */
9145 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9147 sa.sin_addr.s_addr = bcast_addr;
9148 sa.sin_port = 0;
9149 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9150 sizeof (struct sockaddr)),
9151 res);
9153 /* IP address. */
9154 sa.sin_addr.s_addr = ip_addr;
9155 sa.sin_port = 0;
9156 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9157 sizeof (struct sockaddr)),
9158 res);
9160 else
9161 res = Fcons (Qnil, Fcons (Qnil, res));
9164 /* GetAdaptersInfo is documented to not report loopback
9165 interfaces, so we generate one out of thin air. */
9166 if (!lo_count)
9168 sa.sin_family = AF_INET;
9169 sa.sin_port = 0;
9170 if (NILP (ifname))
9172 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9173 res = Fcons (Fcons (build_string ("lo"),
9174 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9175 sizeof (struct sockaddr))),
9176 res);
9178 else if (strcmp (SSDATA (ifname), "lo") == 0)
9180 res = Fcons (Fcons (intern ("running"),
9181 Fcons (intern ("loopback"),
9182 Fcons (intern ("up"), Qnil))), Qnil);
9183 /* 772 is what 3 different GNU/Linux systems report for
9184 the loopback interface. */
9185 res = Fcons (Fcons (make_number (772),
9186 Fmake_vector (make_number (6),
9187 make_number (0))),
9188 res);
9189 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9190 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9191 sizeof (struct sockaddr)),
9192 res);
9193 sa.sin_addr.s_addr = sys_inet_addr ("0.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 ("127.0.0.1");
9198 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9199 sizeof (struct sockaddr)),
9200 res);
9206 done:
9207 xfree (ainfo);
9208 return res;
9211 Lisp_Object
9212 network_interface_list (void)
9214 return network_interface_get_info (Qnil);
9217 Lisp_Object
9218 network_interface_info (Lisp_Object ifname)
9220 CHECK_STRING (ifname);
9221 return network_interface_get_info (ifname);
9225 /* The Windows CRT functions are "optimized for speed", so they don't
9226 check for timezone and DST changes if they were last called less
9227 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9228 all Emacs features that repeatedly call time functions (e.g.,
9229 display-time) are in real danger of missing timezone and DST
9230 changes. Calling tzset before each localtime call fixes that. */
9231 struct tm *
9232 sys_localtime (const time_t *t)
9234 tzset ();
9235 return localtime (t);
9240 /* Try loading LIBRARY_ID from the file(s) specified in
9241 Vdynamic_library_alist. If the library is loaded successfully,
9242 return the handle of the DLL, and record the filename in the
9243 property :loaded-from of LIBRARY_ID. If the library could not be
9244 found, or when it was already loaded (because the handle is not
9245 recorded anywhere, and so is lost after use), return NULL.
9247 We could also save the handle in :loaded-from, but currently
9248 there's no use case for it. */
9249 HMODULE
9250 w32_delayed_load (Lisp_Object library_id)
9252 HMODULE dll_handle = NULL;
9254 CHECK_SYMBOL (library_id);
9256 if (CONSP (Vdynamic_library_alist)
9257 && NILP (Fassq (library_id, Vlibrary_cache)))
9259 Lisp_Object found = Qnil;
9260 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9262 if (CONSP (dlls))
9263 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9265 Lisp_Object dll = XCAR (dlls);
9266 char name[MAX_UTF8_PATH];
9267 DWORD res = -1;
9269 CHECK_STRING (dll);
9270 dll = ENCODE_FILE (dll);
9271 if (w32_unicode_filenames)
9273 wchar_t name_w[MAX_PATH];
9275 filename_to_utf16 (SSDATA (dll), name_w);
9276 dll_handle = LoadLibraryW (name_w);
9277 if (dll_handle)
9279 res = GetModuleFileNameW (dll_handle, name_w,
9280 sizeof (name_w));
9281 if (res > 0)
9282 filename_from_utf16 (name_w, name);
9285 else
9287 char name_a[MAX_PATH];
9289 filename_to_ansi (SSDATA (dll), name_a);
9290 dll_handle = LoadLibraryA (name_a);
9291 if (dll_handle)
9293 res = GetModuleFileNameA (dll_handle, name_a,
9294 sizeof (name_a));
9295 if (res > 0)
9296 filename_from_ansi (name_a, name);
9299 if (dll_handle)
9301 ptrdiff_t len = strlen (name);
9302 found = Fcons (dll,
9303 (res > 0)
9304 /* Possibly truncated */
9305 ? make_specified_string (name, -1, len, 1)
9306 : Qnil);
9307 /* This prevents thread start and end notifications
9308 from being sent to the DLL, for every thread we
9309 start. We don't need those notifications because
9310 threads we create never use any of these DLLs, only
9311 the main thread uses them. This is supposed to
9312 speed up thread creation. */
9313 DisableThreadLibraryCalls (dll_handle);
9314 break;
9318 Fput (library_id, QCloaded_from, found);
9321 return dll_handle;
9325 void
9326 check_windows_init_file (void)
9328 /* A common indication that Emacs is not installed properly is when
9329 it cannot find the Windows installation file. If this file does
9330 not exist in the expected place, tell the user. */
9332 if (!noninteractive && !inhibit_window_system
9333 /* Vload_path is not yet initialized when we are loading
9334 loadup.el. */
9335 && NILP (Vpurify_flag))
9337 Lisp_Object init_file;
9338 int fd;
9340 /* Implementation note: this function runs early during Emacs
9341 startup, before startup.el is run. So Vload_path is still in
9342 its initial unibyte form, but it holds UTF-8 encoded file
9343 names, since init_callproc was already called. So we do not
9344 need to ENCODE_FILE here, but we do need to convert the file
9345 names from UTF-8 to ANSI. */
9346 init_file = build_string ("term/w32-win");
9347 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9348 if (fd < 0)
9350 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9351 char *init_file_name = SSDATA (init_file);
9352 char *load_path = SSDATA (load_path_print);
9353 char *buffer = alloca (1024
9354 + strlen (init_file_name)
9355 + strlen (load_path));
9356 char *msg = buffer;
9357 int needed;
9359 sprintf (buffer,
9360 "The Emacs Windows initialization file \"%s.el\" "
9361 "could not be found in your Emacs installation. "
9362 "Emacs checked the following directories for this file:\n"
9363 "\n%s\n\n"
9364 "When Emacs cannot find this file, it usually means that it "
9365 "was not installed properly, or its distribution file was "
9366 "not unpacked properly.\nSee the README.W32 file in the "
9367 "top-level Emacs directory for more information.",
9368 init_file_name, load_path);
9369 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9370 buffer, -1, NULL, 0);
9371 if (needed > 0)
9373 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9375 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9376 -1, msg_w, needed);
9377 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9378 NULL, 0, NULL, NULL);
9379 if (needed > 0)
9381 char *msg_a = alloca (needed + 1);
9383 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9384 NULL, NULL);
9385 msg = msg_a;
9388 MessageBox (NULL,
9389 msg,
9390 "Emacs Abort Dialog",
9391 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9392 /* Use the low-level system abort. */
9393 abort ();
9395 else
9397 _close (fd);
9402 void
9403 term_ntproc (int ignored)
9405 (void)ignored;
9407 term_timers ();
9409 /* shutdown the socket interface if necessary */
9410 term_winsock ();
9412 term_w32select ();
9415 void
9416 init_ntproc (int dumping)
9418 sigset_t initial_mask = 0;
9420 /* Initialize the socket interface now if available and requested by
9421 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9422 delayed until open-network-stream is called (w32-has-winsock can
9423 also be used to dynamically load or reload winsock).
9425 Conveniently, init_environment is called before us, so
9426 PRELOAD_WINSOCK can be set in the registry. */
9428 /* Always initialize this correctly. */
9429 winsock_lib = NULL;
9431 if (getenv ("PRELOAD_WINSOCK") != NULL)
9432 init_winsock (TRUE);
9434 /* Initial preparation for subprocess support: replace our standard
9435 handles with non-inheritable versions. */
9437 HANDLE parent;
9438 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9439 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9440 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9442 parent = GetCurrentProcess ();
9444 /* ignore errors when duplicating and closing; typically the
9445 handles will be invalid when running as a gui program. */
9446 DuplicateHandle (parent,
9447 GetStdHandle (STD_INPUT_HANDLE),
9448 parent,
9449 &stdin_save,
9451 FALSE,
9452 DUPLICATE_SAME_ACCESS);
9454 DuplicateHandle (parent,
9455 GetStdHandle (STD_OUTPUT_HANDLE),
9456 parent,
9457 &stdout_save,
9459 FALSE,
9460 DUPLICATE_SAME_ACCESS);
9462 DuplicateHandle (parent,
9463 GetStdHandle (STD_ERROR_HANDLE),
9464 parent,
9465 &stderr_save,
9467 FALSE,
9468 DUPLICATE_SAME_ACCESS);
9470 fclose (stdin);
9471 fclose (stdout);
9472 fclose (stderr);
9474 if (stdin_save != INVALID_HANDLE_VALUE)
9475 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9476 else
9477 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9478 _fdopen (0, "r");
9480 if (stdout_save != INVALID_HANDLE_VALUE)
9481 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9482 else
9483 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9484 _fdopen (1, "w");
9486 if (stderr_save != INVALID_HANDLE_VALUE)
9487 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9488 else
9489 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9490 _fdopen (2, "w");
9493 /* unfortunately, atexit depends on implementation of malloc */
9494 /* atexit (term_ntproc); */
9495 if (!dumping)
9497 /* Make sure we start with all signals unblocked. */
9498 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9499 signal (SIGABRT, term_ntproc);
9501 init_timers ();
9503 /* determine which drives are fixed, for GetCachedVolumeInformation */
9505 /* GetDriveType must have trailing backslash. */
9506 char drive[] = "A:\\";
9508 /* Loop over all possible drive letters */
9509 while (*drive <= 'Z')
9511 /* Record if this drive letter refers to a fixed drive. */
9512 fixed_drives[DRIVE_INDEX (*drive)] =
9513 (GetDriveType (drive) == DRIVE_FIXED);
9515 (*drive)++;
9518 /* Reset the volume info cache. */
9519 volume_cache = NULL;
9524 shutdown_handler ensures that buffers' autosave files are
9525 up to date when the user logs off, or the system shuts down.
9527 static BOOL WINAPI
9528 shutdown_handler (DWORD type)
9530 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9531 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9532 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9533 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9535 /* Shut down cleanly, making sure autosave files are up to date. */
9536 shut_down_emacs (0, Qnil);
9539 /* Allow other handlers to handle this signal. */
9540 return FALSE;
9543 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9544 NT, return a handle to GDI32.DLL. */
9545 HANDLE
9546 maybe_load_unicows_dll (void)
9548 if (os_subtype == OS_9X)
9550 HANDLE ret = LoadLibrary ("Unicows.dll");
9551 if (ret)
9553 /* These two functions are present on Windows 9X as stubs
9554 that always fail. We need the real implementations from
9555 UNICOWS.DLL, so we must call these functions through
9556 pointers, and assign the correct addresses to these
9557 pointers at program startup (see emacs.c, which calls
9558 this function early on). */
9559 pMultiByteToWideChar =
9560 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9561 pWideCharToMultiByte =
9562 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9563 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9564 return ret;
9566 else
9568 int button;
9570 button = MessageBox (NULL,
9571 "Emacs cannot load the UNICOWS.DLL library.\n"
9572 "This library is essential for using Emacs\n"
9573 "on this system. You need to install it.\n\n"
9574 "Emacs will exit when you click OK.",
9575 "Emacs cannot load UNICOWS.DLL",
9576 MB_ICONERROR | MB_TASKMODAL
9577 | MB_SETFOREGROUND | MB_OK);
9578 switch (button)
9580 case IDOK:
9581 default:
9582 exit (1);
9586 else
9588 /* On NT family of Windows, these two functions are always
9589 linked in, so we just assign their addresses to the 2
9590 pointers; no need for the LoadLibrary dance. */
9591 pMultiByteToWideChar = MultiByteToWideChar;
9592 pWideCharToMultiByte = WideCharToMultiByte;
9593 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9594 if (w32_major_version < 5)
9595 multiByteToWideCharFlags = 0;
9596 else
9597 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9598 return LoadLibrary ("Gdi32.dll");
9603 globals_of_w32 is used to initialize those global variables that
9604 must always be initialized on startup even when the global variable
9605 initialized is non zero (see the function main in emacs.c).
9607 void
9608 globals_of_w32 (void)
9610 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9612 get_process_times_fn = (GetProcessTimes_Proc)
9613 GetProcAddress (kernel32, "GetProcessTimes");
9615 DEFSYM (QCloaded_from, ":loaded-from");
9617 g_b_init_is_windows_9x = 0;
9618 g_b_init_open_process_token = 0;
9619 g_b_init_get_token_information = 0;
9620 g_b_init_lookup_account_sid = 0;
9621 g_b_init_get_sid_sub_authority = 0;
9622 g_b_init_get_sid_sub_authority_count = 0;
9623 g_b_init_get_security_info = 0;
9624 g_b_init_get_file_security_w = 0;
9625 g_b_init_get_file_security_a = 0;
9626 g_b_init_get_security_descriptor_owner = 0;
9627 g_b_init_get_security_descriptor_group = 0;
9628 g_b_init_is_valid_sid = 0;
9629 g_b_init_create_toolhelp32_snapshot = 0;
9630 g_b_init_process32_first = 0;
9631 g_b_init_process32_next = 0;
9632 g_b_init_open_thread_token = 0;
9633 g_b_init_impersonate_self = 0;
9634 g_b_init_revert_to_self = 0;
9635 g_b_init_get_process_memory_info = 0;
9636 g_b_init_get_process_working_set_size = 0;
9637 g_b_init_global_memory_status = 0;
9638 g_b_init_global_memory_status_ex = 0;
9639 g_b_init_equal_sid = 0;
9640 g_b_init_copy_sid = 0;
9641 g_b_init_get_length_sid = 0;
9642 g_b_init_get_native_system_info = 0;
9643 g_b_init_get_system_times = 0;
9644 g_b_init_create_symbolic_link_w = 0;
9645 g_b_init_create_symbolic_link_a = 0;
9646 g_b_init_get_security_descriptor_dacl = 0;
9647 g_b_init_convert_sd_to_sddl = 0;
9648 g_b_init_convert_sddl_to_sd = 0;
9649 g_b_init_is_valid_security_descriptor = 0;
9650 g_b_init_set_file_security_w = 0;
9651 g_b_init_set_file_security_a = 0;
9652 g_b_init_set_named_security_info_w = 0;
9653 g_b_init_set_named_security_info_a = 0;
9654 g_b_init_get_adapters_info = 0;
9655 g_b_init_compare_string_w = 0;
9656 num_of_processors = 0;
9657 /* The following sets a handler for shutdown notifications for
9658 console apps. This actually applies to Emacs in both console and
9659 GUI modes, since we had to fool windows into thinking emacs is a
9660 console application to get console mode to work. */
9661 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9663 /* "None" is the default group name on standalone workstations. */
9664 strcpy (dflt_group_name, "None");
9666 /* Reset, in case it has some value inherited from dump time. */
9667 w32_stat_get_owner_group = 0;
9669 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9670 (a.k.a. "wide") APIs to invoke functions that accept file
9671 names. */
9672 if (is_windows_9x ())
9673 w32_unicode_filenames = 0;
9674 else
9675 w32_unicode_filenames = 1;
9677 #ifdef HAVE_MODULES
9678 dynlib_reset_last_error ();
9679 #endif
9681 w32_crypto_hprov = (HCRYPTPROV)0;
9684 /* For make-serial-process */
9686 serial_open (Lisp_Object port_obj)
9688 char *port = SSDATA (port_obj);
9689 HANDLE hnd;
9690 child_process *cp;
9691 int fd = -1;
9693 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9694 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9695 if (hnd == INVALID_HANDLE_VALUE)
9696 error ("Could not open %s", port);
9697 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9698 if (fd == -1)
9699 error ("Could not open %s", port);
9701 cp = new_child ();
9702 if (!cp)
9703 error ("Could not create child process");
9704 cp->fd = fd;
9705 cp->status = STATUS_READ_ACKNOWLEDGED;
9706 fd_info[ fd ].hnd = hnd;
9707 fd_info[ fd ].flags |=
9708 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9709 if (fd_info[ fd ].cp != NULL)
9711 error ("fd_info[fd = %d] is already in use", fd);
9713 fd_info[ fd ].cp = cp;
9714 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9715 if (cp->ovl_read.hEvent == NULL)
9716 error ("Could not create read event");
9717 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9718 if (cp->ovl_write.hEvent == NULL)
9719 error ("Could not create write event");
9721 return fd;
9724 /* For serial-process-configure */
9725 void
9726 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9728 Lisp_Object childp2 = Qnil;
9729 Lisp_Object tem = Qnil;
9730 HANDLE hnd;
9731 DCB dcb;
9732 COMMTIMEOUTS ct;
9733 char summary[4] = "???"; /* This usually becomes "8N1". */
9735 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9736 error ("Not a serial process");
9737 hnd = fd_info[ p->outfd ].hnd;
9739 childp2 = Fcopy_sequence (p->childp);
9741 /* Initialize timeouts for blocking read and blocking write. */
9742 if (!GetCommTimeouts (hnd, &ct))
9743 error ("GetCommTimeouts() failed");
9744 ct.ReadIntervalTimeout = 0;
9745 ct.ReadTotalTimeoutMultiplier = 0;
9746 ct.ReadTotalTimeoutConstant = 0;
9747 ct.WriteTotalTimeoutMultiplier = 0;
9748 ct.WriteTotalTimeoutConstant = 0;
9749 if (!SetCommTimeouts (hnd, &ct))
9750 error ("SetCommTimeouts() failed");
9751 /* Read port attributes and prepare default configuration. */
9752 memset (&dcb, 0, sizeof (dcb));
9753 dcb.DCBlength = sizeof (DCB);
9754 if (!GetCommState (hnd, &dcb))
9755 error ("GetCommState() failed");
9756 dcb.fBinary = TRUE;
9757 dcb.fNull = FALSE;
9758 dcb.fAbortOnError = FALSE;
9759 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9760 dcb.ErrorChar = 0;
9761 dcb.EofChar = 0;
9762 dcb.EvtChar = 0;
9764 /* Configure speed. */
9765 if (!NILP (Fplist_member (contact, QCspeed)))
9766 tem = Fplist_get (contact, QCspeed);
9767 else
9768 tem = Fplist_get (p->childp, QCspeed);
9769 CHECK_NUMBER (tem);
9770 dcb.BaudRate = XINT (tem);
9771 childp2 = Fplist_put (childp2, QCspeed, tem);
9773 /* Configure bytesize. */
9774 if (!NILP (Fplist_member (contact, QCbytesize)))
9775 tem = Fplist_get (contact, QCbytesize);
9776 else
9777 tem = Fplist_get (p->childp, QCbytesize);
9778 if (NILP (tem))
9779 tem = make_number (8);
9780 CHECK_NUMBER (tem);
9781 if (XINT (tem) != 7 && XINT (tem) != 8)
9782 error (":bytesize must be nil (8), 7, or 8");
9783 dcb.ByteSize = XINT (tem);
9784 summary[0] = XINT (tem) + '0';
9785 childp2 = Fplist_put (childp2, QCbytesize, tem);
9787 /* Configure parity. */
9788 if (!NILP (Fplist_member (contact, QCparity)))
9789 tem = Fplist_get (contact, QCparity);
9790 else
9791 tem = Fplist_get (p->childp, QCparity);
9792 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9793 error (":parity must be nil (no parity), `even', or `odd'");
9794 dcb.fParity = FALSE;
9795 dcb.Parity = NOPARITY;
9796 dcb.fErrorChar = FALSE;
9797 if (NILP (tem))
9799 summary[1] = 'N';
9801 else if (EQ (tem, Qeven))
9803 summary[1] = 'E';
9804 dcb.fParity = TRUE;
9805 dcb.Parity = EVENPARITY;
9806 dcb.fErrorChar = TRUE;
9808 else if (EQ (tem, Qodd))
9810 summary[1] = 'O';
9811 dcb.fParity = TRUE;
9812 dcb.Parity = ODDPARITY;
9813 dcb.fErrorChar = TRUE;
9815 childp2 = Fplist_put (childp2, QCparity, tem);
9817 /* Configure stopbits. */
9818 if (!NILP (Fplist_member (contact, QCstopbits)))
9819 tem = Fplist_get (contact, QCstopbits);
9820 else
9821 tem = Fplist_get (p->childp, QCstopbits);
9822 if (NILP (tem))
9823 tem = make_number (1);
9824 CHECK_NUMBER (tem);
9825 if (XINT (tem) != 1 && XINT (tem) != 2)
9826 error (":stopbits must be nil (1 stopbit), 1, or 2");
9827 summary[2] = XINT (tem) + '0';
9828 if (XINT (tem) == 1)
9829 dcb.StopBits = ONESTOPBIT;
9830 else if (XINT (tem) == 2)
9831 dcb.StopBits = TWOSTOPBITS;
9832 childp2 = Fplist_put (childp2, QCstopbits, tem);
9834 /* Configure flowcontrol. */
9835 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9836 tem = Fplist_get (contact, QCflowcontrol);
9837 else
9838 tem = Fplist_get (p->childp, QCflowcontrol);
9839 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9840 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9841 dcb.fOutxCtsFlow = FALSE;
9842 dcb.fOutxDsrFlow = FALSE;
9843 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9844 dcb.fDsrSensitivity = FALSE;
9845 dcb.fTXContinueOnXoff = FALSE;
9846 dcb.fOutX = FALSE;
9847 dcb.fInX = FALSE;
9848 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9849 dcb.XonChar = 17; /* Control-Q */
9850 dcb.XoffChar = 19; /* Control-S */
9851 if (NILP (tem))
9853 /* Already configured. */
9855 else if (EQ (tem, Qhw))
9857 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9858 dcb.fOutxCtsFlow = TRUE;
9860 else if (EQ (tem, Qsw))
9862 dcb.fOutX = TRUE;
9863 dcb.fInX = TRUE;
9865 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9867 /* Activate configuration. */
9868 if (!SetCommState (hnd, &dcb))
9869 error ("SetCommState() failed");
9871 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9872 pset_childp (p, childp2);
9875 /* For make-pipe-process */
9876 void
9877 register_aux_fd (int infd)
9879 child_process *cp;
9881 cp = new_child ();
9882 if (!cp)
9883 error ("Could not create child process");
9884 cp->fd = infd;
9885 cp->status = STATUS_READ_ACKNOWLEDGED;
9887 if (fd_info[ infd ].cp != NULL)
9889 error ("fd_info[fd = %d] is already in use", infd);
9891 fd_info[ infd ].cp = cp;
9892 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9895 #ifdef HAVE_GNUTLS
9897 ssize_t
9898 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9900 int n, err;
9901 struct Lisp_Process *process = (struct Lisp_Process *)p;
9902 int fd = process->infd;
9904 n = sys_read (fd, (char*)buf, sz);
9906 if (n >= 0)
9907 return n;
9909 err = errno;
9911 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9912 if (err == EWOULDBLOCK)
9913 err = EAGAIN;
9915 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9917 return -1;
9920 ssize_t
9921 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9923 struct Lisp_Process *process = (struct Lisp_Process *)p;
9924 int fd = process->outfd;
9925 ssize_t n = sys_write (fd, buf, sz);
9927 /* 0 or more bytes written means everything went fine. */
9928 if (n >= 0)
9929 return n;
9931 /* Negative bytes written means we got an error in errno.
9932 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9933 emacs_gnutls_transport_set_errno (process->gnutls_state,
9934 errno == EWOULDBLOCK ? EAGAIN : errno);
9936 return -1;
9938 #endif /* HAVE_GNUTLS */
9940 /* end of w32.c */