]> code.delx.au - gnu-emacs/blob - src/w32.c
Fix compiler warnings in the MinGW build
[gnu-emacs] / src / w32.c
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2
3 Copyright (C) 1994-1995, 2000-2016 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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/>. */
19
20 /*
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
22 */
23
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>
39
40 /* must include CRT headers *before* config.h */
41
42 #include <config.h>
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
44
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
57
58 #undef close
59 #undef dup
60 #undef dup2
61 #undef pipe
62 #undef read
63 #undef write
64
65 #undef strerror
66
67 #undef localtime
68
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 *);
82
83 #ifdef HAVE_MODULES
84 extern void dynlib_reset_last_error (void);
85 #endif
86
87 #include "lisp.h"
88 #include "epaths.h" /* for PATH_EXEC */
89
90 #include <pwd.h>
91 #include <grp.h>
92
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;
114
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;
129
130 #include <lmcons.h>
131 #include <shlobj.h>
132
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
158
159 #include <winioctl.h>
160 #include <aclapi.h>
161 #include <sddl.h>
162
163 #include <sys/acl.h>
164 #include <acl.h>
165
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 */
171
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. */
177
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;
203
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
222
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
242
243 #include <iphlpapi.h> /* should be after winsock2.h */
244
245 #include <wincrypt.h>
246
247 #include <c-strcase.h>
248 #include <utimens.h> /* for fdutimens */
249
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 */
257
258 #include "careadlinkat.h"
259 #include "allocator.h"
260
261 /* For Lisp_Process, serial_configure and serial_open. */
262 #include "process.h"
263 #include "systty.h"
264
265 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
266 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
267
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);
274
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);
280
281
282
283 \f
284 /* Initialization states.
285
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;
331
332 BOOL g_b_init_compare_string_w;
333
334 /*
335 BEGIN: Wrapper functions around OpenProcessToken
336 and other functions in advapi32.dll that are only
337 supported in Windows NT / 2k / XP
338 */
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);
356
357 GetProcessTimes_Proc get_process_times_fn = NULL;
358
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);
504
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;
508
509 /* ** A utility function ** */
510 static BOOL
511 is_windows_9x (void)
512 {
513 static BOOL s_b_ret = 0;
514 OSVERSIONINFO os_ver;
515 if (g_b_init_is_windows_9x == 0)
516 {
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))
521 {
522 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
523 }
524 }
525 return s_b_ret;
526 }
527
528 static Lisp_Object ltime (ULONGLONG);
529
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);
534
535 Lisp_Object
536 w32_get_internal_run_time (void)
537 {
538 if (get_process_times_fn)
539 {
540 FILETIME create, exit, kernel, user;
541 HANDLE proc = GetCurrentProcess ();
542 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
543 {
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);
551 }
552 }
553
554 return Fcurrent_time ();
555 }
556
557 /* ** The wrapper functions ** */
558
559 static BOOL WINAPI
560 open_process_token (HANDLE ProcessHandle,
561 DWORD DesiredAccess,
562 PHANDLE TokenHandle)
563 {
564 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
565 HMODULE hm_advapi32 = NULL;
566 if (is_windows_9x () == TRUE)
567 {
568 return FALSE;
569 }
570 if (g_b_init_open_process_token == 0)
571 {
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");
576 }
577 if (s_pfn_Open_Process_Token == NULL)
578 {
579 return FALSE;
580 }
581 return (
582 s_pfn_Open_Process_Token (
583 ProcessHandle,
584 DesiredAccess,
585 TokenHandle)
586 );
587 }
588
589 static BOOL WINAPI
590 get_token_information (HANDLE TokenHandle,
591 TOKEN_INFORMATION_CLASS TokenInformationClass,
592 LPVOID TokenInformation,
593 DWORD TokenInformationLength,
594 PDWORD ReturnLength)
595 {
596 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
597 HMODULE hm_advapi32 = NULL;
598 if (is_windows_9x () == TRUE)
599 {
600 return FALSE;
601 }
602 if (g_b_init_get_token_information == 0)
603 {
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");
608 }
609 if (s_pfn_Get_Token_Information == NULL)
610 {
611 return FALSE;
612 }
613 return (
614 s_pfn_Get_Token_Information (
615 TokenHandle,
616 TokenInformationClass,
617 TokenInformation,
618 TokenInformationLength,
619 ReturnLength)
620 );
621 }
622
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)
631 {
632 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
633 HMODULE hm_advapi32 = NULL;
634 if (is_windows_9x () == TRUE)
635 {
636 return FALSE;
637 }
638 if (g_b_init_lookup_account_sid == 0)
639 {
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);
644 }
645 if (s_pfn_Lookup_Account_Sid == NULL)
646 {
647 return FALSE;
648 }
649 return (
650 s_pfn_Lookup_Account_Sid (
651 lpSystemName,
652 Sid,
653 Name,
654 cbName,
655 DomainName,
656 cbDomainName,
657 peUse)
658 );
659 }
660
661 static PDWORD WINAPI
662 get_sid_sub_authority (PSID pSid, DWORD n)
663 {
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)
668 {
669 return &zero;
670 }
671 if (g_b_init_get_sid_sub_authority == 0)
672 {
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");
678 }
679 if (s_pfn_Get_Sid_Sub_Authority == NULL)
680 {
681 return &zero;
682 }
683 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
684 }
685
686 static PUCHAR WINAPI
687 get_sid_sub_authority_count (PSID pSid)
688 {
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)
693 {
694 return &zero;
695 }
696 if (g_b_init_get_sid_sub_authority_count == 0)
697 {
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");
703 }
704 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
705 {
706 return &zero;
707 }
708 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
709 }
710
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)
720 {
721 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
722 HMODULE hm_advapi32 = NULL;
723 if (is_windows_9x () == TRUE)
724 {
725 return FALSE;
726 }
727 if (g_b_init_get_security_info == 0)
728 {
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");
734 }
735 if (s_pfn_Get_Security_Info == NULL)
736 {
737 return FALSE;
738 }
739 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
740 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
741 ppSecurityDescriptor));
742 }
743
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)
750 {
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)
755 {
756 errno = ENOTSUP;
757 return FALSE;
758 }
759 if (w32_unicode_filenames)
760 {
761 wchar_t filename_w[MAX_PATH];
762
763 if (g_b_init_get_file_security_w == 0)
764 {
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");
770 }
771 if (s_pfn_Get_File_SecurityW == NULL)
772 {
773 errno = ENOTSUP;
774 return FALSE;
775 }
776 filename_to_utf16 (lpFileName, filename_w);
777 return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
778 pSecurityDescriptor, nLength,
779 lpnLengthNeeded));
780 }
781 else
782 {
783 char filename_a[MAX_PATH];
784
785 if (g_b_init_get_file_security_a == 0)
786 {
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");
792 }
793 if (s_pfn_Get_File_SecurityA == NULL)
794 {
795 errno = ENOTSUP;
796 return FALSE;
797 }
798 filename_to_ansi (lpFileName, filename_a);
799 return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
800 pSecurityDescriptor, nLength,
801 lpnLengthNeeded));
802 }
803 }
804
805 static BOOL WINAPI
806 set_file_security (const char *lpFileName,
807 SECURITY_INFORMATION SecurityInformation,
808 PSECURITY_DESCRIPTOR pSecurityDescriptor)
809 {
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)
814 {
815 errno = ENOTSUP;
816 return FALSE;
817 }
818 if (w32_unicode_filenames)
819 {
820 wchar_t filename_w[MAX_PATH];
821
822 if (g_b_init_set_file_security_w == 0)
823 {
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");
829 }
830 if (s_pfn_Set_File_SecurityW == NULL)
831 {
832 errno = ENOTSUP;
833 return FALSE;
834 }
835 filename_to_utf16 (lpFileName, filename_w);
836 return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
837 pSecurityDescriptor));
838 }
839 else
840 {
841 char filename_a[MAX_PATH];
842
843 if (g_b_init_set_file_security_a == 0)
844 {
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");
850 }
851 if (s_pfn_Set_File_SecurityA == NULL)
852 {
853 errno = ENOTSUP;
854 return FALSE;
855 }
856 filename_to_ansi (lpFileName, filename_a);
857 return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
858 pSecurityDescriptor));
859 }
860 }
861
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)
870 {
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)
875 {
876 errno = ENOTSUP;
877 return ENOTSUP;
878 }
879 if (w32_unicode_filenames)
880 {
881 wchar_t filename_w[MAX_PATH];
882
883 if (g_b_init_set_named_security_info_w == 0)
884 {
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");
890 }
891 if (s_pfn_Set_Named_Security_InfoW == NULL)
892 {
893 errno = ENOTSUP;
894 return ENOTSUP;
895 }
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));
900 }
901 else
902 {
903 char filename_a[MAX_PATH];
904
905 if (g_b_init_set_named_security_info_a == 0)
906 {
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");
912 }
913 if (s_pfn_Set_Named_Security_InfoA == NULL)
914 {
915 errno = ENOTSUP;
916 return ENOTSUP;
917 }
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));
922 }
923 }
924
925 static BOOL WINAPI
926 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
927 PSID *pOwner,
928 LPBOOL lpbOwnerDefaulted)
929 {
930 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
931 HMODULE hm_advapi32 = NULL;
932 if (is_windows_9x () == TRUE)
933 {
934 errno = ENOTSUP;
935 return FALSE;
936 }
937 if (g_b_init_get_security_descriptor_owner == 0)
938 {
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");
944 }
945 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
946 {
947 errno = ENOTSUP;
948 return FALSE;
949 }
950 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
951 lpbOwnerDefaulted));
952 }
953
954 static BOOL WINAPI
955 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
956 PSID *pGroup,
957 LPBOOL lpbGroupDefaulted)
958 {
959 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
960 HMODULE hm_advapi32 = NULL;
961 if (is_windows_9x () == TRUE)
962 {
963 errno = ENOTSUP;
964 return FALSE;
965 }
966 if (g_b_init_get_security_descriptor_group == 0)
967 {
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");
973 }
974 if (s_pfn_Get_Security_Descriptor_Group == NULL)
975 {
976 errno = ENOTSUP;
977 return FALSE;
978 }
979 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
980 lpbGroupDefaulted));
981 }
982
983 static BOOL WINAPI
984 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
985 LPBOOL lpbDaclPresent,
986 PACL *pDacl,
987 LPBOOL lpbDaclDefaulted)
988 {
989 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
990 HMODULE hm_advapi32 = NULL;
991 if (is_windows_9x () == TRUE)
992 {
993 errno = ENOTSUP;
994 return FALSE;
995 }
996 if (g_b_init_get_security_descriptor_dacl == 0)
997 {
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");
1003 }
1004 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
1005 {
1006 errno = ENOTSUP;
1007 return FALSE;
1008 }
1009 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
1010 lpbDaclPresent, pDacl,
1011 lpbDaclDefaulted));
1012 }
1013
1014 static BOOL WINAPI
1015 is_valid_sid (PSID sid)
1016 {
1017 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
1018 HMODULE hm_advapi32 = NULL;
1019 if (is_windows_9x () == TRUE)
1020 {
1021 return FALSE;
1022 }
1023 if (g_b_init_is_valid_sid == 0)
1024 {
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");
1030 }
1031 if (s_pfn_Is_Valid_Sid == NULL)
1032 {
1033 return FALSE;
1034 }
1035 return (s_pfn_Is_Valid_Sid (sid));
1036 }
1037
1038 static BOOL WINAPI
1039 equal_sid (PSID sid1, PSID sid2)
1040 {
1041 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
1042 HMODULE hm_advapi32 = NULL;
1043 if (is_windows_9x () == TRUE)
1044 {
1045 return FALSE;
1046 }
1047 if (g_b_init_equal_sid == 0)
1048 {
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");
1054 }
1055 if (s_pfn_Equal_Sid == NULL)
1056 {
1057 return FALSE;
1058 }
1059 return (s_pfn_Equal_Sid (sid1, sid2));
1060 }
1061
1062 static DWORD WINAPI
1063 get_length_sid (PSID sid)
1064 {
1065 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
1066 HMODULE hm_advapi32 = NULL;
1067 if (is_windows_9x () == TRUE)
1068 {
1069 return 0;
1070 }
1071 if (g_b_init_get_length_sid == 0)
1072 {
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");
1078 }
1079 if (s_pfn_Get_Length_Sid == NULL)
1080 {
1081 return 0;
1082 }
1083 return (s_pfn_Get_Length_Sid (sid));
1084 }
1085
1086 static BOOL WINAPI
1087 copy_sid (DWORD destlen, PSID dest, PSID src)
1088 {
1089 static CopySid_Proc s_pfn_Copy_Sid = NULL;
1090 HMODULE hm_advapi32 = NULL;
1091 if (is_windows_9x () == TRUE)
1092 {
1093 return FALSE;
1094 }
1095 if (g_b_init_copy_sid == 0)
1096 {
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");
1102 }
1103 if (s_pfn_Copy_Sid == NULL)
1104 {
1105 return FALSE;
1106 }
1107 return (s_pfn_Copy_Sid (destlen, dest, src));
1108 }
1109
1110 /*
1111 END: Wrapper functions around OpenProcessToken
1112 and other functions in advapi32.dll that are only
1113 supported in Windows NT / 2k / XP
1114 */
1115
1116 static void WINAPI
1117 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1118 {
1119 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
1120 if (is_windows_9x () != TRUE)
1121 {
1122 if (g_b_init_get_native_system_info == 0)
1123 {
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");
1128 }
1129 if (s_pfn_Get_Native_System_Info != NULL)
1130 s_pfn_Get_Native_System_Info (lpSystemInfo);
1131 }
1132 else
1133 lpSystemInfo->dwNumberOfProcessors = -1;
1134 }
1135
1136 static BOOL WINAPI
1137 get_system_times (LPFILETIME lpIdleTime,
1138 LPFILETIME lpKernelTime,
1139 LPFILETIME lpUserTime)
1140 {
1141 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
1142 if (is_windows_9x () == TRUE)
1143 {
1144 return FALSE;
1145 }
1146 if (g_b_init_get_system_times == 0)
1147 {
1148 g_b_init_get_system_times = 1;
1149 s_pfn_Get_System_times =
1150 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1151 "GetSystemTimes");
1152 }
1153 if (s_pfn_Get_System_times == NULL)
1154 return FALSE;
1155 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
1156 }
1157
1158 static BOOLEAN WINAPI
1159 create_symbolic_link (LPCSTR lpSymlinkFilename,
1160 LPCSTR lpTargetFileName,
1161 DWORD dwFlags)
1162 {
1163 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
1164 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1165 BOOLEAN retval;
1166
1167 if (is_windows_9x () == TRUE)
1168 {
1169 errno = ENOSYS;
1170 return 0;
1171 }
1172 if (w32_unicode_filenames)
1173 {
1174 wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];
1175
1176 if (g_b_init_create_symbolic_link_w == 0)
1177 {
1178 g_b_init_create_symbolic_link_w = 1;
1179 s_pfn_Create_Symbolic_LinkW =
1180 (CreateSymbolicLinkW_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1181 "CreateSymbolicLinkW");
1182 }
1183 if (s_pfn_Create_Symbolic_LinkW == NULL)
1184 {
1185 errno = ENOSYS;
1186 return 0;
1187 }
1188
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)
1195 {
1196 TOKEN_PRIVILEGES priv_current;
1197
1198 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1199 &priv_current))
1200 {
1201 retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
1202 restore_privilege (&priv_current);
1203 revert_to_self ();
1204 }
1205 }
1206 }
1207 else
1208 {
1209 char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1210
1211 if (g_b_init_create_symbolic_link_a == 0)
1212 {
1213 g_b_init_create_symbolic_link_a = 1;
1214 s_pfn_Create_Symbolic_LinkA =
1215 (CreateSymbolicLinkA_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1216 "CreateSymbolicLinkA");
1217 }
1218 if (s_pfn_Create_Symbolic_LinkA == NULL)
1219 {
1220 errno = ENOSYS;
1221 return 0;
1222 }
1223
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)
1230 {
1231 TOKEN_PRIVILEGES priv_current;
1232
1233 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
1234 &priv_current))
1235 {
1236 retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
1237 restore_privilege (&priv_current);
1238 revert_to_self ();
1239 }
1240 }
1241 }
1242 return retval;
1243 }
1244
1245 static BOOL WINAPI
1246 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1247 {
1248 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1249
1250 if (is_windows_9x () == TRUE)
1251 {
1252 errno = ENOTSUP;
1253 return FALSE;
1254 }
1255
1256 if (g_b_init_is_valid_security_descriptor == 0)
1257 {
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");
1262 }
1263 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1264 {
1265 errno = ENOTSUP;
1266 return FALSE;
1267 }
1268
1269 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1270 }
1271
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)
1278 {
1279 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1280 BOOL retval;
1281
1282 if (is_windows_9x () == TRUE)
1283 {
1284 errno = ENOTSUP;
1285 return FALSE;
1286 }
1287
1288 if (g_b_init_convert_sd_to_sddl == 0)
1289 {
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
1300 }
1301 if (s_pfn_Convert_SD_To_SDDL == NULL)
1302 {
1303 errno = ENOTSUP;
1304 return FALSE;
1305 }
1306
1307 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1308 RequestedStringSDRevision,
1309 SecurityInformation,
1310 StringSecurityDescriptor,
1311 StringSecurityDescriptorLen);
1312
1313 return retval;
1314 }
1315
1316 static BOOL WINAPI
1317 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1318 DWORD StringSDRevision,
1319 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1320 PULONG SecurityDescriptorSize)
1321 {
1322 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1323 BOOL retval;
1324
1325 if (is_windows_9x () == TRUE)
1326 {
1327 errno = ENOTSUP;
1328 return FALSE;
1329 }
1330
1331 if (g_b_init_convert_sddl_to_sd == 0)
1332 {
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
1343 }
1344 if (s_pfn_Convert_SDDL_To_SD == NULL)
1345 {
1346 errno = ENOTSUP;
1347 return FALSE;
1348 }
1349
1350 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1351 StringSDRevision,
1352 SecurityDescriptor,
1353 SecurityDescriptorSize);
1354
1355 return retval;
1356 }
1357
1358 static DWORD WINAPI
1359 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1360 {
1361 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1362 HMODULE hm_iphlpapi = NULL;
1363
1364 if (is_windows_9x () == TRUE)
1365 return ERROR_NOT_SUPPORTED;
1366
1367 if (g_b_init_get_adapters_info == 0)
1368 {
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");
1374 }
1375 if (s_pfn_Get_Adapters_Info == NULL)
1376 return ERROR_NOT_SUPPORTED;
1377 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1378 }
1379
1380 \f
1381
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.
1384
1385 This is called from alloc.c:valid_pointer_p. */
1386 int
1387 w32_valid_pointer_p (void *p, int size)
1388 {
1389 SIZE_T done;
1390 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1391
1392 if (h)
1393 {
1394 unsigned char *buf = alloca (size);
1395 int retval = ReadProcessMemory (h, p, buf, size, &done);
1396
1397 CloseHandle (h);
1398 return retval;
1399 }
1400 else
1401 return -1;
1402 }
1403
1404 \f
1405
1406 /* Here's an overview of how the Windows build supports file names
1407 that cannot be encoded by the current system codepage.
1408
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!)
1418
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).
1427
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.)
1440
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.
1448
1449 This arrangement works very well, but it has a few gotchas and
1450 limitations:
1451
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.
1457
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.
1462
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.
1467
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.
1473
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.
1483
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.
1497
1498 . For similar reasons, server.el and emacsclient are also limited
1499 to the current ANSI codepage for now.
1500
1501 . Emacs itself can only handle command-line arguments encoded in
1502 the current codepage.
1503
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. */
1507
1508 \f
1509
1510 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1511 codepage defined by file-name-coding-system. */
1512
1513 /* Current codepage for encoding file names. */
1514 static int file_name_codepage;
1515
1516 /* Produce a Windows ANSI codepage suitable for encoding file names.
1517 Return the information about that codepage in CP_INFO. */
1518 int
1519 codepage_for_filenames (CPINFO *cp_info)
1520 {
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;
1527
1528 current_encoding = Vfile_name_coding_system;
1529 if (NILP (current_encoding))
1530 current_encoding = Vdefault_file_name_coding_system;
1531
1532 if (!EQ (last_file_name_encoding, current_encoding))
1533 {
1534 /* Default to the current ANSI codepage. */
1535 file_name_codepage = w32_ansi_code_page;
1536
1537 if (NILP (current_encoding))
1538 {
1539 char *cpname = SSDATA (SYMBOL_NAME (current_encoding));
1540 char *cp = NULL, *end;
1541 int cpnum;
1542
1543 if (strncmp (cpname, "cp", 2) == 0)
1544 cp = cpname + 2;
1545 else if (strncmp (cpname, "windows-", 8) == 0)
1546 cp = cpname + 8;
1547
1548 if (cp)
1549 {
1550 end = cp;
1551 cpnum = strtol (cp, &end, 10);
1552 if (cpnum && *end == '\0' && end - cp >= 2)
1553 file_name_codepage = cpnum;
1554 }
1555 }
1556
1557 if (!file_name_codepage)
1558 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1559
1560 if (!GetCPInfo (file_name_codepage, &cp))
1561 {
1562 file_name_codepage = CP_ACP;
1563 if (!GetCPInfo (file_name_codepage, &cp))
1564 emacs_abort ();
1565 }
1566 }
1567 if (cp_info)
1568 *cp_info = cp;
1569
1570 return file_name_codepage;
1571 }
1572
1573 int
1574 filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1575 {
1576 int result = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, fn_in,
1577 -1, fn_out, MAX_PATH);
1578
1579 if (!result)
1580 {
1581 DWORD err = GetLastError ();
1582
1583 switch (err)
1584 {
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;
1594 }
1595 return -1;
1596 }
1597 return 0;
1598 }
1599
1600 int
1601 filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1602 {
1603 int result = pWideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1604 fn_out, MAX_UTF8_PATH, NULL, NULL);
1605
1606 if (!result)
1607 {
1608 DWORD err = GetLastError ();
1609
1610 switch (err)
1611 {
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;
1621 }
1622 return -1;
1623 }
1624 return 0;
1625 }
1626
1627 int
1628 filename_to_ansi (const char *fn_in, char *fn_out)
1629 {
1630 wchar_t fn_utf16[MAX_PATH];
1631
1632 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1633 {
1634 int result;
1635 int codepage = codepage_for_filenames (NULL);
1636
1637 result = pWideCharToMultiByte (codepage, 0, fn_utf16, -1,
1638 fn_out, MAX_PATH, NULL, NULL);
1639 if (!result)
1640 {
1641 DWORD err = GetLastError ();
1642
1643 switch (err)
1644 {
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;
1654 }
1655 return -1;
1656 }
1657 return 0;
1658 }
1659 return -1;
1660 }
1661
1662 int
1663 filename_from_ansi (const char *fn_in, char *fn_out)
1664 {
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);
1669
1670 if (!result)
1671 {
1672 DWORD err = GetLastError ();
1673
1674 switch (err)
1675 {
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;
1685 }
1686 return -1;
1687 }
1688 return filename_from_utf16 (fn_utf16, fn_out);
1689 }
1690
1691 \f
1692
1693 /* The directory where we started, in UTF-8. */
1694 static char startup_dir[MAX_UTF8_PATH];
1695
1696 /* Get the current working directory. */
1697 char *
1698 getcwd (char *dir, int dirsize)
1699 {
1700 if (!dirsize)
1701 {
1702 errno = EINVAL;
1703 return NULL;
1704 }
1705 if (dirsize <= strlen (startup_dir))
1706 {
1707 errno = ERANGE;
1708 return NULL;
1709 }
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
1720 }
1721
1722 /* Emulate getloadavg. */
1723
1724 struct load_sample {
1725 time_t sample_time;
1726 ULONGLONG idle;
1727 ULONGLONG kernel;
1728 ULONGLONG user;
1729 };
1730
1731 /* Number of processors on this machine. */
1732 static unsigned num_of_processors;
1733
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);
1738
1739 static int
1740 buf_next (int from)
1741 {
1742 int next_idx = from + 1;
1743
1744 if (next_idx >= max_idx)
1745 next_idx = 0;
1746
1747 return next_idx;
1748 }
1749
1750 static int
1751 buf_prev (int from)
1752 {
1753 int prev_idx = from - 1;
1754
1755 if (prev_idx < 0)
1756 prev_idx = max_idx - 1;
1757
1758 return prev_idx;
1759 }
1760
1761 static void
1762 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1763 {
1764 SYSTEM_INFO sysinfo;
1765 FILETIME ft_idle, ft_user, ft_kernel;
1766
1767 /* Initialize the number of processors on this machine. */
1768 if (num_of_processors <= 0)
1769 {
1770 get_native_system_info (&sysinfo);
1771 num_of_processors = sysinfo.dwNumberOfProcessors;
1772 if (num_of_processors <= 0)
1773 {
1774 GetSystemInfo (&sysinfo);
1775 num_of_processors = sysinfo.dwNumberOfProcessors;
1776 }
1777 if (num_of_processors <= 0)
1778 num_of_processors = 1;
1779 }
1780
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. */
1785
1786 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1787 {
1788 ULARGE_INTEGER uidle, ukernel, uuser;
1789
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;
1796 }
1797 else
1798 {
1799 *idle = 0;
1800 *kernel = 0;
1801 *user = 0;
1802 }
1803 }
1804
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)
1810 {
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;
1816
1817 if (first_idx != last_idx)
1818 {
1819 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1820 {
1821 tdiff = difftime (now, samples[idx].sample_time);
1822 if (tdiff >= span - 2*DBL_EPSILON*now)
1823 {
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;
1828
1829 retval = (1.0 - idl / sys) * num_of_processors;
1830 break;
1831 }
1832 if (idx == first_idx)
1833 break;
1834 }
1835 }
1836
1837 return retval;
1838 }
1839
1840 int
1841 getloadavg (double loadavg[], int nelem)
1842 {
1843 int elem;
1844 ULONGLONG idle, kernel, user;
1845 time_t now = time (NULL);
1846
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)
1852 {
1853 while (difftime (now, samples[last_idx].sample_time) < -1.0)
1854 {
1855 if (last_idx == first_idx)
1856 {
1857 first_idx = last_idx = -1;
1858 break;
1859 }
1860 last_idx = buf_prev (last_idx);
1861 }
1862 }
1863
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))
1869 {
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);
1884 }
1885
1886 for (elem = 0; elem < nelem; elem++)
1887 {
1888 double avg = getavg (elem);
1889
1890 if (avg < 0)
1891 break;
1892 loadavg[elem] = avg;
1893 }
1894
1895 return elem;
1896 }
1897
1898 /* Emulate getpwuid, getpwnam and others. */
1899
1900 #define PASSWD_FIELD_SIZE 256
1901
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];
1907
1908 static struct passwd dflt_passwd =
1909 {
1910 dflt_passwd_name,
1911 dflt_passwd_passwd,
1912 0,
1913 0,
1914 0,
1915 dflt_passwd_gecos,
1916 dflt_passwd_dir,
1917 dflt_passwd_shell,
1918 };
1919
1920 static char dflt_group_name[GNLEN+1];
1921
1922 static struct group dflt_group =
1923 {
1924 /* When group information is not available, we return this as the
1925 group for all files. */
1926 dflt_group_name,
1927 0,
1928 };
1929
1930 unsigned
1931 getuid (void)
1932 {
1933 return dflt_passwd.pw_uid;
1934 }
1935
1936 unsigned
1937 geteuid (void)
1938 {
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 ();
1943 }
1944
1945 unsigned
1946 getgid (void)
1947 {
1948 return dflt_passwd.pw_gid;
1949 }
1950
1951 unsigned
1952 getegid (void)
1953 {
1954 return getgid ();
1955 }
1956
1957 struct passwd *
1958 getpwuid (unsigned uid)
1959 {
1960 if (uid == dflt_passwd.pw_uid)
1961 return &dflt_passwd;
1962 return NULL;
1963 }
1964
1965 struct group *
1966 getgrgid (gid_t gid)
1967 {
1968 return &dflt_group;
1969 }
1970
1971 struct passwd *
1972 getpwnam (char *name)
1973 {
1974 struct passwd *pw;
1975
1976 pw = getpwuid (getuid ());
1977 if (!pw)
1978 return pw;
1979
1980 if (xstrcasecmp (name, pw->pw_name))
1981 return NULL;
1982
1983 return pw;
1984 }
1985
1986 static void
1987 init_user_info (void)
1988 {
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.
1991
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). */
1995
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;
2006
2007 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
2008 if (result)
2009 {
2010 result = get_token_information (token, TokenUser, NULL, 0, &blen);
2011 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
2012 {
2013 buf = xmalloc (blen);
2014 result = get_token_information (token, TokenUser,
2015 (LPVOID)buf, blen, &needed);
2016 if (result)
2017 {
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);
2022 }
2023 }
2024 else
2025 result = FALSE;
2026 }
2027 if (result)
2028 {
2029 strcpy (dflt_passwd.pw_name, uname);
2030 /* Determine a reasonable uid value. */
2031 if (xstrcasecmp ("administrator", uname) == 0)
2032 {
2033 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
2034 dflt_passwd.pw_gid = 513; /* well-known None gid */
2035 }
2036 else
2037 {
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);
2041
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)
2046 {
2047 buf = xrealloc (buf, blen = needed);
2048 result = get_token_information (token, TokenPrimaryGroup,
2049 (LPVOID)buf, blen, &needed);
2050 }
2051 if (result)
2052 {
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);
2063 }
2064 else
2065 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
2066 }
2067 }
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))
2071 {
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;
2078 }
2079 else
2080 {
2081 strcpy (dflt_passwd.pw_name, "unknown");
2082 dflt_passwd.pw_uid = 123;
2083 dflt_passwd.pw_gid = 123;
2084 }
2085 dflt_group.gr_gid = dflt_passwd.pw_gid;
2086
2087 /* Set dir and shell from environment variables. */
2088 if (w32_unicode_filenames)
2089 {
2090 wchar_t *home = _wgetenv (L"HOME");
2091 wchar_t *shell = _wgetenv (L"SHELL");
2092
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);
2100 }
2101 else
2102 {
2103 char *home = getenv ("HOME");
2104 char *shell = getenv ("SHELL");
2105
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);
2112 }
2113
2114 xfree (buf);
2115 if (token)
2116 CloseHandle (token);
2117 }
2118
2119 static HCRYPTPROV w32_crypto_hprov;
2120 static int
2121 w32_init_crypt_random (void)
2122 {
2123 if (!CryptAcquireContext (&w32_crypto_hprov, NULL, NULL, PROV_RSA_FULL,
2124 CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
2125 {
2126 DebPrint (("CryptAcquireContext failed with error %x\n",
2127 GetLastError ()));
2128 w32_crypto_hprov = 0;
2129 return -1;
2130 }
2131 return 0;
2132 }
2133
2134 int
2135 w32_init_random (void *buf, ptrdiff_t buflen)
2136 {
2137 if (!w32_crypto_hprov)
2138 w32_init_crypt_random ();
2139 if (w32_crypto_hprov)
2140 {
2141 if (CryptGenRandom (w32_crypto_hprov, buflen, (BYTE *)buf))
2142 return 0;
2143 }
2144 return -1;
2145 }
2146
2147 int
2148 random (void)
2149 {
2150 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2151 return ((rand () << 15) | rand ());
2152 }
2153
2154 void
2155 srandom (int seed)
2156 {
2157 srand (seed);
2158 }
2159
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)
2165 {
2166 CPINFO cp_info;
2167
2168 codepage_for_filenames (&cp_info);
2169 return cp_info.MaxCharSize;
2170 }
2171
2172 /* Normalize filename by converting in-place all of its path
2173 separators to the separator specified by PATH_SEP. */
2174
2175 static void
2176 normalize_filename (register char *fp, char path_sep)
2177 {
2178 char *p2;
2179
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;
2186
2187 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
2188 {
2189 *fp += 'a' - 'A';
2190 fp += 2;
2191 }
2192
2193 while (*fp)
2194 {
2195 if ((*fp == '/' || *fp == '\\') && *fp != path_sep)
2196 *fp = path_sep;
2197 fp++;
2198 }
2199 }
2200
2201 /* Destructively turn backslashes into slashes. */
2202 void
2203 dostounix_filename (register char *p)
2204 {
2205 normalize_filename (p, '/');
2206 }
2207
2208 /* Destructively turn slashes into backslashes. */
2209 void
2210 unixtodos_filename (register char *p)
2211 {
2212 normalize_filename (p, '\\');
2213 }
2214
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)
2220 {
2221 unsigned char *np = (unsigned char *)buf;
2222 unsigned char *startp = np;
2223 char *endp = buf + n;
2224
2225 if (n == 0)
2226 return n;
2227 while (buf < endp - 1)
2228 {
2229 if (*buf == 0x0d)
2230 {
2231 if (*(++buf) != 0x0a)
2232 *np++ = 0x0d;
2233 }
2234 else
2235 *np++ = *buf++;
2236 }
2237 if (buf < endp)
2238 *np++ = *buf++;
2239 return np - startp;
2240 }
2241
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)
2246 {
2247 const char * start = name;
2248
2249 if (name == NULL)
2250 return 0;
2251
2252 /* find the root name of the volume if given */
2253 if (isalpha (name[0]) && name[1] == ':')
2254 {
2255 /* skip past drive specifier */
2256 name += 2;
2257 if (IS_DIRECTORY_SEP (name[0]))
2258 name++;
2259 }
2260 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2261 {
2262 int slashes = 2;
2263
2264 name += 2;
2265 do
2266 {
2267 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2268 break;
2269 name++;
2270 }
2271 while ( *name );
2272 if (IS_DIRECTORY_SEP (name[0]))
2273 name++;
2274 }
2275
2276 if (pPath)
2277 *pPath = name;
2278
2279 return name - start;
2280 }
2281
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)
2285 {
2286 HANDLE dir_handle = INVALID_HANDLE_VALUE;
2287 char fname_utf8[MAX_UTF8_PATH];
2288 int len = 0;
2289 int cstatus = -1;
2290
2291 /* Must be valid filename, no wild cards or other invalid characters. */
2292 if (strpbrk (name, "*?|<>\""))
2293 return 0;
2294
2295 if (w32_unicode_filenames)
2296 {
2297 wchar_t fname_utf16[MAX_PATH];
2298 WIN32_FIND_DATAW find_data_wide;
2299
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);
2304 }
2305 else
2306 {
2307 char fname_ansi[MAX_PATH];
2308 WIN32_FIND_DATAA find_data_ansi;
2309
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, "?"))
2317 {
2318 /* Find the basename of fname_ansi. */
2319 char *p = strrchr (fname_ansi, '\\');
2320
2321 if (!p)
2322 p = fname_ansi;
2323 else
2324 p++;
2325 cstatus = filename_from_ansi (p, fname_utf8);
2326 }
2327 else
2328 {
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);
2332 }
2333 }
2334
2335 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
2336 memcpy (buf, fname_utf8, len + 1);
2337 else
2338 len = 0;
2339
2340 if (dir_handle != INVALID_HANDLE_VALUE)
2341 FindClose (dir_handle);
2342
2343 return len;
2344 }
2345
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)
2349 {
2350 char * o = buf;
2351 char * p;
2352 const char * q;
2353 char full[ MAX_UTF8_PATH ];
2354 int len;
2355
2356 len = strlen (name);
2357 if (len >= MAX_UTF8_PATH)
2358 return FALSE;
2359
2360 /* Use local copy for destructive modification. */
2361 memcpy (full, name, len+1);
2362 unixtodos_filename (full);
2363
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;
2370
2371 while (p != NULL && *p)
2372 {
2373 q = p;
2374 p = strchr (q, '\\');
2375 if (p) *p = '\0';
2376 len = get_long_basename (full, o, size);
2377 if (len > 0)
2378 {
2379 o += len;
2380 size -= len;
2381 if (p != NULL)
2382 {
2383 *p++ = '\\';
2384 if (size < 2)
2385 return FALSE;
2386 *o++ = '\\';
2387 size--;
2388 *o = '\0';
2389 }
2390 }
2391 else
2392 return FALSE;
2393 }
2394
2395 return TRUE;
2396 }
2397
2398 unsigned int
2399 w32_get_short_filename (const char * name, char * buf, int size)
2400 {
2401 if (w32_unicode_filenames)
2402 {
2403 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2404 unsigned int retval;
2405
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;
2411 }
2412 else
2413 {
2414 char name_ansi[MAX_PATH];
2415
2416 filename_to_ansi (name, name_ansi);
2417 return GetShortPathNameA (name_ansi, buf, size);
2418 }
2419 }
2420
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. */
2428
2429 Lisp_Object
2430 ansi_encode_filename (Lisp_Object filename)
2431 {
2432 Lisp_Object encoded_filename;
2433 char fname[MAX_PATH];
2434
2435 filename_to_ansi (SSDATA (filename), fname);
2436 if (_mbspbrk (fname, "?"))
2437 {
2438 char shortname[MAX_PATH];
2439
2440 if (w32_get_short_filename (SSDATA (filename), shortname, MAX_PATH))
2441 {
2442 dostounix_filename (shortname);
2443 encoded_filename = build_string (shortname);
2444 }
2445 else
2446 encoded_filename = build_unibyte_string (fname);
2447 }
2448 else
2449 encoded_filename = build_unibyte_string (fname);
2450 return encoded_filename;
2451 }
2452
2453 static int
2454 is_unc_volume (const char *filename)
2455 {
2456 const char *ptr = filename;
2457
2458 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2459 return 0;
2460
2461 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
2462 return 0;
2463
2464 return 1;
2465 }
2466
2467 /* Emulate the Posix unsetenv. */
2468 int
2469 unsetenv (const char *name)
2470 {
2471 char *var;
2472 size_t name_len;
2473
2474 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2475 {
2476 errno = EINVAL;
2477 return -1;
2478 }
2479 name_len = strlen (name);
2480 /* MS docs says an environment variable cannot be longer than 32K. */
2481 if (name_len > 32767)
2482 {
2483 errno = ENOMEM;
2484 return 0;
2485 }
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);
2493 }
2494
2495 /* MS _putenv doesn't support removing a variable when the argument
2496 does not include the '=' character, so we fix that here. */
2497 int
2498 sys_putenv (char *str)
2499 {
2500 const char *const name_end = strchr (str, '=');
2501
2502 if (name_end == NULL)
2503 {
2504 /* Remove the variable from the environment. */
2505 return unsetenv (str);
2506 }
2507
2508 return _putenv (str);
2509 }
2510
2511 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2512
2513 LPBYTE
2514 w32_get_resource (const char *key, LPDWORD lpdwtype)
2515 {
2516 LPBYTE lpvalue;
2517 HKEY hrootkey = NULL;
2518 DWORD cbData;
2519
2520 /* Check both the current user and the local machine to see if
2521 we have any resources. */
2522
2523 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2524 {
2525 lpvalue = NULL;
2526
2527 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2528 && (lpvalue = xmalloc (cbData)) != NULL
2529 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2530 {
2531 RegCloseKey (hrootkey);
2532 return (lpvalue);
2533 }
2534
2535 xfree (lpvalue);
2536
2537 RegCloseKey (hrootkey);
2538 }
2539
2540 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2541 {
2542 lpvalue = NULL;
2543
2544 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
2545 && (lpvalue = xmalloc (cbData)) != NULL
2546 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2547 {
2548 RegCloseKey (hrootkey);
2549 return (lpvalue);
2550 }
2551
2552 xfree (lpvalue);
2553
2554 RegCloseKey (hrootkey);
2555 }
2556
2557 return (NULL);
2558 }
2559
2560 /* The argv[] array holds ANSI-encoded strings, and so this function
2561 works with ANS_encoded strings. */
2562 void
2563 init_environment (char ** argv)
2564 {
2565 static const char * const tempdirs[] = {
2566 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2567 };
2568
2569 int i;
2570
2571 const int imax = ARRAYELTS (tempdirs);
2572
2573 /* Implementation note: This function explicitly works with ANSI
2574 file names, not with UTF-8 encoded file names. This is because
2575 this function pushes variables into the Emacs's environment, and
2576 the environment variables are always assumed to be in the
2577 locale-specific encoding. Do NOT call any functions that accept
2578 UTF-8 file names from this function! */
2579
2580 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2581 temporary files and assume "/tmp" if $TMPDIR is unset, which
2582 will break on DOS/Windows. Refuse to work if we cannot find
2583 a directory, not even "c:/", usable for that purpose. */
2584 for (i = 0; i < imax ; i++)
2585 {
2586 const char *tmp = tempdirs[i];
2587
2588 if (*tmp == '$')
2589 tmp = getenv (tmp + 1);
2590 /* Note that `access' can lie to us if the directory resides on a
2591 read-only filesystem, like CD-ROM or a write-protected floppy.
2592 The only way to be really sure is to actually create a file and
2593 see if it succeeds. But I think that's too much to ask. */
2594
2595 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2596 if (tmp && sys_access (tmp, D_OK) == 0)
2597 {
2598 char * var = alloca (strlen (tmp) + 8);
2599 sprintf (var, "TMPDIR=%s", tmp);
2600 _putenv (strdup (var));
2601 break;
2602 }
2603 }
2604 if (i >= imax)
2605 cmd_error_internal
2606 (Fcons (Qerror,
2607 Fcons (build_string ("no usable temporary directories found!!"),
2608 Qnil)),
2609 "While setting TMPDIR: ");
2610
2611 /* Check for environment variables and use registry settings if they
2612 don't exist. Fallback on default values where applicable. */
2613 {
2614 int i;
2615 LPBYTE lpval;
2616 DWORD dwType;
2617 char locale_name[32];
2618 char default_home[MAX_PATH];
2619 int appdata = 0;
2620
2621 static const struct env_entry
2622 {
2623 const char * name;
2624 const char * def_value;
2625 } dflt_envvars[] =
2626 {
2627 /* If the default value is NULL, we will use the value from the
2628 outside environment or the Registry, but will not push the
2629 variable into the Emacs environment if it is defined neither
2630 in the Registry nor in the outside environment. */
2631 {"HOME", "C:/"},
2632 {"PRELOAD_WINSOCK", NULL},
2633 {"emacs_dir", "C:/emacs"},
2634 {"EMACSLOADPATH", NULL},
2635 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2636 {"EMACSDATA", NULL},
2637 {"EMACSPATH", NULL},
2638 {"INFOPATH", NULL},
2639 {"EMACSDOC", NULL},
2640 {"TERM", "cmd"},
2641 {"LANG", NULL},
2642 };
2643
2644 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2645
2646 /* We need to copy dflt_envvars[] and work on the copy because we
2647 don't want the dumped Emacs to inherit the values of
2648 environment variables we saw during dumping (which could be on
2649 a different system). The defaults above must be left intact. */
2650 struct env_entry env_vars[N_ENV_VARS];
2651
2652 for (i = 0; i < N_ENV_VARS; i++)
2653 env_vars[i] = dflt_envvars[i];
2654
2655 /* For backwards compatibility, check if a .emacs file exists in C:/
2656 If not, then we can try to default to the appdata directory under the
2657 user's profile, which is more likely to be writable. */
2658 if (sys_access ("C:/.emacs", F_OK) != 0)
2659 {
2660 HRESULT profile_result;
2661 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2662 of Windows 95 and NT4 that have not been updated to include
2663 MSIE 5. */
2664 ShGetFolderPath_fn get_folder_path;
2665 get_folder_path = (ShGetFolderPath_fn)
2666 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2667
2668 if (get_folder_path != NULL)
2669 {
2670 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2671 0, default_home);
2672
2673 /* If we can't get the appdata dir, revert to old behavior. */
2674 if (profile_result == S_OK)
2675 {
2676 env_vars[0].def_value = default_home;
2677 appdata = 1;
2678 }
2679 }
2680 }
2681
2682 /* Get default locale info and use it for LANG. */
2683 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2684 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2685 locale_name, sizeof (locale_name)))
2686 {
2687 for (i = 0; i < N_ENV_VARS; i++)
2688 {
2689 if (strcmp (env_vars[i].name, "LANG") == 0)
2690 {
2691 env_vars[i].def_value = locale_name;
2692 break;
2693 }
2694 }
2695 }
2696
2697 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2698
2699 /* Treat emacs_dir specially: set it unconditionally based on our
2700 location. */
2701 {
2702 char *p;
2703 char modname[MAX_PATH];
2704
2705 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2706 emacs_abort ();
2707 if ((p = _mbsrchr (modname, '\\')) == NULL)
2708 emacs_abort ();
2709 *p = 0;
2710
2711 if ((p = _mbsrchr (modname, '\\'))
2712 /* From bin means installed Emacs, from src means uninstalled. */
2713 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2714 {
2715 char buf[SET_ENV_BUF_SIZE];
2716 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2717
2718 *p = 0;
2719 for (p = modname; *p; p = CharNext (p))
2720 if (*p == '\\') *p = '/';
2721
2722 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2723 _putenv (strdup (buf));
2724 /* If we are running from the Posix-like build tree, define
2725 SHELL to point to our own cmdproxy. The loop below will
2726 then disregard PATH_EXEC and the default value. */
2727 if (within_build_tree)
2728 {
2729 _snprintf (buf, sizeof (buf) - 1,
2730 "SHELL=%s/nt/cmdproxy.exe", modname);
2731 _putenv (strdup (buf));
2732 }
2733 }
2734 }
2735
2736 for (i = 0; i < N_ENV_VARS; i++)
2737 {
2738 if (!getenv (env_vars[i].name))
2739 {
2740 int dont_free = 0;
2741 char bufc[SET_ENV_BUF_SIZE];
2742
2743 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2744 /* Also ignore empty environment variables. */
2745 || *lpval == 0)
2746 {
2747 xfree (lpval);
2748 dont_free = 1;
2749 if (strcmp (env_vars[i].name, "SHELL") == 0)
2750 {
2751 /* Look for cmdproxy.exe in every directory in
2752 PATH_EXEC. FIXME: This does not find cmdproxy
2753 in nt/ when we run uninstalled. */
2754 char fname[MAX_PATH];
2755 const char *pstart = PATH_EXEC, *pend;
2756
2757 do {
2758 pend = _mbschr (pstart, ';');
2759 if (!pend)
2760 pend = pstart + strlen (pstart);
2761 /* Be defensive against series of ;;; characters. */
2762 if (pend > pstart)
2763 {
2764 strncpy (fname, pstart, pend - pstart);
2765 fname[pend - pstart] = '/';
2766 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2767 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2768 sizeof (bufc));
2769 if (sys_access (bufc, F_OK) == 0)
2770 {
2771 lpval = bufc;
2772 dwType = REG_SZ;
2773 break;
2774 }
2775 }
2776 if (*pend)
2777 pstart = pend + 1;
2778 else
2779 pstart = pend;
2780 if (!*pstart)
2781 {
2782 /* If not found in any directory, use the
2783 default as the last resort. */
2784 lpval = (char *)env_vars[i].def_value;
2785 dwType = REG_EXPAND_SZ;
2786 }
2787 } while (*pstart);
2788 }
2789 else
2790 {
2791 lpval = (char *)env_vars[i].def_value;
2792 dwType = REG_EXPAND_SZ;
2793 }
2794 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2795 Vdelayed_warnings_list
2796 = Fcons (listn (CONSTYPE_HEAP, 2,
2797 intern ("initialization"),
2798 build_string ("Setting HOME to C:\\ by default is deprecated")),
2799 Vdelayed_warnings_list);
2800 }
2801
2802 if (lpval)
2803 {
2804 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2805
2806 if (dwType == REG_EXPAND_SZ)
2807 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2808 else if (dwType == REG_SZ)
2809 strcpy (buf1, (char *)lpval);
2810 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2811 {
2812 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2813 buf1);
2814 _putenv (strdup (buf2));
2815 }
2816
2817 if (!dont_free)
2818 xfree (lpval);
2819 }
2820 }
2821 }
2822 }
2823
2824 /* Rebuild system configuration to reflect invoking system. */
2825 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2826
2827 /* Another special case: on NT, the PATH variable is actually named
2828 "Path" although cmd.exe (perhaps NT itself) arranges for
2829 environment variable lookup and setting to be case insensitive.
2830 However, Emacs assumes a fully case sensitive environment, so we
2831 need to change "Path" to "PATH" to match the expectations of
2832 various elisp packages. We do this by the sneaky method of
2833 modifying the string in the C runtime environ entry.
2834
2835 The same applies to COMSPEC. */
2836 {
2837 char ** envp;
2838
2839 for (envp = environ; *envp; envp++)
2840 if (_strnicmp (*envp, "PATH=", 5) == 0)
2841 memcpy (*envp, "PATH=", 5);
2842 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2843 memcpy (*envp, "COMSPEC=", 8);
2844 }
2845
2846 /* Remember the initial working directory for getcwd. */
2847 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2848 Does it matter anywhere in Emacs? */
2849 if (w32_unicode_filenames)
2850 {
2851 wchar_t wstartup_dir[MAX_PATH];
2852
2853 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2854 emacs_abort ();
2855 filename_from_utf16 (wstartup_dir, startup_dir);
2856 }
2857 else
2858 {
2859 char astartup_dir[MAX_PATH];
2860
2861 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2862 emacs_abort ();
2863 filename_from_ansi (astartup_dir, startup_dir);
2864 }
2865
2866 {
2867 static char modname[MAX_PATH];
2868
2869 if (!GetModuleFileNameA (NULL, modname, MAX_PATH))
2870 emacs_abort ();
2871 argv[0] = modname;
2872 }
2873
2874 /* Determine if there is a middle mouse button, to allow parse_button
2875 to decide whether right mouse events should be mouse-2 or
2876 mouse-3. */
2877 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2878
2879 init_user_info ();
2880 }
2881
2882 /* Called from expand-file-name when default-directory is not a string. */
2883
2884 char *
2885 emacs_root_dir (void)
2886 {
2887 static char root_dir[MAX_UTF8_PATH];
2888 const char *p;
2889
2890 p = getenv ("emacs_dir");
2891 if (p == NULL)
2892 emacs_abort ();
2893 filename_from_ansi (p, root_dir);
2894 root_dir[parse_root (root_dir, NULL)] = '\0';
2895 dostounix_filename (root_dir);
2896 return root_dir;
2897 }
2898
2899 #include <sys/timeb.h>
2900
2901 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2902 int
2903 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2904 {
2905 struct _timeb tb;
2906 _ftime (&tb);
2907
2908 tv->tv_sec = tb.time;
2909 tv->tv_usec = tb.millitm * 1000L;
2910 /* Implementation note: _ftime sometimes doesn't update the dstflag
2911 according to the new timezone when the system timezone is
2912 changed. We could fix that by using GetSystemTime and
2913 GetTimeZoneInformation, but that doesn't seem necessary, since
2914 Emacs always calls gettimeofday with the 2nd argument NULL (see
2915 current_emacs_time). */
2916 if (tz)
2917 {
2918 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2919 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2920 }
2921 return 0;
2922 }
2923
2924 /* Emulate fdutimens. */
2925
2926 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2927 TIMESPEC[0] and TIMESPEC[1], respectively.
2928 FD must be either negative -- in which case it is ignored --
2929 or a file descriptor that is open on FILE.
2930 If FD is nonnegative, then FILE can be NULL, which means
2931 use just futimes instead of utimes.
2932 If TIMESPEC is null, FAIL.
2933 Return 0 on success, -1 (setting errno) on failure. */
2934
2935 int
2936 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2937 {
2938 if (!timespec)
2939 {
2940 errno = ENOSYS;
2941 return -1;
2942 }
2943 if (fd < 0 && !file)
2944 {
2945 errno = EBADF;
2946 return -1;
2947 }
2948 /* _futime's prototype defines 2nd arg as having the type 'struct
2949 _utimbuf', while utime needs to accept 'struct utimbuf' for
2950 compatibility with Posix. So we need to use 2 different (but
2951 equivalent) types to avoid compiler warnings, sigh. */
2952 if (fd >= 0)
2953 {
2954 struct _utimbuf _ut;
2955
2956 _ut.actime = timespec[0].tv_sec;
2957 _ut.modtime = timespec[1].tv_sec;
2958 return _futime (fd, &_ut);
2959 }
2960 else
2961 {
2962 struct utimbuf ut;
2963
2964 ut.actime = timespec[0].tv_sec;
2965 ut.modtime = timespec[1].tv_sec;
2966 /* Call 'utime', which is implemented below, not the MS library
2967 function, which fails on directories. */
2968 return utime (file, &ut);
2969 }
2970 }
2971
2972
2973 /* ------------------------------------------------------------------------- */
2974 /* IO support and wrapper functions for the Windows API. */
2975 /* ------------------------------------------------------------------------- */
2976
2977 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2978 on network directories, so we handle that case here.
2979 (Ulrich Leodolter, 1/11/95). */
2980 char *
2981 sys_ctime (const time_t *t)
2982 {
2983 char *str = (char *) ctime (t);
2984 return (str ? str : (char *)"Sun Jan 01 00:00:00 1970");
2985 }
2986
2987 /* Emulate sleep...we could have done this with a define, but that
2988 would necessitate including windows.h in the files that used it.
2989 This is much easier. */
2990 void
2991 sys_sleep (int seconds)
2992 {
2993 Sleep (seconds * 1000);
2994 }
2995
2996 /* Internal MSVC functions for low-level descriptor munging */
2997 extern int __cdecl _set_osfhnd (int fd, long h);
2998 extern int __cdecl _free_osfhnd (int fd);
2999
3000 /* parallel array of private info on file handles */
3001 filedesc fd_info [ MAXDESC ];
3002
3003 typedef struct volume_info_data {
3004 struct volume_info_data * next;
3005
3006 /* time when info was obtained */
3007 DWORD timestamp;
3008
3009 /* actual volume info */
3010 char * root_dir;
3011 DWORD serialnum;
3012 DWORD maxcomp;
3013 DWORD flags;
3014 char * name;
3015 char * type;
3016 } volume_info_data;
3017
3018 /* Global referenced by various functions. */
3019 static volume_info_data volume_info;
3020
3021 /* Vector to indicate which drives are local and fixed (for which cached
3022 data never expires). */
3023 static BOOL fixed_drives[26];
3024
3025 /* Consider cached volume information to be stale if older than 10s,
3026 at least for non-local drives. Info for fixed drives is never stale. */
3027 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3028 #define VOLINFO_STILL_VALID( root_dir, info ) \
3029 ( ( isalpha (root_dir[0]) && \
3030 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3031 || GetTickCount () - info->timestamp < 10000 )
3032
3033 /* Cache support functions. */
3034
3035 /* Simple linked list with linear search is sufficient. */
3036 static volume_info_data *volume_cache = NULL;
3037
3038 static volume_info_data *
3039 lookup_volume_info (char * root_dir)
3040 {
3041 volume_info_data * info;
3042
3043 for (info = volume_cache; info; info = info->next)
3044 if (xstrcasecmp (info->root_dir, root_dir) == 0)
3045 break;
3046 return info;
3047 }
3048
3049 static void
3050 add_volume_info (char * root_dir, volume_info_data * info)
3051 {
3052 info->root_dir = xstrdup (root_dir);
3053 unixtodos_filename (info->root_dir);
3054 info->next = volume_cache;
3055 volume_cache = info;
3056 }
3057
3058
3059 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3060 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3061 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3062 static volume_info_data *
3063 GetCachedVolumeInformation (char * root_dir)
3064 {
3065 volume_info_data * info;
3066 char default_root[ MAX_UTF8_PATH ];
3067 char name[MAX_PATH+1];
3068 char type[MAX_PATH+1];
3069
3070 /* NULL for root_dir means use root from current directory. */
3071 if (root_dir == NULL)
3072 {
3073 if (w32_unicode_filenames)
3074 {
3075 wchar_t curdirw[MAX_PATH];
3076
3077 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
3078 return NULL;
3079 filename_from_utf16 (curdirw, default_root);
3080 }
3081 else
3082 {
3083 char curdira[MAX_PATH];
3084
3085 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
3086 return NULL;
3087 filename_from_ansi (curdira, default_root);
3088 }
3089 parse_root (default_root, (const char **)&root_dir);
3090 *root_dir = 0;
3091 root_dir = default_root;
3092 }
3093
3094 /* Local fixed drives can be cached permanently. Removable drives
3095 cannot be cached permanently, since the volume name and serial
3096 number (if nothing else) can change. Remote drives should be
3097 treated as if they are removable, since there is no sure way to
3098 tell whether they are or not. Also, the UNC association of drive
3099 letters mapped to remote volumes can be changed at any time (even
3100 by other processes) without notice.
3101
3102 As a compromise, so we can benefit from caching info for remote
3103 volumes, we use a simple expiry mechanism to invalidate cache
3104 entries that are more than ten seconds old. */
3105
3106 #if 0
3107 /* No point doing this, because WNetGetConnection is even slower than
3108 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3109 GetDriveType is about the only call of this type which does not
3110 involve network access, and so is extremely quick). */
3111
3112 /* Map drive letter to UNC if remote. */
3113 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
3114 {
3115 char remote_name[ 256 ];
3116 char drive[3] = { root_dir[0], ':' };
3117
3118 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
3119 == NO_ERROR)
3120 /* do something */ ;
3121 }
3122 #endif
3123
3124 info = lookup_volume_info (root_dir);
3125
3126 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
3127 {
3128 DWORD serialnum;
3129 DWORD maxcomp;
3130 DWORD flags;
3131
3132 /* Info is not cached, or is stale. */
3133 if (w32_unicode_filenames)
3134 {
3135 wchar_t root_w[MAX_PATH];
3136 wchar_t name_w[MAX_PATH+1];
3137 wchar_t type_w[MAX_PATH+1];
3138
3139 filename_to_utf16 (root_dir, root_w);
3140 if (!GetVolumeInformationW (root_w,
3141 name_w, sizeof (name_w),
3142 &serialnum,
3143 &maxcomp,
3144 &flags,
3145 type_w, sizeof (type_w)))
3146 return NULL;
3147 /* Hmm... not really 100% correct, as these 2 are not file
3148 names... */
3149 filename_from_utf16 (name_w, name);
3150 filename_from_utf16 (type_w, type);
3151 }
3152 else
3153 {
3154 char root_a[MAX_PATH];
3155 char name_a[MAX_PATH+1];
3156 char type_a[MAX_PATH+1];
3157
3158 filename_to_ansi (root_dir, root_a);
3159 if (!GetVolumeInformationA (root_a,
3160 name_a, sizeof (name_a),
3161 &serialnum,
3162 &maxcomp,
3163 &flags,
3164 type_a, sizeof (type_a)))
3165 return NULL;
3166 filename_from_ansi (name_a, name);
3167 filename_from_ansi (type_a, type);
3168 }
3169
3170 /* Cache the volume information for future use, overwriting existing
3171 entry if present. */
3172 if (info == NULL)
3173 {
3174 info = xmalloc (sizeof (volume_info_data));
3175 add_volume_info (root_dir, info);
3176 }
3177 else
3178 {
3179 xfree (info->name);
3180 xfree (info->type);
3181 }
3182
3183 info->name = xstrdup (name);
3184 unixtodos_filename (info->name);
3185 info->serialnum = serialnum;
3186 info->maxcomp = maxcomp;
3187 info->flags = flags;
3188 info->type = xstrdup (type);
3189 info->timestamp = GetTickCount ();
3190 }
3191
3192 return info;
3193 }
3194
3195 /* Get information on the volume where NAME is held; set path pointer to
3196 start of pathname in NAME (past UNC header\volume header if present),
3197 if pPath is non-NULL.
3198
3199 Note: if NAME includes symlinks, the information is for the volume
3200 of the symlink, not of its target. That's because, even though
3201 GetVolumeInformation returns information about the symlink target
3202 of its argument, we only pass the root directory to
3203 GetVolumeInformation, not the full NAME. */
3204 static int
3205 get_volume_info (const char * name, const char ** pPath)
3206 {
3207 char temp[MAX_UTF8_PATH];
3208 char *rootname = NULL; /* default to current volume */
3209 volume_info_data * info;
3210 int root_len = parse_root (name, pPath);
3211
3212 if (name == NULL)
3213 return FALSE;
3214
3215 /* Copy the root name of the volume, if given. */
3216 if (root_len)
3217 {
3218 strncpy (temp, name, root_len);
3219 temp[root_len] = '\0';
3220 unixtodos_filename (temp);
3221 rootname = temp;
3222 }
3223
3224 info = GetCachedVolumeInformation (rootname);
3225 if (info != NULL)
3226 {
3227 /* Set global referenced by other functions. */
3228 volume_info = *info;
3229 return TRUE;
3230 }
3231 return FALSE;
3232 }
3233
3234 /* Determine if volume is FAT format (ie. only supports short 8.3
3235 names); also set path pointer to start of pathname in name, if
3236 pPath is non-NULL. */
3237 static int
3238 is_fat_volume (const char * name, const char ** pPath)
3239 {
3240 if (get_volume_info (name, pPath))
3241 return (volume_info.maxcomp == 12);
3242 return FALSE;
3243 }
3244
3245 /* Convert all slashes in a filename to backslashes, and map filename
3246 to a valid 8.3 name if necessary. The result is a pointer to a
3247 static buffer, so CAVEAT EMPTOR! */
3248 const char *map_w32_filename (const char *, const char **);
3249
3250 const char *
3251 map_w32_filename (const char * name, const char ** pPath)
3252 {
3253 static char shortname[MAX_UTF8_PATH];
3254 char * str = shortname;
3255 char c;
3256 char * path;
3257 const char * save_name = name;
3258
3259 if (strlen (name) >= sizeof (shortname))
3260 {
3261 /* Return a filename which will cause callers to fail. */
3262 strcpy (shortname, "?");
3263 return shortname;
3264 }
3265
3266 if (!fatal_error_in_progress /* disable fancy processing during crash */
3267 && is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
3268 {
3269 register int left = 8; /* maximum number of chars in part */
3270 register int extn = 0; /* extension added? */
3271 register int dots = 2; /* maximum number of dots allowed */
3272
3273 while (name < path)
3274 *str++ = *name++; /* skip past UNC header */
3275
3276 while ((c = *name++))
3277 {
3278 switch ( c )
3279 {
3280 case ':':
3281 case '\\':
3282 case '/':
3283 *str++ = (c == ':' ? ':' : '\\');
3284 extn = 0; /* reset extension flags */
3285 dots = 2; /* max 2 dots */
3286 left = 8; /* max length 8 for main part */
3287 break;
3288 case '.':
3289 if ( dots )
3290 {
3291 /* Convert path components of the form .xxx to _xxx,
3292 but leave . and .. as they are. This allows .emacs
3293 to be read as _emacs, for example. */
3294
3295 if (! *name ||
3296 *name == '.' ||
3297 IS_DIRECTORY_SEP (*name))
3298 {
3299 *str++ = '.';
3300 dots--;
3301 }
3302 else
3303 {
3304 *str++ = '_';
3305 left--;
3306 dots = 0;
3307 }
3308 }
3309 else if ( !extn )
3310 {
3311 *str++ = '.';
3312 extn = 1; /* we've got an extension */
3313 left = 3; /* 3 chars in extension */
3314 }
3315 else
3316 {
3317 /* any embedded dots after the first are converted to _ */
3318 *str++ = '_';
3319 }
3320 break;
3321 case '~':
3322 case '#': /* don't lose these, they're important */
3323 if ( ! left )
3324 str[-1] = c; /* replace last character of part */
3325 /* FALLTHRU */
3326 default:
3327 if ( left && 'A' <= c && c <= 'Z' )
3328 {
3329 *str++ = tolower (c); /* map to lower case (looks nicer) */
3330 left--;
3331 dots = 0; /* started a path component */
3332 }
3333 break;
3334 }
3335 }
3336 *str = '\0';
3337 }
3338 else
3339 {
3340 strcpy (shortname, name);
3341 unixtodos_filename (shortname);
3342 }
3343
3344 if (pPath)
3345 *pPath = shortname + (path - save_name);
3346
3347 return shortname;
3348 }
3349
3350 static int
3351 is_exec (const char * name)
3352 {
3353 char * p = strrchr (name, '.');
3354 return
3355 (p != NULL
3356 && (xstrcasecmp (p, ".exe") == 0 ||
3357 xstrcasecmp (p, ".com") == 0 ||
3358 xstrcasecmp (p, ".bat") == 0 ||
3359 xstrcasecmp (p, ".cmd") == 0));
3360 }
3361
3362 /* Emulate the Unix directory procedures opendir, closedir, and
3363 readdir. We rename them to sys_* names because some versions of
3364 MinGW startup code call opendir and readdir to glob wildcards, and
3365 the code that calls them doesn't grok UTF-8 encoded file names we
3366 produce in dirent->d_name[]. */
3367
3368 struct dirent dir_static; /* simulated directory contents */
3369 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
3370 static int dir_is_fat;
3371 static char dir_pathname[MAX_UTF8_PATH];
3372 static WIN32_FIND_DATAW dir_find_data_w;
3373 static WIN32_FIND_DATAA dir_find_data_a;
3374 #define DIR_FIND_DATA_W 1
3375 #define DIR_FIND_DATA_A 2
3376 static int last_dir_find_data = -1;
3377
3378 /* Support shares on a network resource as subdirectories of a read-only
3379 root directory. */
3380 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
3381 static HANDLE open_unc_volume (const char *);
3382 static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
3383 static void close_unc_volume (HANDLE);
3384
3385 DIR *
3386 sys_opendir (const char *filename)
3387 {
3388 DIR *dirp;
3389
3390 /* Opening is done by FindFirstFile. However, a read is inherent to
3391 this operation, so we defer the open until read time. */
3392
3393 if (dir_find_handle != INVALID_HANDLE_VALUE)
3394 return NULL;
3395 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3396 return NULL;
3397
3398 /* Note: We don't support traversal of UNC volumes via symlinks.
3399 Doing so would mean punishing 99.99% of use cases by resolving
3400 all the possible symlinks in FILENAME, recursively. */
3401 if (is_unc_volume (filename))
3402 {
3403 wnet_enum_handle = open_unc_volume (filename);
3404 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
3405 return NULL;
3406 }
3407
3408 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
3409 return NULL;
3410
3411 dirp->dd_fd = 0;
3412 dirp->dd_loc = 0;
3413 dirp->dd_size = 0;
3414
3415 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
3416 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
3417 /* Note: We don't support symlinks to file names on FAT volumes.
3418 Doing so would mean punishing 99.99% of use cases by resolving
3419 all the possible symlinks in FILENAME, recursively. */
3420 dir_is_fat = is_fat_volume (filename, NULL);
3421
3422 return dirp;
3423 }
3424
3425 void
3426 sys_closedir (DIR *dirp)
3427 {
3428 /* If we have a find-handle open, close it. */
3429 if (dir_find_handle != INVALID_HANDLE_VALUE)
3430 {
3431 FindClose (dir_find_handle);
3432 dir_find_handle = INVALID_HANDLE_VALUE;
3433 }
3434 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3435 {
3436 close_unc_volume (wnet_enum_handle);
3437 wnet_enum_handle = INVALID_HANDLE_VALUE;
3438 }
3439 xfree ((char *) dirp);
3440 }
3441
3442 struct dirent *
3443 sys_readdir (DIR *dirp)
3444 {
3445 int downcase = !NILP (Vw32_downcase_file_names);
3446
3447 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3448 {
3449 if (!read_unc_volume (wnet_enum_handle,
3450 dir_find_data_w.cFileName,
3451 dir_find_data_a.cFileName,
3452 MAX_PATH))
3453 return NULL;
3454 }
3455 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3456 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3457 {
3458 char filename[MAX_UTF8_PATH];
3459 int ln;
3460 bool last_slash = true;
3461
3462 /* Note: We don't need to worry about dir_pathname being longer
3463 than MAX_UTF8_PATH, as sys_opendir already took care of that
3464 when it called map_w32_filename: that function will put a "?"
3465 in its return value in that case, thus failing all the calls
3466 below. */
3467 strcpy (filename, dir_pathname);
3468 ln = strlen (filename);
3469 if (!IS_DIRECTORY_SEP (filename[ln - 1]))
3470 last_slash = false;
3471
3472 /* Note: No need to resolve symlinks in FILENAME, because
3473 FindFirst opens the directory that is the target of a
3474 symlink. */
3475 if (w32_unicode_filenames)
3476 {
3477 wchar_t fnw[MAX_PATH + 2];
3478
3479 filename_to_utf16 (filename, fnw);
3480 if (!last_slash)
3481 wcscat (fnw, L"\\");
3482 wcscat (fnw, L"*");
3483 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
3484 }
3485 else
3486 {
3487 char fna[MAX_PATH + 2];
3488
3489 filename_to_ansi (filename, fna);
3490 if (!last_slash)
3491 strcat (fna, "\\");
3492 strcat (fna, "*");
3493 /* If FILENAME is not representable by the current ANSI
3494 codepage, we don't want FindFirstFileA to interpret the
3495 '?' characters as a wildcard. */
3496 if (_mbspbrk (fna, "?"))
3497 dir_find_handle = INVALID_HANDLE_VALUE;
3498 else
3499 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
3500 }
3501
3502 if (dir_find_handle == INVALID_HANDLE_VALUE)
3503 {
3504 /* Any changes in the value of errno here should be in sync
3505 with what directory_files_internal does when it calls
3506 readdir. */
3507 switch (GetLastError ())
3508 {
3509 /* Windows uses this value when FindFirstFile finds no
3510 files that match the wildcard. This is not supposed
3511 to happen, since our wildcard is "*", but just in
3512 case, if there's some weird empty directory with not
3513 even "." and ".." entries... */
3514 case ERROR_FILE_NOT_FOUND:
3515 errno = 0;
3516 /* FALLTHRU */
3517 default:
3518 break;
3519 case ERROR_ACCESS_DENIED:
3520 case ERROR_NETWORK_ACCESS_DENIED:
3521 errno = EACCES;
3522 break;
3523 case ERROR_PATH_NOT_FOUND:
3524 case ERROR_INVALID_DRIVE:
3525 case ERROR_NOT_READY:
3526 case ERROR_BAD_NETPATH:
3527 case ERROR_BAD_NET_NAME:
3528 errno = ENOENT;
3529 break;
3530 }
3531 return NULL;
3532 }
3533 }
3534 else if (w32_unicode_filenames)
3535 {
3536 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3537 {
3538 errno = 0;
3539 return NULL;
3540 }
3541 }
3542 else
3543 {
3544 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
3545 {
3546 errno = 0;
3547 return NULL;
3548 }
3549 }
3550
3551 /* Emacs never uses this value, so don't bother making it match
3552 value returned by stat(). */
3553 dir_static.d_ino = 1;
3554
3555 if (w32_unicode_filenames)
3556 {
3557 if (downcase || dir_is_fat)
3558 {
3559 wchar_t tem[MAX_PATH];
3560
3561 wcscpy (tem, dir_find_data_w.cFileName);
3562 CharLowerW (tem);
3563 filename_from_utf16 (tem, dir_static.d_name);
3564 }
3565 else
3566 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
3567 last_dir_find_data = DIR_FIND_DATA_W;
3568 }
3569 else
3570 {
3571 char tem[MAX_PATH];
3572
3573 /* If the file name in cFileName[] includes `?' characters, it
3574 means the original file name used characters that cannot be
3575 represented by the current ANSI codepage. To avoid total
3576 lossage, retrieve the short 8+3 alias of the long file
3577 name. */
3578 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
3579 {
3580 strcpy (tem, dir_find_data_a.cAlternateFileName);
3581 /* 8+3 aliases are returned in all caps, which could break
3582 various alists that look at filenames' extensions. */
3583 downcase = 1;
3584 }
3585 else if (downcase || dir_is_fat)
3586 strcpy (tem, dir_find_data_a.cFileName);
3587 else
3588 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3589 if (downcase || dir_is_fat)
3590 {
3591 _mbslwr (tem);
3592 filename_from_ansi (tem, dir_static.d_name);
3593 }
3594 last_dir_find_data = DIR_FIND_DATA_A;
3595 }
3596
3597 dir_static.d_namlen = strlen (dir_static.d_name);
3598 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3599 dir_static.d_namlen - dir_static.d_namlen % 4;
3600
3601 return &dir_static;
3602 }
3603
3604 static HANDLE
3605 open_unc_volume (const char *path)
3606 {
3607 const char *fn = map_w32_filename (path, NULL);
3608 DWORD result;
3609 HANDLE henum;
3610
3611 if (w32_unicode_filenames)
3612 {
3613 NETRESOURCEW nrw;
3614 wchar_t fnw[MAX_PATH];
3615
3616 nrw.dwScope = RESOURCE_GLOBALNET;
3617 nrw.dwType = RESOURCETYPE_DISK;
3618 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3619 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3620 nrw.lpLocalName = NULL;
3621 filename_to_utf16 (fn, fnw);
3622 nrw.lpRemoteName = fnw;
3623 nrw.lpComment = NULL;
3624 nrw.lpProvider = NULL;
3625
3626 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3627 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3628 }
3629 else
3630 {
3631 NETRESOURCEA nra;
3632 char fna[MAX_PATH];
3633
3634 nra.dwScope = RESOURCE_GLOBALNET;
3635 nra.dwType = RESOURCETYPE_DISK;
3636 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3637 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3638 nra.lpLocalName = NULL;
3639 filename_to_ansi (fn, fna);
3640 nra.lpRemoteName = fna;
3641 nra.lpComment = NULL;
3642 nra.lpProvider = NULL;
3643
3644 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3645 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3646 }
3647 if (result == NO_ERROR)
3648 return henum;
3649 else
3650 {
3651 /* Make sure directory_files_internal reports a sensible error. */
3652 errno = ENOENT;
3653 return INVALID_HANDLE_VALUE;
3654 }
3655 }
3656
3657 static void *
3658 read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
3659 {
3660 DWORD count;
3661 int result;
3662 char *buffer;
3663 DWORD bufsize = 512;
3664 void *retval;
3665
3666 count = 1;
3667 if (w32_unicode_filenames)
3668 {
3669 wchar_t *ptrw;
3670
3671 bufsize *= 2;
3672 buffer = alloca (bufsize);
3673 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3674 if (result != NO_ERROR)
3675 return NULL;
3676 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3677 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3678 ptrw += 2;
3679 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3680 ptrw++;
3681 wcsncpy (fname_w, ptrw, size);
3682 retval = fname_w;
3683 }
3684 else
3685 {
3686 int dbcs_p = max_filename_mbslen () > 1;
3687 char *ptra;
3688
3689 buffer = alloca (bufsize);
3690 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3691 if (result != NO_ERROR)
3692 return NULL;
3693 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3694 ptra += 2;
3695 if (!dbcs_p)
3696 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3697 else
3698 {
3699 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3700 ptra = CharNextExA (file_name_codepage, ptra, 0);
3701 }
3702 ptra++;
3703 strncpy (fname_a, ptra, size);
3704 retval = fname_a;
3705 }
3706
3707 return retval;
3708 }
3709
3710 static void
3711 close_unc_volume (HANDLE henum)
3712 {
3713 if (henum != INVALID_HANDLE_VALUE)
3714 WNetCloseEnum (henum);
3715 }
3716
3717 static DWORD
3718 unc_volume_file_attributes (const char *path)
3719 {
3720 HANDLE henum;
3721 DWORD attrs;
3722
3723 henum = open_unc_volume (path);
3724 if (henum == INVALID_HANDLE_VALUE)
3725 return -1;
3726
3727 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3728
3729 close_unc_volume (henum);
3730
3731 return attrs;
3732 }
3733
3734 /* Ensure a network connection is authenticated. */
3735 static void
3736 logon_network_drive (const char *path)
3737 {
3738 char share[MAX_UTF8_PATH];
3739 int n_slashes;
3740 char drive[4];
3741 UINT drvtype;
3742 char *p;
3743 DWORD val;
3744
3745 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3746 drvtype = DRIVE_REMOTE;
3747 else if (path[0] == '\0' || path[1] != ':')
3748 drvtype = GetDriveType (NULL);
3749 else
3750 {
3751 drive[0] = path[0];
3752 drive[1] = ':';
3753 drive[2] = '\\';
3754 drive[3] = '\0';
3755 drvtype = GetDriveType (drive);
3756 }
3757
3758 /* Only logon to networked drives. */
3759 if (drvtype != DRIVE_REMOTE)
3760 return;
3761
3762 n_slashes = 2;
3763 strncpy (share, path, MAX_UTF8_PATH);
3764 /* Truncate to just server and share name. */
3765 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
3766 {
3767 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3768 {
3769 *p = '\0';
3770 break;
3771 }
3772 }
3773
3774 if (w32_unicode_filenames)
3775 {
3776 NETRESOURCEW resourcew;
3777 wchar_t share_w[MAX_PATH];
3778
3779 resourcew.dwScope = RESOURCE_GLOBALNET;
3780 resourcew.dwType = RESOURCETYPE_DISK;
3781 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3782 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3783 resourcew.lpLocalName = NULL;
3784 filename_to_utf16 (share, share_w);
3785 resourcew.lpRemoteName = share_w;
3786 resourcew.lpProvider = NULL;
3787
3788 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3789 }
3790 else
3791 {
3792 NETRESOURCEA resourcea;
3793 char share_a[MAX_PATH];
3794
3795 resourcea.dwScope = RESOURCE_GLOBALNET;
3796 resourcea.dwType = RESOURCETYPE_DISK;
3797 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3798 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3799 resourcea.lpLocalName = NULL;
3800 filename_to_ansi (share, share_a);
3801 resourcea.lpRemoteName = share_a;
3802 resourcea.lpProvider = NULL;
3803
3804 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3805 }
3806
3807 switch (val)
3808 {
3809 case NO_ERROR:
3810 case ERROR_ALREADY_ASSIGNED:
3811 break;
3812 case ERROR_ACCESS_DENIED:
3813 case ERROR_LOGON_FAILURE:
3814 errno = EACCES;
3815 break;
3816 case ERROR_BUSY:
3817 errno = EAGAIN;
3818 break;
3819 case ERROR_BAD_NET_NAME:
3820 case ERROR_NO_NET_OR_BAD_PATH:
3821 case ERROR_NO_NETWORK:
3822 case ERROR_CANCELLED:
3823 default:
3824 errno = ENOENT;
3825 break;
3826 }
3827 }
3828
3829 /* Emulate faccessat(2). */
3830 int
3831 faccessat (int dirfd, const char * path, int mode, int flags)
3832 {
3833 DWORD attributes;
3834
3835 if (dirfd != AT_FDCWD
3836 && !(IS_DIRECTORY_SEP (path[0])
3837 || IS_DEVICE_SEP (path[1])))
3838 {
3839 errno = EBADF;
3840 return -1;
3841 }
3842
3843 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3844 newer versions blow up when passed D_OK. */
3845 path = map_w32_filename (path, NULL);
3846 /* If the last element of PATH is a symlink, we need to resolve it
3847 to get the attributes of its target file. Note: any symlinks in
3848 PATH elements other than the last one are transparently resolved
3849 by GetFileAttributes below. */
3850 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3851 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3852 path = chase_symlinks (path);
3853
3854 if (w32_unicode_filenames)
3855 {
3856 wchar_t path_w[MAX_PATH];
3857
3858 filename_to_utf16 (path, path_w);
3859 attributes = GetFileAttributesW (path_w);
3860 }
3861 else
3862 {
3863 char path_a[MAX_PATH];
3864
3865 filename_to_ansi (path, path_a);
3866 attributes = GetFileAttributesA (path_a);
3867 }
3868
3869 if (attributes == -1)
3870 {
3871 DWORD w32err = GetLastError ();
3872
3873 switch (w32err)
3874 {
3875 case ERROR_INVALID_NAME:
3876 case ERROR_BAD_PATHNAME:
3877 if (is_unc_volume (path))
3878 {
3879 attributes = unc_volume_file_attributes (path);
3880 if (attributes == -1)
3881 {
3882 errno = EACCES;
3883 return -1;
3884 }
3885 goto check_attrs;
3886 }
3887 /* FALLTHROUGH */
3888 case ERROR_FILE_NOT_FOUND:
3889 case ERROR_BAD_NETPATH:
3890 errno = ENOENT;
3891 break;
3892 default:
3893 errno = EACCES;
3894 break;
3895 }
3896 return -1;
3897 }
3898
3899 check_attrs:
3900 if ((mode & X_OK) != 0
3901 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3902 {
3903 errno = EACCES;
3904 return -1;
3905 }
3906 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3907 {
3908 errno = EACCES;
3909 return -1;
3910 }
3911 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3912 {
3913 errno = EACCES;
3914 return -1;
3915 }
3916 return 0;
3917 }
3918
3919 /* A special test for DIRNAME being a directory accessible by the
3920 current user. This is needed because the security permissions in
3921 directory's ACLs are not visible in the Posix-style mode bits
3922 returned by 'stat' and in attributes returned by GetFileAttributes.
3923 So a directory would seem like it's readable by the current user,
3924 but will in fact error out with EACCES when they actually try. */
3925 int
3926 w32_accessible_directory_p (const char *dirname, ptrdiff_t dirlen)
3927 {
3928 char pattern[MAX_UTF8_PATH];
3929 bool last_slash = dirlen > 0 && IS_DIRECTORY_SEP (dirname[dirlen - 1]);
3930 HANDLE dh;
3931
3932 /* Network volumes need a different reading method. */
3933 if (is_unc_volume (dirname))
3934 {
3935 void *read_result = NULL;
3936 wchar_t fnw[MAX_PATH];
3937 char fna[MAX_PATH];
3938
3939 dh = open_unc_volume (dirname);
3940 if (dh != INVALID_HANDLE_VALUE)
3941 {
3942 read_result = read_unc_volume (dh, fnw, fna, MAX_PATH);
3943 close_unc_volume (dh);
3944 }
3945 /* Treat empty volumes as accessible. */
3946 return read_result != NULL || GetLastError () == ERROR_NO_MORE_ITEMS;
3947 }
3948
3949 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3950 MAX_UTF8_PATH. */
3951 strcpy (pattern, map_w32_filename (dirname, NULL));
3952
3953 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3954 opens the directory that is the target of a symlink. */
3955 if (w32_unicode_filenames)
3956 {
3957 wchar_t pat_w[MAX_PATH + 2];
3958 WIN32_FIND_DATAW dfd_w;
3959
3960 filename_to_utf16 (pattern, pat_w);
3961 if (!last_slash)
3962 wcscat (pat_w, L"\\");
3963 wcscat (pat_w, L"*");
3964 dh = FindFirstFileW (pat_w, &dfd_w);
3965 }
3966 else
3967 {
3968 char pat_a[MAX_PATH + 2];
3969 WIN32_FIND_DATAA dfd_a;
3970
3971 filename_to_ansi (pattern, pat_a);
3972 if (!last_slash)
3973 strcpy (pat_a, "\\");
3974 strcat (pat_a, "*");
3975 /* In case DIRNAME cannot be expressed in characters from the
3976 current ANSI codepage. */
3977 if (_mbspbrk (pat_a, "?"))
3978 dh = INVALID_HANDLE_VALUE;
3979 else
3980 dh = FindFirstFileA (pat_a, &dfd_a);
3981 }
3982
3983 if (dh == INVALID_HANDLE_VALUE)
3984 return 0;
3985 FindClose (dh);
3986 return 1;
3987 }
3988
3989 /* A version of 'access' to be used locally with file names in
3990 locale-specific encoding. Does not resolve symlinks and does not
3991 support file names on FAT12 and FAT16 volumes, but that's OK, since
3992 we only invoke this function for files inside the Emacs source or
3993 installation tree, on directories (so any symlinks should have the
3994 directory bit set), and on short file names such as "C:/.emacs". */
3995 static int
3996 sys_access (const char *fname, int mode)
3997 {
3998 char fname_copy[MAX_PATH], *p;
3999 DWORD attributes;
4000
4001 strcpy (fname_copy, fname);
4002 /* Do the equivalent of unixtodos_filename. */
4003 for (p = fname_copy; *p; p = CharNext (p))
4004 if (*p == '/')
4005 *p = '\\';
4006
4007 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
4008 {
4009 DWORD w32err = GetLastError ();
4010
4011 switch (w32err)
4012 {
4013 case ERROR_INVALID_NAME:
4014 case ERROR_BAD_PATHNAME:
4015 case ERROR_FILE_NOT_FOUND:
4016 case ERROR_BAD_NETPATH:
4017 errno = ENOENT;
4018 break;
4019 default:
4020 errno = EACCES;
4021 break;
4022 }
4023 return -1;
4024 }
4025 if ((mode & X_OK) != 0
4026 && !(is_exec (fname_copy)
4027 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
4028 {
4029 errno = EACCES;
4030 return -1;
4031 }
4032 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
4033 {
4034 errno = EACCES;
4035 return -1;
4036 }
4037 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
4038 {
4039 errno = EACCES;
4040 return -1;
4041 }
4042 return 0;
4043 }
4044
4045 /* Shadow some MSVC runtime functions to map requests for long filenames
4046 to reasonable short names if necessary. This was originally added to
4047 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4048 long file names. */
4049
4050 int
4051 sys_chdir (const char * path)
4052 {
4053 path = map_w32_filename (path, NULL);
4054 if (w32_unicode_filenames)
4055 {
4056 wchar_t newdir_w[MAX_PATH];
4057
4058 if (filename_to_utf16 (path, newdir_w) == 0)
4059 return _wchdir (newdir_w);
4060 return -1;
4061 }
4062 else
4063 {
4064 char newdir_a[MAX_PATH];
4065
4066 if (filename_to_ansi (path, newdir_a) == 0)
4067 return _chdir (newdir_a);
4068 return -1;
4069 }
4070 }
4071
4072 int
4073 sys_chmod (const char * path, int mode)
4074 {
4075 path = chase_symlinks (map_w32_filename (path, NULL));
4076 if (w32_unicode_filenames)
4077 {
4078 wchar_t path_w[MAX_PATH];
4079
4080 filename_to_utf16 (path, path_w);
4081 return _wchmod (path_w, mode);
4082 }
4083 else
4084 {
4085 char path_a[MAX_PATH];
4086
4087 filename_to_ansi (path, path_a);
4088 return _chmod (path_a, mode);
4089 }
4090 }
4091
4092 int
4093 sys_creat (const char * path, int mode)
4094 {
4095 path = map_w32_filename (path, NULL);
4096 if (w32_unicode_filenames)
4097 {
4098 wchar_t path_w[MAX_PATH];
4099
4100 filename_to_utf16 (path, path_w);
4101 return _wcreat (path_w, mode);
4102 }
4103 else
4104 {
4105 char path_a[MAX_PATH];
4106
4107 filename_to_ansi (path, path_a);
4108 return _creat (path_a, mode);
4109 }
4110 }
4111
4112 FILE *
4113 sys_fopen (const char * path, const char * mode)
4114 {
4115 int fd;
4116 int oflag;
4117 const char * mode_save = mode;
4118
4119 /* Force all file handles to be non-inheritable. This is necessary to
4120 ensure child processes don't unwittingly inherit handles that might
4121 prevent future file access. */
4122
4123 if (mode[0] == 'r')
4124 oflag = O_RDONLY;
4125 else if (mode[0] == 'w' || mode[0] == 'a')
4126 oflag = O_WRONLY | O_CREAT | O_TRUNC;
4127 else
4128 return NULL;
4129
4130 /* Only do simplistic option parsing. */
4131 while (*++mode)
4132 if (mode[0] == '+')
4133 {
4134 oflag &= ~(O_RDONLY | O_WRONLY);
4135 oflag |= O_RDWR;
4136 }
4137 else if (mode[0] == 'b')
4138 {
4139 oflag &= ~O_TEXT;
4140 oflag |= O_BINARY;
4141 }
4142 else if (mode[0] == 't')
4143 {
4144 oflag &= ~O_BINARY;
4145 oflag |= O_TEXT;
4146 }
4147 else break;
4148
4149 path = map_w32_filename (path, NULL);
4150 if (w32_unicode_filenames)
4151 {
4152 wchar_t path_w[MAX_PATH];
4153
4154 filename_to_utf16 (path, path_w);
4155 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
4156 }
4157 else
4158 {
4159 char path_a[MAX_PATH];
4160
4161 filename_to_ansi (path, path_a);
4162 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
4163 }
4164 if (fd < 0)
4165 return NULL;
4166
4167 return _fdopen (fd, mode_save);
4168 }
4169
4170 /* This only works on NTFS volumes, but is useful to have. */
4171 int
4172 sys_link (const char * old, const char * new)
4173 {
4174 HANDLE fileh;
4175 int result = -1;
4176 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
4177 wchar_t oldname_w[MAX_PATH];
4178 char oldname_a[MAX_PATH];
4179
4180 if (old == NULL || new == NULL)
4181 {
4182 errno = ENOENT;
4183 return -1;
4184 }
4185
4186 strcpy (oldname, map_w32_filename (old, NULL));
4187 strcpy (newname, map_w32_filename (new, NULL));
4188
4189 if (w32_unicode_filenames)
4190 {
4191 filename_to_utf16 (oldname, oldname_w);
4192 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
4193 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4194 }
4195 else
4196 {
4197 filename_to_ansi (oldname, oldname_a);
4198 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
4199 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4200 }
4201 if (fileh != INVALID_HANDLE_VALUE)
4202 {
4203 int wlen;
4204
4205 /* Confusingly, the "alternate" stream name field does not apply
4206 when restoring a hard link, and instead contains the actual
4207 stream data for the link (ie. the name of the link to create).
4208 The WIN32_STREAM_ID structure before the cStreamName field is
4209 the stream header, which is then immediately followed by the
4210 stream data. */
4211
4212 struct {
4213 WIN32_STREAM_ID wid;
4214 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
4215 } data;
4216
4217 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4218 indicates that flag is unsupported for CP_UTF8, and OTOH says
4219 it is the default anyway. */
4220 wlen = pMultiByteToWideChar (CP_UTF8, 0, newname, -1,
4221 data.wid.cStreamName, MAX_PATH);
4222 if (wlen > 0)
4223 {
4224 LPVOID context = NULL;
4225 DWORD wbytes = 0;
4226
4227 data.wid.dwStreamId = BACKUP_LINK;
4228 data.wid.dwStreamAttributes = 0;
4229 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
4230 data.wid.Size.HighPart = 0;
4231 data.wid.dwStreamNameSize = 0;
4232
4233 if (BackupWrite (fileh, (LPBYTE)&data,
4234 offsetof (WIN32_STREAM_ID, cStreamName)
4235 + data.wid.Size.LowPart,
4236 &wbytes, FALSE, FALSE, &context)
4237 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
4238 {
4239 /* succeeded */
4240 result = 0;
4241 }
4242 else
4243 {
4244 DWORD err = GetLastError ();
4245 DWORD attributes;
4246
4247 switch (err)
4248 {
4249 case ERROR_ACCESS_DENIED:
4250 /* This is what happens when OLDNAME is a directory,
4251 since Windows doesn't support hard links to
4252 directories. Posix says to set errno to EPERM in
4253 that case. */
4254 if (w32_unicode_filenames)
4255 attributes = GetFileAttributesW (oldname_w);
4256 else
4257 attributes = GetFileAttributesA (oldname_a);
4258 if (attributes != -1
4259 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
4260 errno = EPERM;
4261 else if (attributes == -1
4262 && is_unc_volume (oldname)
4263 && unc_volume_file_attributes (oldname) != -1)
4264 errno = EPERM;
4265 else
4266 errno = EACCES;
4267 break;
4268 case ERROR_TOO_MANY_LINKS:
4269 errno = EMLINK;
4270 break;
4271 case ERROR_NOT_SAME_DEVICE:
4272 errno = EXDEV;
4273 break;
4274 default:
4275 errno = EINVAL;
4276 break;
4277 }
4278 }
4279 }
4280
4281 CloseHandle (fileh);
4282 }
4283 else
4284 errno = ENOENT;
4285
4286 return result;
4287 }
4288
4289 int
4290 sys_mkdir (const char * path)
4291 {
4292 path = map_w32_filename (path, NULL);
4293
4294 if (w32_unicode_filenames)
4295 {
4296 wchar_t path_w[MAX_PATH];
4297
4298 filename_to_utf16 (path, path_w);
4299 return _wmkdir (path_w);
4300 }
4301 else
4302 {
4303 char path_a[MAX_PATH];
4304
4305 filename_to_ansi (path, path_a);
4306 return _mkdir (path_a);
4307 }
4308 }
4309
4310 int
4311 sys_open (const char * path, int oflag, int mode)
4312 {
4313 const char* mpath = map_w32_filename (path, NULL);
4314 int res = -1;
4315
4316 if (w32_unicode_filenames)
4317 {
4318 wchar_t mpath_w[MAX_PATH];
4319
4320 filename_to_utf16 (mpath, mpath_w);
4321 /* If possible, try to open file without _O_CREAT, to be able to
4322 write to existing hidden and system files. Force all file
4323 handles to be non-inheritable. */
4324 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4325 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4326 if (res < 0)
4327 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
4328 }
4329 else
4330 {
4331 char mpath_a[MAX_PATH];
4332
4333 filename_to_ansi (mpath, mpath_a);
4334 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
4335 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
4336 if (res < 0)
4337 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
4338 }
4339
4340 return res;
4341 }
4342
4343 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4344 when using mktemp.
4345
4346 Standard algorithm for generating a temporary file name seems to be
4347 use pid or tid with a letter on the front (in place of the 6 X's)
4348 and cycle through the letters to find a unique name. We extend
4349 that to allow any reasonable character as the first of the 6 X's,
4350 so that the number of simultaneously used temporary files will be
4351 greater. */
4352
4353 int
4354 mkostemp (char * template, int flags)
4355 {
4356 char * p;
4357 int i, fd = -1;
4358 unsigned uid = GetCurrentThreadId ();
4359 int save_errno = errno;
4360 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4361
4362 errno = EINVAL;
4363 if (template == NULL)
4364 return -1;
4365
4366 p = template + strlen (template);
4367 i = 5;
4368 /* replace up to the last 5 X's with uid in decimal */
4369 while (--p >= template && p[0] == 'X' && --i >= 0)
4370 {
4371 p[0] = '0' + uid % 10;
4372 uid /= 10;
4373 }
4374
4375 if (i < 0 && p[0] == 'X')
4376 {
4377 i = 0;
4378 do
4379 {
4380 p[0] = first_char[i];
4381 if ((fd = sys_open (template,
4382 flags | _O_CREAT | _O_EXCL | _O_RDWR,
4383 S_IRUSR | S_IWUSR)) >= 0
4384 || errno != EEXIST)
4385 {
4386 if (fd >= 0)
4387 errno = save_errno;
4388 return fd;
4389 }
4390 }
4391 while (++i < sizeof (first_char));
4392 }
4393
4394 /* Template is badly formed or else we can't generate a unique name. */
4395 return -1;
4396 }
4397
4398 int
4399 fchmod (int fd, mode_t mode)
4400 {
4401 return 0;
4402 }
4403
4404 int
4405 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
4406 {
4407 BOOL result;
4408 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
4409 int newname_dev;
4410 int oldname_dev;
4411 bool have_temp_a = false;
4412
4413 /* MoveFile on Windows 95 doesn't correctly change the short file name
4414 alias in a number of circumstances (it is not easy to predict when
4415 just by looking at oldname and newname, unfortunately). In these
4416 cases, renaming through a temporary name avoids the problem.
4417
4418 A second problem on Windows 95 is that renaming through a temp name when
4419 newname is uppercase fails (the final long name ends up in
4420 lowercase, although the short alias might be uppercase) UNLESS the
4421 long temp name is not 8.3.
4422
4423 So, on Windows 95 we always rename through a temp name, and we make sure
4424 the temp name has a long extension to ensure correct renaming. */
4425
4426 strcpy (temp, map_w32_filename (oldname, NULL));
4427
4428 /* volume_info is set indirectly by map_w32_filename. */
4429 oldname_dev = volume_info.serialnum;
4430
4431 if (os_subtype == OS_9X)
4432 {
4433 char * o;
4434 char * p;
4435 int i = 0;
4436 char oldname_a[MAX_PATH];
4437
4438 oldname = map_w32_filename (oldname, NULL);
4439 filename_to_ansi (oldname, oldname_a);
4440 filename_to_ansi (temp, temp_a);
4441 if ((o = strrchr (oldname_a, '\\')))
4442 o++;
4443 else
4444 o = (char *) oldname_a;
4445
4446 if ((p = strrchr (temp_a, '\\')))
4447 p++;
4448 else
4449 p = temp_a;
4450
4451 do
4452 {
4453 /* Force temp name to require a manufactured 8.3 alias - this
4454 seems to make the second rename work properly. */
4455 sprintf (p, "_.%s.%d", o, i);
4456 i++;
4457 result = rename (oldname_a, temp_a);
4458 }
4459 /* This loop must surely terminate! */
4460 while (result < 0 && errno == EEXIST);
4461 if (result < 0)
4462 return -1;
4463 have_temp_a = true;
4464 }
4465
4466 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4467 (at least if it is a file; don't do this for directories).
4468
4469 Since we mustn't do this if we are just changing the case of the
4470 file name (we would end up deleting the file we are trying to
4471 rename!), we let rename detect if the destination file already
4472 exists - that way we avoid the possible pitfalls of trying to
4473 determine ourselves whether two names really refer to the same
4474 file, which is not always possible in the general case. (Consider
4475 all the permutations of shared or subst'd drives, etc.) */
4476
4477 newname = map_w32_filename (newname, NULL);
4478
4479 /* volume_info is set indirectly by map_w32_filename. */
4480 newname_dev = volume_info.serialnum;
4481
4482 if (w32_unicode_filenames)
4483 {
4484 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
4485
4486 filename_to_utf16 (temp, temp_w);
4487 filename_to_utf16 (newname, newname_w);
4488 result = _wrename (temp_w, newname_w);
4489 if (result < 0 && force)
4490 {
4491 DWORD w32err = GetLastError ();
4492
4493 if (errno == EACCES
4494 && newname_dev != oldname_dev)
4495 {
4496 /* The implementation of `rename' on Windows does not return
4497 errno = EXDEV when you are moving a directory to a
4498 different storage device (ex. logical disk). It returns
4499 EACCES instead. So here we handle such situations and
4500 return EXDEV. */
4501 DWORD attributes;
4502
4503 if ((attributes = GetFileAttributesW (temp_w)) != -1
4504 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4505 errno = EXDEV;
4506 }
4507 else if (errno == EEXIST)
4508 {
4509 if (_wchmod (newname_w, 0666) != 0)
4510 return result;
4511 if (_wunlink (newname_w) != 0)
4512 return result;
4513 result = _wrename (temp_w, newname_w);
4514 }
4515 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4516 && is_symlink (temp))
4517 {
4518 /* This is Windows prohibiting the user from creating a
4519 symlink in another place, since that requires
4520 privileges. */
4521 errno = EPERM;
4522 }
4523 }
4524 }
4525 else
4526 {
4527 char newname_a[MAX_PATH];
4528
4529 if (!have_temp_a)
4530 filename_to_ansi (temp, temp_a);
4531 filename_to_ansi (newname, newname_a);
4532 result = rename (temp_a, newname_a);
4533 if (result < 0 && force)
4534 {
4535 DWORD w32err = GetLastError ();
4536
4537 if (errno == EACCES
4538 && newname_dev != oldname_dev)
4539 {
4540 DWORD attributes;
4541
4542 if ((attributes = GetFileAttributesA (temp_a)) != -1
4543 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
4544 errno = EXDEV;
4545 }
4546 else if (errno == EEXIST)
4547 {
4548 if (_chmod (newname_a, 0666) != 0)
4549 return result;
4550 if (_unlink (newname_a) != 0)
4551 return result;
4552 result = rename (temp_a, newname_a);
4553 }
4554 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
4555 && is_symlink (temp))
4556 errno = EPERM;
4557 }
4558 }
4559
4560 return result;
4561 }
4562
4563 int
4564 sys_rename (char const *old, char const *new)
4565 {
4566 return sys_rename_replace (old, new, TRUE);
4567 }
4568
4569 int
4570 sys_rmdir (const char * path)
4571 {
4572 path = map_w32_filename (path, NULL);
4573
4574 if (w32_unicode_filenames)
4575 {
4576 wchar_t path_w[MAX_PATH];
4577
4578 filename_to_utf16 (path, path_w);
4579 return _wrmdir (path_w);
4580 }
4581 else
4582 {
4583 char path_a[MAX_PATH];
4584
4585 filename_to_ansi (path, path_a);
4586 return _rmdir (path_a);
4587 }
4588 }
4589
4590 int
4591 sys_unlink (const char * path)
4592 {
4593 int rmstatus, e;
4594
4595 path = map_w32_filename (path, NULL);
4596
4597 if (w32_unicode_filenames)
4598 {
4599 wchar_t path_w[MAX_PATH];
4600
4601 filename_to_utf16 (path, path_w);
4602 /* On Unix, unlink works without write permission. */
4603 _wchmod (path_w, 0666);
4604 rmstatus = _wunlink (path_w);
4605 e = errno;
4606 /* Symlinks to directories can only be deleted by _rmdir;
4607 _unlink returns EACCES. */
4608 if (rmstatus != 0
4609 && errno == EACCES
4610 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4611 rmstatus = _wrmdir (path_w);
4612 else
4613 errno = e;
4614 }
4615 else
4616 {
4617 char path_a[MAX_PATH];
4618
4619 filename_to_ansi (path, path_a);
4620 _chmod (path_a, 0666);
4621 rmstatus = _unlink (path_a);
4622 e = errno;
4623 if (rmstatus != 0
4624 && errno == EACCES
4625 && (is_symlink (path) & FILE_ATTRIBUTE_DIRECTORY) != 0)
4626 rmstatus = _rmdir (path_a);
4627 else
4628 errno = e;
4629 }
4630
4631 return rmstatus;
4632 }
4633
4634 static FILETIME utc_base_ft;
4635 static ULONGLONG utc_base; /* In 100ns units */
4636 static int init = 0;
4637
4638 #define FILETIME_TO_U64(result, ft) \
4639 do { \
4640 ULARGE_INTEGER uiTemp; \
4641 uiTemp.LowPart = (ft).dwLowDateTime; \
4642 uiTemp.HighPart = (ft).dwHighDateTime; \
4643 result = uiTemp.QuadPart; \
4644 } while (0)
4645
4646 static void
4647 initialize_utc_base (void)
4648 {
4649 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4650 SYSTEMTIME st;
4651
4652 st.wYear = 1970;
4653 st.wMonth = 1;
4654 st.wDay = 1;
4655 st.wHour = 0;
4656 st.wMinute = 0;
4657 st.wSecond = 0;
4658 st.wMilliseconds = 0;
4659
4660 SystemTimeToFileTime (&st, &utc_base_ft);
4661 FILETIME_TO_U64 (utc_base, utc_base_ft);
4662 }
4663
4664 static time_t
4665 convert_time (FILETIME ft)
4666 {
4667 ULONGLONG tmp;
4668
4669 if (!init)
4670 {
4671 initialize_utc_base ();
4672 init = 1;
4673 }
4674
4675 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4676 return 0;
4677
4678 FILETIME_TO_U64 (tmp, ft);
4679 return (time_t) ((tmp - utc_base) / 10000000L);
4680 }
4681
4682 static void
4683 convert_from_time_t (time_t time, FILETIME * pft)
4684 {
4685 ULARGE_INTEGER tmp;
4686
4687 if (!init)
4688 {
4689 initialize_utc_base ();
4690 init = 1;
4691 }
4692
4693 /* time in 100ns units since 1-Jan-1601 */
4694 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4695 pft->dwHighDateTime = tmp.HighPart;
4696 pft->dwLowDateTime = tmp.LowPart;
4697 }
4698
4699 static PSECURITY_DESCRIPTOR
4700 get_file_security_desc_by_handle (HANDLE h)
4701 {
4702 PSECURITY_DESCRIPTOR psd = NULL;
4703 DWORD err;
4704 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4705 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4706
4707 err = get_security_info (h, SE_FILE_OBJECT, si,
4708 NULL, NULL, NULL, NULL, &psd);
4709 if (err != ERROR_SUCCESS)
4710 return NULL;
4711
4712 return psd;
4713 }
4714
4715 static PSECURITY_DESCRIPTOR
4716 get_file_security_desc_by_name (const char *fname)
4717 {
4718 PSECURITY_DESCRIPTOR psd = NULL;
4719 DWORD sd_len, err;
4720 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4721 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4722
4723 if (!get_file_security (fname, si, psd, 0, &sd_len))
4724 {
4725 err = GetLastError ();
4726 if (err != ERROR_INSUFFICIENT_BUFFER)
4727 return NULL;
4728 }
4729
4730 psd = xmalloc (sd_len);
4731 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4732 {
4733 xfree (psd);
4734 return NULL;
4735 }
4736
4737 return psd;
4738 }
4739
4740 static DWORD
4741 get_rid (PSID sid)
4742 {
4743 unsigned n_subauthorities;
4744
4745 /* Use the last sub-authority value of the RID, the relative
4746 portion of the SID, as user/group ID. */
4747 n_subauthorities = *get_sid_sub_authority_count (sid);
4748 if (n_subauthorities < 1)
4749 return 0; /* the "World" RID */
4750 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4751 }
4752
4753 /* Caching SID and account values for faster lokup. */
4754
4755 struct w32_id {
4756 unsigned rid;
4757 struct w32_id *next;
4758 char name[GNLEN+1];
4759 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4760 };
4761
4762 static struct w32_id *w32_idlist;
4763
4764 static int
4765 w32_cached_id (PSID sid, unsigned *id, char *name)
4766 {
4767 struct w32_id *tail, *found;
4768
4769 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4770 {
4771 if (equal_sid ((PSID)tail->sid, sid))
4772 {
4773 found = tail;
4774 break;
4775 }
4776 }
4777 if (found)
4778 {
4779 *id = found->rid;
4780 strcpy (name, found->name);
4781 return 1;
4782 }
4783 else
4784 return 0;
4785 }
4786
4787 static void
4788 w32_add_to_cache (PSID sid, unsigned id, char *name)
4789 {
4790 DWORD sid_len;
4791 struct w32_id *new_entry;
4792
4793 /* We don't want to leave behind stale cache from when Emacs was
4794 dumped. */
4795 if (initialized)
4796 {
4797 sid_len = get_length_sid (sid);
4798 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4799 if (new_entry)
4800 {
4801 new_entry->rid = id;
4802 strcpy (new_entry->name, name);
4803 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4804 new_entry->next = w32_idlist;
4805 w32_idlist = new_entry;
4806 }
4807 }
4808 }
4809
4810 #define UID 1
4811 #define GID 2
4812
4813 static int
4814 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
4815 {
4816 PSID sid = NULL;
4817 BOOL dflt;
4818 SID_NAME_USE ignore;
4819 char name[UNLEN+1];
4820 DWORD name_len = sizeof (name);
4821 char domain[1024];
4822 DWORD domain_len = sizeof (domain);
4823 int use_dflt = 0;
4824 int result;
4825
4826 if (what == UID)
4827 result = get_security_descriptor_owner (psd, &sid, &dflt);
4828 else if (what == GID)
4829 result = get_security_descriptor_group (psd, &sid, &dflt);
4830 else
4831 result = 0;
4832
4833 if (!result || !is_valid_sid (sid))
4834 use_dflt = 1;
4835 else if (!w32_cached_id (sid, id, nm))
4836 {
4837 if (!lookup_account_sid (NULL, sid, name, &name_len,
4838 domain, &domain_len, &ignore)
4839 || name_len > UNLEN+1)
4840 use_dflt = 1;
4841 else
4842 {
4843 *id = get_rid (sid);
4844 strcpy (nm, name);
4845 w32_add_to_cache (sid, *id, name);
4846 }
4847 }
4848 return use_dflt;
4849 }
4850
4851 static void
4852 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
4853 {
4854 int dflt_usr = 0, dflt_grp = 0;
4855
4856 if (!psd)
4857 {
4858 dflt_usr = 1;
4859 dflt_grp = 1;
4860 }
4861 else
4862 {
4863 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
4864 dflt_usr = 1;
4865 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
4866 dflt_grp = 1;
4867 }
4868 /* Consider files to belong to current user/group, if we cannot get
4869 more accurate information. */
4870 if (dflt_usr)
4871 {
4872 st->st_uid = dflt_passwd.pw_uid;
4873 strcpy (st->st_uname, dflt_passwd.pw_name);
4874 }
4875 if (dflt_grp)
4876 {
4877 st->st_gid = dflt_passwd.pw_gid;
4878 strcpy (st->st_gname, dflt_group.gr_name);
4879 }
4880 }
4881
4882 /* Return non-zero if NAME is a potentially slow filesystem. */
4883 int is_slow_fs (const char *);
4884
4885 int
4886 is_slow_fs (const char *name)
4887 {
4888 char drive_root[4];
4889 UINT devtype;
4890
4891 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4892 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4893 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4894 devtype = GetDriveType (NULL); /* use root of current drive */
4895 else
4896 {
4897 /* GetDriveType needs the root directory of the drive. */
4898 strncpy (drive_root, name, 2);
4899 drive_root[2] = '\\';
4900 drive_root[3] = '\0';
4901 devtype = GetDriveType (drive_root);
4902 }
4903 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4904 }
4905
4906 /* If this is non-zero, the caller wants accurate information about
4907 file's owner and group, which could be expensive to get. dired.c
4908 uses this flag when needed for the job at hand. */
4909 int w32_stat_get_owner_group;
4910
4911 /* MSVC stat function can't cope with UNC names and has other bugs, so
4912 replace it with our own. This also allows us to calculate consistent
4913 inode values and owner/group without hacks in the main Emacs code,
4914 and support file names encoded in UTF-8. */
4915
4916 static int
4917 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4918 {
4919 char *name, *save_name, *r;
4920 WIN32_FIND_DATAW wfd_w;
4921 WIN32_FIND_DATAA wfd_a;
4922 HANDLE fh;
4923 unsigned __int64 fake_inode = 0;
4924 int permission;
4925 int len;
4926 int rootdir = FALSE;
4927 PSECURITY_DESCRIPTOR psd = NULL;
4928 int is_a_symlink = 0;
4929 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4930 DWORD access_rights = 0;
4931 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4932 FILETIME ctime, atime, wtime;
4933 wchar_t name_w[MAX_PATH];
4934 char name_a[MAX_PATH];
4935
4936 if (path == NULL || buf == NULL)
4937 {
4938 errno = EFAULT;
4939 return -1;
4940 }
4941
4942 save_name = name = (char *) map_w32_filename (path, &path);
4943 /* Must be valid filename, no wild cards or other invalid
4944 characters. */
4945 if (strpbrk (name, "*?|<>\""))
4946 {
4947 errno = ENOENT;
4948 return -1;
4949 }
4950
4951 len = strlen (name);
4952 /* Allocate 1 extra byte so that we could append a slash to a root
4953 directory, down below. */
4954 name = strcpy (alloca (len + 2), name);
4955
4956 /* Avoid a somewhat costly call to is_symlink if the filesystem
4957 doesn't support symlinks. */
4958 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4959 is_a_symlink = is_symlink (name);
4960
4961 /* Plan A: Open the file and get all the necessary information via
4962 the resulting handle. This solves several issues in one blow:
4963
4964 . retrieves attributes for the target of a symlink, if needed
4965 . gets attributes of root directories and symlinks pointing to
4966 root directories, thus avoiding the need for special-casing
4967 these and detecting them by examining the file-name format
4968 . retrieves more accurate attributes (e.g., non-zero size for
4969 some directories, esp. directories that are junction points)
4970 . correctly resolves "c:/..", "/.." and similar file names
4971 . avoids run-time penalties for 99% of use cases
4972
4973 Plan A is always tried first, unless the user asked not to (but
4974 if the file is a symlink and we need to follow links, we try Plan
4975 A even if the user asked not to).
4976
4977 If Plan A fails, we go to Plan B (below), where various
4978 potentially expensive techniques must be used to handle "special"
4979 files such as UNC volumes etc. */
4980 if (!(NILP (Vw32_get_true_file_attributes)
4981 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4982 /* Following symlinks requires getting the info by handle. */
4983 || (is_a_symlink && follow_symlinks))
4984 {
4985 BY_HANDLE_FILE_INFORMATION info;
4986
4987 if (is_a_symlink && !follow_symlinks)
4988 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4989 /* READ_CONTROL access rights are required to get security info
4990 by handle. But if the OS doesn't support security in the
4991 first place, we don't need to try. */
4992 if (is_windows_9x () != TRUE)
4993 access_rights |= READ_CONTROL;
4994
4995 if (w32_unicode_filenames)
4996 {
4997 filename_to_utf16 (name, name_w);
4998 fh = CreateFileW (name_w, access_rights, 0, NULL, OPEN_EXISTING,
4999 file_flags, NULL);
5000 /* If CreateFile fails with READ_CONTROL, try again with
5001 zero as access rights. */
5002 if (fh == INVALID_HANDLE_VALUE && access_rights)
5003 fh = CreateFileW (name_w, 0, 0, NULL, OPEN_EXISTING,
5004 file_flags, NULL);
5005 }
5006 else
5007 {
5008 filename_to_ansi (name, name_a);
5009 fh = CreateFileA (name_a, access_rights, 0, NULL, OPEN_EXISTING,
5010 file_flags, NULL);
5011 if (fh == INVALID_HANDLE_VALUE && access_rights)
5012 fh = CreateFileA (name_a, 0, 0, NULL, OPEN_EXISTING,
5013 file_flags, NULL);
5014 }
5015 if (fh == INVALID_HANDLE_VALUE)
5016 goto no_true_file_attributes;
5017
5018 /* This is more accurate in terms of getting the correct number
5019 of links, but is quite slow (it is noticeable when Emacs is
5020 making a list of file name completions). */
5021 if (GetFileInformationByHandle (fh, &info))
5022 {
5023 nlinks = info.nNumberOfLinks;
5024 /* Might as well use file index to fake inode values, but this
5025 is not guaranteed to be unique unless we keep a handle open
5026 all the time (even then there are situations where it is
5027 not unique). Reputedly, there are at most 48 bits of info
5028 (on NTFS, presumably less on FAT). */
5029 fake_inode = info.nFileIndexHigh;
5030 fake_inode <<= 32;
5031 fake_inode += info.nFileIndexLow;
5032 serialnum = info.dwVolumeSerialNumber;
5033 fs_high = info.nFileSizeHigh;
5034 fs_low = info.nFileSizeLow;
5035 ctime = info.ftCreationTime;
5036 atime = info.ftLastAccessTime;
5037 wtime = info.ftLastWriteTime;
5038 fattrs = info.dwFileAttributes;
5039 }
5040 else
5041 {
5042 /* We don't go to Plan B here, because it's not clear that
5043 it's a good idea. The only known use case where
5044 CreateFile succeeds, but GetFileInformationByHandle fails
5045 (with ERROR_INVALID_FUNCTION) is for character devices
5046 such as NUL, PRN, etc. For these, switching to Plan B is
5047 a net loss, because we lose the character device
5048 attribute returned by GetFileType below (FindFirstFile
5049 doesn't set that bit in the attributes), and the other
5050 fields don't make sense for character devices anyway.
5051 Emacs doesn't really care for non-file entities in the
5052 context of l?stat, so neither do we. */
5053
5054 /* w32err is assigned so one could put a breakpoint here and
5055 examine its value, when GetFileInformationByHandle
5056 fails. */
5057 DWORD w32err = GetLastError ();
5058
5059 switch (w32err)
5060 {
5061 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
5062 errno = ENOENT;
5063 return -1;
5064 }
5065 }
5066
5067 /* Test for a symlink before testing for a directory, since
5068 symlinks to directories have the directory bit set, but we
5069 don't want them to appear as directories. */
5070 if (is_a_symlink && !follow_symlinks)
5071 buf->st_mode = S_IFLNK;
5072 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5073 buf->st_mode = S_IFDIR;
5074 else
5075 {
5076 DWORD ftype = GetFileType (fh);
5077
5078 switch (ftype)
5079 {
5080 case FILE_TYPE_DISK:
5081 buf->st_mode = S_IFREG;
5082 break;
5083 case FILE_TYPE_PIPE:
5084 buf->st_mode = S_IFIFO;
5085 break;
5086 case FILE_TYPE_CHAR:
5087 case FILE_TYPE_UNKNOWN:
5088 default:
5089 buf->st_mode = S_IFCHR;
5090 }
5091 }
5092 /* We produce the fallback owner and group data, based on the
5093 current user that runs Emacs, in the following cases:
5094
5095 . caller didn't request owner and group info
5096 . this is Windows 9X
5097 . getting security by handle failed, and we need to produce
5098 information for the target of a symlink (this is better
5099 than producing a potentially misleading info about the
5100 symlink itself)
5101
5102 If getting security by handle fails, and we don't need to
5103 resolve symlinks, we try getting security by name. */
5104 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5105 get_file_owner_and_group (NULL, buf);
5106 else
5107 {
5108 psd = get_file_security_desc_by_handle (fh);
5109 if (psd)
5110 {
5111 get_file_owner_and_group (psd, buf);
5112 LocalFree (psd);
5113 }
5114 else if (!(is_a_symlink && follow_symlinks))
5115 {
5116 psd = get_file_security_desc_by_name (name);
5117 get_file_owner_and_group (psd, buf);
5118 xfree (psd);
5119 }
5120 else
5121 get_file_owner_and_group (NULL, buf);
5122 }
5123 CloseHandle (fh);
5124 }
5125 else
5126 {
5127 no_true_file_attributes:
5128 /* Plan B: Either getting a handle on the file failed, or the
5129 caller explicitly asked us to not bother making this
5130 information more accurate.
5131
5132 Implementation note: In Plan B, we never bother to resolve
5133 symlinks, even if we got here because we tried Plan A and
5134 failed. That's because, even if the caller asked for extra
5135 precision by setting Vw32_get_true_file_attributes to t,
5136 resolving symlinks requires acquiring a file handle to the
5137 symlink, which we already know will fail. And if the user
5138 did not ask for extra precision, resolving symlinks will fly
5139 in the face of that request, since the user then wants the
5140 lightweight version of the code. */
5141 rootdir = (path >= save_name + len - 1
5142 && (IS_DIRECTORY_SEP (*path) || *path == 0));
5143
5144 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5145 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
5146 if (IS_DIRECTORY_SEP (r[0])
5147 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
5148 r[1] = r[2] = '\0';
5149
5150 /* Note: If NAME is a symlink to the root of a UNC volume
5151 (i.e. "\\SERVER"), we will not detect that here, and we will
5152 return data about the symlink as result of FindFirst below.
5153 This is unfortunate, but that marginal use case does not
5154 justify a call to chase_symlinks which would impose a penalty
5155 on all the other use cases. (We get here for symlinks to
5156 roots of UNC volumes because CreateFile above fails for them,
5157 unlike with symlinks to root directories X:\ of drives.) */
5158 if (is_unc_volume (name))
5159 {
5160 fattrs = unc_volume_file_attributes (name);
5161 if (fattrs == -1)
5162 return -1;
5163
5164 ctime = atime = wtime = utc_base_ft;
5165 }
5166 else if (rootdir)
5167 {
5168 /* Make sure root directories end in a slash. */
5169 if (!IS_DIRECTORY_SEP (name[len-1]))
5170 strcpy (name + len, "\\");
5171 if (GetDriveType (name) < 2)
5172 {
5173 errno = ENOENT;
5174 return -1;
5175 }
5176
5177 fattrs = FILE_ATTRIBUTE_DIRECTORY;
5178 ctime = atime = wtime = utc_base_ft;
5179 }
5180 else
5181 {
5182 int have_wfd = -1;
5183
5184 /* Make sure non-root directories do NOT end in a slash,
5185 otherwise FindFirstFile might fail. */
5186 if (IS_DIRECTORY_SEP (name[len-1]))
5187 name[len - 1] = 0;
5188
5189 /* (This is hacky, but helps when doing file completions on
5190 network drives.) Optimize by using information available from
5191 active readdir if possible. */
5192 len = strlen (dir_pathname);
5193 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
5194 len--;
5195 if (dir_find_handle != INVALID_HANDLE_VALUE
5196 && last_dir_find_data != -1
5197 && !(is_a_symlink && follow_symlinks)
5198 /* The 2 file-name comparisons below support only ASCII
5199 characters, and will lose (compare not equal) when
5200 the file names include non-ASCII characters that are
5201 the same but for the case. However, doing this
5202 properly involves: (a) converting both file names to
5203 UTF-16, (b) lower-casing both names using CharLowerW,
5204 and (c) comparing the results; this would be quite a
5205 bit slower, whereas Plan B is for users who want
5206 lightweight albeit inaccurate version of 'stat'. */
5207 && c_strncasecmp (save_name, dir_pathname, len) == 0
5208 && IS_DIRECTORY_SEP (name[len])
5209 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
5210 {
5211 have_wfd = last_dir_find_data;
5212 /* This was the last entry returned by readdir. */
5213 if (last_dir_find_data == DIR_FIND_DATA_W)
5214 wfd_w = dir_find_data_w;
5215 else
5216 wfd_a = dir_find_data_a;
5217 }
5218 else
5219 {
5220 logon_network_drive (name);
5221
5222 if (w32_unicode_filenames)
5223 {
5224 filename_to_utf16 (name, name_w);
5225 fh = FindFirstFileW (name_w, &wfd_w);
5226 have_wfd = DIR_FIND_DATA_W;
5227 }
5228 else
5229 {
5230 filename_to_ansi (name, name_a);
5231 /* If NAME includes characters not representable by
5232 the current ANSI codepage, filename_to_ansi
5233 usually replaces them with a '?'. We don't want
5234 to let FindFirstFileA interpret those as wildcards,
5235 and "succeed", returning us data from some random
5236 file in the same directory. */
5237 if (_mbspbrk (name_a, "?"))
5238 fh = INVALID_HANDLE_VALUE;
5239 else
5240 fh = FindFirstFileA (name_a, &wfd_a);
5241 have_wfd = DIR_FIND_DATA_A;
5242 }
5243 if (fh == INVALID_HANDLE_VALUE)
5244 {
5245 errno = ENOENT;
5246 return -1;
5247 }
5248 FindClose (fh);
5249 }
5250 /* Note: if NAME is a symlink, the information we get from
5251 FindFirstFile is for the symlink, not its target. */
5252 if (have_wfd == DIR_FIND_DATA_W)
5253 {
5254 fattrs = wfd_w.dwFileAttributes;
5255 ctime = wfd_w.ftCreationTime;
5256 atime = wfd_w.ftLastAccessTime;
5257 wtime = wfd_w.ftLastWriteTime;
5258 fs_high = wfd_w.nFileSizeHigh;
5259 fs_low = wfd_w.nFileSizeLow;
5260 }
5261 else
5262 {
5263 fattrs = wfd_a.dwFileAttributes;
5264 ctime = wfd_a.ftCreationTime;
5265 atime = wfd_a.ftLastAccessTime;
5266 wtime = wfd_a.ftLastWriteTime;
5267 fs_high = wfd_a.nFileSizeHigh;
5268 fs_low = wfd_a.nFileSizeLow;
5269 }
5270 fake_inode = 0;
5271 nlinks = 1;
5272 serialnum = volume_info.serialnum;
5273 }
5274 if (is_a_symlink && !follow_symlinks)
5275 buf->st_mode = S_IFLNK;
5276 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5277 buf->st_mode = S_IFDIR;
5278 else
5279 buf->st_mode = S_IFREG;
5280
5281 get_file_owner_and_group (NULL, buf);
5282 }
5283
5284 buf->st_ino = fake_inode;
5285
5286 buf->st_dev = serialnum;
5287 buf->st_rdev = serialnum;
5288
5289 buf->st_size = fs_high;
5290 buf->st_size <<= 32;
5291 buf->st_size += fs_low;
5292 buf->st_nlink = nlinks;
5293
5294 /* Convert timestamps to Unix format. */
5295 buf->st_mtime = convert_time (wtime);
5296 buf->st_atime = convert_time (atime);
5297 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5298 buf->st_ctime = convert_time (ctime);
5299 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5300
5301 /* determine rwx permissions */
5302 if (is_a_symlink && !follow_symlinks)
5303 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
5304 else
5305 {
5306 if (fattrs & FILE_ATTRIBUTE_READONLY)
5307 permission = S_IREAD;
5308 else
5309 permission = S_IREAD | S_IWRITE;
5310
5311 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
5312 permission |= S_IEXEC;
5313 else if (is_exec (name))
5314 permission |= S_IEXEC;
5315 }
5316
5317 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5318
5319 return 0;
5320 }
5321
5322 int
5323 stat (const char * path, struct stat * buf)
5324 {
5325 return stat_worker (path, buf, 1);
5326 }
5327
5328 int
5329 lstat (const char * path, struct stat * buf)
5330 {
5331 return stat_worker (path, buf, 0);
5332 }
5333
5334 int
5335 fstatat (int fd, char const *name, struct stat *st, int flags)
5336 {
5337 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5338 This is good enough for the current usage in Emacs, but is fragile.
5339
5340 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5341 Gnulib does this and can serve as a model. */
5342 char fullname[MAX_UTF8_PATH];
5343
5344 if (fd != AT_FDCWD)
5345 {
5346 char lastc = dir_pathname[strlen (dir_pathname) - 1];
5347
5348 if (_snprintf (fullname, sizeof fullname, "%s%s%s",
5349 dir_pathname, IS_DIRECTORY_SEP (lastc) ? "" : "/", name)
5350 < 0)
5351 {
5352 errno = ENAMETOOLONG;
5353 return -1;
5354 }
5355 name = fullname;
5356 }
5357
5358 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
5359 }
5360
5361 /* Provide fstat and utime as well as stat for consistent handling of
5362 file timestamps. */
5363 int
5364 fstat (int desc, struct stat * buf)
5365 {
5366 HANDLE fh = (HANDLE) _get_osfhandle (desc);
5367 BY_HANDLE_FILE_INFORMATION info;
5368 unsigned __int64 fake_inode;
5369 int permission;
5370
5371 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
5372 {
5373 case FILE_TYPE_DISK:
5374 buf->st_mode = S_IFREG;
5375 if (!GetFileInformationByHandle (fh, &info))
5376 {
5377 errno = EACCES;
5378 return -1;
5379 }
5380 break;
5381 case FILE_TYPE_PIPE:
5382 buf->st_mode = S_IFIFO;
5383 goto non_disk;
5384 case FILE_TYPE_CHAR:
5385 case FILE_TYPE_UNKNOWN:
5386 default:
5387 buf->st_mode = S_IFCHR;
5388 non_disk:
5389 memset (&info, 0, sizeof (info));
5390 info.dwFileAttributes = 0;
5391 info.ftCreationTime = utc_base_ft;
5392 info.ftLastAccessTime = utc_base_ft;
5393 info.ftLastWriteTime = utc_base_ft;
5394 }
5395
5396 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5397 buf->st_mode = S_IFDIR;
5398
5399 buf->st_nlink = info.nNumberOfLinks;
5400 /* Might as well use file index to fake inode values, but this
5401 is not guaranteed to be unique unless we keep a handle open
5402 all the time (even then there are situations where it is
5403 not unique). Reputedly, there are at most 48 bits of info
5404 (on NTFS, presumably less on FAT). */
5405 fake_inode = info.nFileIndexHigh;
5406 fake_inode <<= 32;
5407 fake_inode += info.nFileIndexLow;
5408
5409 /* MSVC defines _ino_t to be short; other libc's might not. */
5410 if (sizeof (buf->st_ino) == 2)
5411 buf->st_ino = fake_inode ^ (fake_inode >> 16);
5412 else
5413 buf->st_ino = fake_inode;
5414
5415 /* If the caller so requested, get the true file owner and group.
5416 Otherwise, consider the file to belong to the current user. */
5417 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
5418 get_file_owner_and_group (NULL, buf);
5419 else
5420 {
5421 PSECURITY_DESCRIPTOR psd = NULL;
5422
5423 psd = get_file_security_desc_by_handle (fh);
5424 if (psd)
5425 {
5426 get_file_owner_and_group (psd, buf);
5427 LocalFree (psd);
5428 }
5429 else
5430 get_file_owner_and_group (NULL, buf);
5431 }
5432
5433 buf->st_dev = info.dwVolumeSerialNumber;
5434 buf->st_rdev = info.dwVolumeSerialNumber;
5435
5436 buf->st_size = info.nFileSizeHigh;
5437 buf->st_size <<= 32;
5438 buf->st_size += info.nFileSizeLow;
5439
5440 /* Convert timestamps to Unix format. */
5441 buf->st_mtime = convert_time (info.ftLastWriteTime);
5442 buf->st_atime = convert_time (info.ftLastAccessTime);
5443 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
5444 buf->st_ctime = convert_time (info.ftCreationTime);
5445 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
5446
5447 /* determine rwx permissions */
5448 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
5449 permission = S_IREAD;
5450 else
5451 permission = S_IREAD | S_IWRITE;
5452
5453 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
5454 permission |= S_IEXEC;
5455 else
5456 {
5457 #if 0 /* no way of knowing the filename */
5458 char * p = strrchr (name, '.');
5459 if (p != NULL &&
5460 (xstrcasecmp (p, ".exe") == 0 ||
5461 xstrcasecmp (p, ".com") == 0 ||
5462 xstrcasecmp (p, ".bat") == 0 ||
5463 xstrcasecmp (p, ".cmd") == 0))
5464 permission |= S_IEXEC;
5465 #endif
5466 }
5467
5468 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
5469
5470 return 0;
5471 }
5472
5473 /* A version of 'utime' which handles directories as well as
5474 files. */
5475
5476 int
5477 utime (const char *name, struct utimbuf *times)
5478 {
5479 struct utimbuf deftime;
5480 HANDLE fh;
5481 FILETIME mtime;
5482 FILETIME atime;
5483
5484 if (times == NULL)
5485 {
5486 deftime.modtime = deftime.actime = time (NULL);
5487 times = &deftime;
5488 }
5489
5490 if (w32_unicode_filenames)
5491 {
5492 wchar_t name_utf16[MAX_PATH];
5493
5494 if (filename_to_utf16 (name, name_utf16) != 0)
5495 return -1; /* errno set by filename_to_utf16 */
5496
5497 /* Need write access to set times. */
5498 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
5499 /* If NAME specifies a directory, FILE_SHARE_DELETE
5500 allows other processes to delete files inside it,
5501 while we have the directory open. */
5502 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5503 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5504 }
5505 else
5506 {
5507 char name_ansi[MAX_PATH];
5508
5509 if (filename_to_ansi (name, name_ansi) != 0)
5510 return -1; /* errno set by filename_to_ansi */
5511
5512 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
5513 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
5514 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5515 }
5516 if (fh != INVALID_HANDLE_VALUE)
5517 {
5518 convert_from_time_t (times->actime, &atime);
5519 convert_from_time_t (times->modtime, &mtime);
5520 if (!SetFileTime (fh, NULL, &atime, &mtime))
5521 {
5522 CloseHandle (fh);
5523 errno = EACCES;
5524 return -1;
5525 }
5526 CloseHandle (fh);
5527 }
5528 else
5529 {
5530 DWORD err = GetLastError ();
5531
5532 switch (err)
5533 {
5534 case ERROR_FILE_NOT_FOUND:
5535 case ERROR_PATH_NOT_FOUND:
5536 case ERROR_INVALID_DRIVE:
5537 case ERROR_BAD_NETPATH:
5538 case ERROR_DEV_NOT_EXIST:
5539 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5540 file name includes ?s, i.e. translation to ANSI failed. */
5541 case ERROR_INVALID_NAME:
5542 errno = ENOENT;
5543 break;
5544 case ERROR_TOO_MANY_OPEN_FILES:
5545 errno = ENFILE;
5546 break;
5547 case ERROR_ACCESS_DENIED:
5548 case ERROR_SHARING_VIOLATION:
5549 errno = EACCES;
5550 break;
5551 default:
5552 errno = EINVAL;
5553 break;
5554 }
5555 return -1;
5556 }
5557 return 0;
5558 }
5559
5560 int
5561 sys_umask (int mode)
5562 {
5563 static int current_mask;
5564 int retval, arg = 0;
5565
5566 /* The only bit we really support is the write bit. Files are
5567 always readable on MS-Windows, and the execute bit does not exist
5568 at all. */
5569 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5570 to prevent access by other users on NTFS. */
5571 if ((mode & S_IWRITE) != 0)
5572 arg |= S_IWRITE;
5573
5574 retval = _umask (arg);
5575 /* Merge into the return value the bits they've set the last time,
5576 which msvcrt.dll ignores and never returns. Emacs insists on its
5577 notion of mask being identical to what we return. */
5578 retval |= (current_mask & ~S_IWRITE);
5579 current_mask = mode;
5580
5581 return retval;
5582 }
5583
5584 \f
5585 /* Symlink-related functions. */
5586 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5587 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5588 #endif
5589
5590 int
5591 symlink (char const *filename, char const *linkname)
5592 {
5593 char linkfn[MAX_UTF8_PATH], *tgtfn;
5594 DWORD flags = 0;
5595 int dir_access, filename_ends_in_slash;
5596
5597 /* Diagnostics follows Posix as much as possible. */
5598 if (filename == NULL || linkname == NULL)
5599 {
5600 errno = EFAULT;
5601 return -1;
5602 }
5603 if (!*filename)
5604 {
5605 errno = ENOENT;
5606 return -1;
5607 }
5608 if (strlen (filename) > MAX_UTF8_PATH || strlen (linkname) > MAX_UTF8_PATH)
5609 {
5610 errno = ENAMETOOLONG;
5611 return -1;
5612 }
5613
5614 strcpy (linkfn, map_w32_filename (linkname, NULL));
5615 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
5616 {
5617 errno = EPERM;
5618 return -1;
5619 }
5620
5621 /* Note: since empty FILENAME was already rejected, we can safely
5622 refer to FILENAME[1]. */
5623 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5624 {
5625 /* Non-absolute FILENAME is understood as being relative to
5626 LINKNAME's directory. We need to prepend that directory to
5627 FILENAME to get correct results from faccessat below, since
5628 otherwise it will interpret FILENAME relative to the
5629 directory where the Emacs process runs. Note that
5630 make-symbolic-link always makes sure LINKNAME is a fully
5631 expanded file name. */
5632 char tem[MAX_UTF8_PATH];
5633 char *p = linkfn + strlen (linkfn);
5634
5635 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5636 p--;
5637 if (p > linkfn)
5638 strncpy (tem, linkfn, p - linkfn);
5639 strcpy (tem + (p - linkfn), filename);
5640 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5641 }
5642 else
5643 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5644
5645 /* Since Windows distinguishes between symlinks to directories and
5646 to files, we provide a kludgy feature: if FILENAME doesn't
5647 exist, but ends in a slash, we create a symlink to directory. If
5648 FILENAME exists and is a directory, we always create a symlink to
5649 directory. */
5650 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5651 if (dir_access == 0 || filename_ends_in_slash)
5652 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5653
5654 tgtfn = (char *)map_w32_filename (filename, NULL);
5655 if (filename_ends_in_slash)
5656 tgtfn[strlen (tgtfn) - 1] = '\0';
5657
5658 errno = 0;
5659 if (!create_symbolic_link (linkfn, tgtfn, flags))
5660 {
5661 /* ENOSYS is set by create_symbolic_link, when it detects that
5662 the OS doesn't support the CreateSymbolicLink API. */
5663 if (errno != ENOSYS)
5664 {
5665 DWORD w32err = GetLastError ();
5666
5667 switch (w32err)
5668 {
5669 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5670 TGTFN point to the same file name, go figure. */
5671 case ERROR_SUCCESS:
5672 case ERROR_FILE_EXISTS:
5673 errno = EEXIST;
5674 break;
5675 case ERROR_ACCESS_DENIED:
5676 errno = EACCES;
5677 break;
5678 case ERROR_FILE_NOT_FOUND:
5679 case ERROR_PATH_NOT_FOUND:
5680 case ERROR_BAD_NETPATH:
5681 case ERROR_INVALID_REPARSE_DATA:
5682 errno = ENOENT;
5683 break;
5684 case ERROR_DIRECTORY:
5685 errno = EISDIR;
5686 break;
5687 case ERROR_PRIVILEGE_NOT_HELD:
5688 case ERROR_NOT_ALL_ASSIGNED:
5689 errno = EPERM;
5690 break;
5691 case ERROR_DISK_FULL:
5692 errno = ENOSPC;
5693 break;
5694 default:
5695 errno = EINVAL;
5696 break;
5697 }
5698 }
5699 return -1;
5700 }
5701 return 0;
5702 }
5703
5704 /* A quick inexpensive test of whether FILENAME identifies a file that
5705 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5706 must already be in the normalized form returned by
5707 map_w32_filename. If the symlink is to a directory, the
5708 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5709
5710 Note: for repeated operations on many files, it is best to test
5711 whether the underlying volume actually supports symlinks, by
5712 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5713 avoid the call to this function if it doesn't. That's because the
5714 call to GetFileAttributes takes a non-negligible time, especially
5715 on non-local or removable filesystems. See stat_worker for an
5716 example of how to do that. */
5717 static int
5718 is_symlink (const char *filename)
5719 {
5720 DWORD attrs;
5721 wchar_t filename_w[MAX_PATH];
5722 char filename_a[MAX_PATH];
5723 WIN32_FIND_DATAW wfdw;
5724 WIN32_FIND_DATAA wfda;
5725 HANDLE fh;
5726 int attrs_mean_symlink;
5727
5728 if (w32_unicode_filenames)
5729 {
5730 filename_to_utf16 (filename, filename_w);
5731 attrs = GetFileAttributesW (filename_w);
5732 }
5733 else
5734 {
5735 filename_to_ansi (filename, filename_a);
5736 attrs = GetFileAttributesA (filename_a);
5737 }
5738 if (attrs == -1)
5739 {
5740 DWORD w32err = GetLastError ();
5741
5742 switch (w32err)
5743 {
5744 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5745 break;
5746 case ERROR_ACCESS_DENIED:
5747 errno = EACCES;
5748 break;
5749 case ERROR_FILE_NOT_FOUND:
5750 case ERROR_PATH_NOT_FOUND:
5751 default:
5752 errno = ENOENT;
5753 break;
5754 }
5755 return 0;
5756 }
5757 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5758 return 0;
5759 logon_network_drive (filename);
5760 if (w32_unicode_filenames)
5761 {
5762 fh = FindFirstFileW (filename_w, &wfdw);
5763 attrs_mean_symlink =
5764 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5765 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5766 if (attrs_mean_symlink)
5767 attrs_mean_symlink |= (wfdw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5768 }
5769 else if (_mbspbrk (filename_a, "?"))
5770 {
5771 /* filename_to_ansi failed to convert the file name. */
5772 errno = ENOENT;
5773 return 0;
5774 }
5775 else
5776 {
5777 fh = FindFirstFileA (filename_a, &wfda);
5778 attrs_mean_symlink =
5779 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5780 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5781 if (attrs_mean_symlink)
5782 attrs_mean_symlink |= (wfda.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
5783 }
5784 if (fh == INVALID_HANDLE_VALUE)
5785 return 0;
5786 FindClose (fh);
5787 return attrs_mean_symlink;
5788 }
5789
5790 /* If NAME identifies a symbolic link, copy into BUF the file name of
5791 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5792 null-terminate the target name, even if it fits. Return the number
5793 of bytes copied, or -1 if NAME is not a symlink or any error was
5794 encountered while resolving it. The file name copied into BUF is
5795 encoded in the current ANSI codepage. */
5796 ssize_t
5797 readlink (const char *name, char *buf, size_t buf_size)
5798 {
5799 const char *path;
5800 TOKEN_PRIVILEGES privs;
5801 int restore_privs = 0;
5802 HANDLE sh;
5803 ssize_t retval;
5804 char resolved[MAX_UTF8_PATH];
5805
5806 if (name == NULL)
5807 {
5808 errno = EFAULT;
5809 return -1;
5810 }
5811 if (!*name)
5812 {
5813 errno = ENOENT;
5814 return -1;
5815 }
5816
5817 path = map_w32_filename (name, NULL);
5818
5819 if (strlen (path) > MAX_UTF8_PATH)
5820 {
5821 errno = ENAMETOOLONG;
5822 return -1;
5823 }
5824
5825 errno = 0;
5826 if (is_windows_9x () == TRUE
5827 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5828 || !is_symlink (path))
5829 {
5830 if (!errno)
5831 errno = EINVAL; /* not a symlink */
5832 return -1;
5833 }
5834
5835 /* Done with simple tests, now we're in for some _real_ work. */
5836 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5837 restore_privs = 1;
5838 /* Implementation note: From here and onward, don't return early,
5839 since that will fail to restore the original set of privileges of
5840 the calling thread. */
5841
5842 retval = -1; /* not too optimistic, are we? */
5843
5844 /* Note: In the next call to CreateFile, we use zero as the 2nd
5845 argument because, when the symlink is a hidden/system file,
5846 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5847 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5848 and directory symlinks. */
5849 if (w32_unicode_filenames)
5850 {
5851 wchar_t path_w[MAX_PATH];
5852
5853 filename_to_utf16 (path, path_w);
5854 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5855 FILE_FLAG_OPEN_REPARSE_POINT
5856 | FILE_FLAG_BACKUP_SEMANTICS,
5857 NULL);
5858 }
5859 else
5860 {
5861 char path_a[MAX_PATH];
5862
5863 filename_to_ansi (path, path_a);
5864 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5865 FILE_FLAG_OPEN_REPARSE_POINT
5866 | FILE_FLAG_BACKUP_SEMANTICS,
5867 NULL);
5868 }
5869 if (sh != INVALID_HANDLE_VALUE)
5870 {
5871 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5872 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5873 DWORD retbytes;
5874
5875 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5876 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5877 &retbytes, NULL))
5878 errno = EIO;
5879 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5880 errno = EINVAL;
5881 else
5882 {
5883 /* Copy the link target name, in wide characters, from
5884 reparse_data, then convert it to multibyte encoding in
5885 the current locale's codepage. */
5886 WCHAR *lwname;
5887 size_t lname_size;
5888 USHORT lwname_len =
5889 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5890 WCHAR *lwname_src =
5891 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5892 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5893 size_t size_to_copy = buf_size;
5894
5895 /* According to MSDN, PrintNameLength does not include the
5896 terminating null character. */
5897 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5898 memcpy (lwname, lwname_src, lwname_len);
5899 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5900 filename_from_utf16 (lwname, resolved);
5901 dostounix_filename (resolved);
5902 lname_size = strlen (resolved) + 1;
5903 if (lname_size <= buf_size)
5904 size_to_copy = lname_size;
5905 strncpy (buf, resolved, size_to_copy);
5906 /* Success! */
5907 retval = size_to_copy;
5908 }
5909 CloseHandle (sh);
5910 }
5911 else
5912 {
5913 /* CreateFile failed. */
5914 DWORD w32err2 = GetLastError ();
5915
5916 switch (w32err2)
5917 {
5918 case ERROR_FILE_NOT_FOUND:
5919 case ERROR_PATH_NOT_FOUND:
5920 errno = ENOENT;
5921 break;
5922 case ERROR_ACCESS_DENIED:
5923 case ERROR_TOO_MANY_OPEN_FILES:
5924 errno = EACCES;
5925 break;
5926 default:
5927 errno = EPERM;
5928 break;
5929 }
5930 }
5931 if (restore_privs)
5932 {
5933 restore_privilege (&privs);
5934 revert_to_self ();
5935 }
5936
5937 return retval;
5938 }
5939
5940 ssize_t
5941 readlinkat (int fd, char const *name, char *buffer,
5942 size_t buffer_size)
5943 {
5944 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5945 as in fstatat. FIXME: Add proper support for readlinkat. */
5946 char fullname[MAX_UTF8_PATH];
5947
5948 if (fd != AT_FDCWD)
5949 {
5950 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5951 < 0)
5952 {
5953 errno = ENAMETOOLONG;
5954 return -1;
5955 }
5956 name = fullname;
5957 }
5958
5959 return readlink (name, buffer, buffer_size);
5960 }
5961
5962 /* If FILE is a symlink, return its target (stored in a static
5963 buffer); otherwise return FILE.
5964
5965 This function repeatedly resolves symlinks in the last component of
5966 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5967 until it arrives at a file whose last component is not a symlink,
5968 or some error occurs. It returns the target of the last
5969 successfully resolved symlink in the chain. If it succeeds to
5970 resolve even a single symlink, the value returned is an absolute
5971 file name with backslashes (result of GetFullPathName). By
5972 contrast, if the original FILE is returned, it is unaltered.
5973
5974 Note: This function can set errno even if it succeeds.
5975
5976 Implementation note: we only resolve the last portion ("basename")
5977 of the argument FILE and of each following file in the chain,
5978 disregarding any possible symlinks in its leading directories.
5979 This is because Windows system calls and library functions
5980 transparently resolve symlinks in leading directories and return
5981 correct information, as long as the basename is not a symlink. */
5982 static char *
5983 chase_symlinks (const char *file)
5984 {
5985 static char target[MAX_UTF8_PATH];
5986 char link[MAX_UTF8_PATH];
5987 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5988 char target_a[MAX_PATH], link_a[MAX_PATH];
5989 ssize_t res, link_len;
5990 int loop_count = 0;
5991
5992 if (is_windows_9x () == TRUE || !is_symlink (file))
5993 return (char *)file;
5994
5995 if (w32_unicode_filenames)
5996 {
5997 wchar_t file_w[MAX_PATH];
5998
5999 filename_to_utf16 (file, file_w);
6000 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
6001 return (char *)file;
6002 filename_from_utf16 (link_w, link);
6003 }
6004 else
6005 {
6006 char file_a[MAX_PATH];
6007
6008 filename_to_ansi (file, file_a);
6009 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
6010 return (char *)file;
6011 filename_from_ansi (link_a, link);
6012 }
6013 link_len = strlen (link);
6014
6015 target[0] = '\0';
6016 do {
6017
6018 /* Remove trailing slashes, as we want to resolve the last
6019 non-trivial part of the link name. */
6020 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
6021 link[link_len--] = '\0';
6022
6023 res = readlink (link, target, MAX_UTF8_PATH);
6024 if (res > 0)
6025 {
6026 target[res] = '\0';
6027 if (!(IS_DEVICE_SEP (target[1])
6028 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6029 {
6030 /* Target is relative. Append it to the directory part of
6031 the symlink, then copy the result back to target. */
6032 char *p = link + link_len;
6033
6034 while (p > link && !IS_ANY_SEP (p[-1]))
6035 p--;
6036 strcpy (p, target);
6037 strcpy (target, link);
6038 }
6039 /* Resolve any "." and ".." to get a fully-qualified file name
6040 in link[] again. */
6041 if (w32_unicode_filenames)
6042 {
6043 filename_to_utf16 (target, target_w);
6044 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
6045 if (link_len > 0)
6046 filename_from_utf16 (link_w, link);
6047 }
6048 else
6049 {
6050 filename_to_ansi (target, target_a);
6051 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
6052 if (link_len > 0)
6053 filename_from_ansi (link_a, link);
6054 }
6055 link_len = strlen (link);
6056 }
6057 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
6058
6059 if (loop_count > 100)
6060 errno = ELOOP;
6061
6062 if (target[0] == '\0') /* not a single call to readlink succeeded */
6063 return (char *)file;
6064 return target;
6065 }
6066
6067 \f
6068 /* Posix ACL emulation. */
6069
6070 int
6071 acl_valid (acl_t acl)
6072 {
6073 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
6074 }
6075
6076 char *
6077 acl_to_text (acl_t acl, ssize_t *size)
6078 {
6079 LPTSTR str_acl;
6080 SECURITY_INFORMATION flags =
6081 OWNER_SECURITY_INFORMATION |
6082 GROUP_SECURITY_INFORMATION |
6083 DACL_SECURITY_INFORMATION;
6084 char *retval = NULL;
6085 ULONG local_size;
6086 int e = errno;
6087
6088 errno = 0;
6089
6090 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
6091 {
6092 errno = e;
6093 /* We don't want to mix heaps, so we duplicate the string in our
6094 heap and free the one allocated by the API. */
6095 retval = xstrdup (str_acl);
6096 if (size)
6097 *size = local_size;
6098 LocalFree (str_acl);
6099 }
6100 else if (errno != ENOTSUP)
6101 errno = EINVAL;
6102
6103 return retval;
6104 }
6105
6106 acl_t
6107 acl_from_text (const char *acl_str)
6108 {
6109 PSECURITY_DESCRIPTOR psd, retval = NULL;
6110 ULONG sd_size;
6111 int e = errno;
6112
6113 errno = 0;
6114
6115 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
6116 {
6117 errno = e;
6118 retval = xmalloc (sd_size);
6119 memcpy (retval, psd, sd_size);
6120 LocalFree (psd);
6121 }
6122 else if (errno != ENOTSUP)
6123 errno = EINVAL;
6124
6125 return retval;
6126 }
6127
6128 int
6129 acl_free (void *ptr)
6130 {
6131 xfree (ptr);
6132 return 0;
6133 }
6134
6135 acl_t
6136 acl_get_file (const char *fname, acl_type_t type)
6137 {
6138 PSECURITY_DESCRIPTOR psd = NULL;
6139 const char *filename;
6140
6141 if (type == ACL_TYPE_ACCESS)
6142 {
6143 DWORD sd_len, err;
6144 SECURITY_INFORMATION si =
6145 OWNER_SECURITY_INFORMATION |
6146 GROUP_SECURITY_INFORMATION |
6147 DACL_SECURITY_INFORMATION ;
6148 int e = errno;
6149
6150 filename = map_w32_filename (fname, NULL);
6151 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6152 fname = chase_symlinks (filename);
6153 else
6154 fname = filename;
6155
6156 errno = 0;
6157 if (!get_file_security (fname, si, psd, 0, &sd_len)
6158 && errno != ENOTSUP)
6159 {
6160 err = GetLastError ();
6161 if (err == ERROR_INSUFFICIENT_BUFFER)
6162 {
6163 psd = xmalloc (sd_len);
6164 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
6165 {
6166 xfree (psd);
6167 errno = EIO;
6168 psd = NULL;
6169 }
6170 }
6171 else if (err == ERROR_FILE_NOT_FOUND
6172 || err == ERROR_PATH_NOT_FOUND
6173 /* ERROR_INVALID_NAME is what we get if
6174 w32-unicode-filenames is nil and the file cannot
6175 be encoded in the current ANSI codepage. */
6176 || err == ERROR_INVALID_NAME)
6177 errno = ENOENT;
6178 else
6179 errno = EIO;
6180 }
6181 else if (!errno)
6182 errno = e;
6183 }
6184 else if (type != ACL_TYPE_DEFAULT)
6185 errno = EINVAL;
6186
6187 return psd;
6188 }
6189
6190 int
6191 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
6192 {
6193 TOKEN_PRIVILEGES old1, old2;
6194 DWORD err;
6195 int st = 0, retval = -1;
6196 SECURITY_INFORMATION flags = 0;
6197 PSID psidOwner, psidGroup;
6198 PACL pacl;
6199 BOOL dflt;
6200 BOOL dacl_present;
6201 int e;
6202 const char *filename;
6203
6204 if (acl_valid (acl) != 0
6205 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6206 {
6207 errno = EINVAL;
6208 return -1;
6209 }
6210
6211 if (type == ACL_TYPE_DEFAULT)
6212 {
6213 errno = ENOSYS;
6214 return -1;
6215 }
6216
6217 filename = map_w32_filename (fname, NULL);
6218 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6219 fname = chase_symlinks (filename);
6220 else
6221 fname = filename;
6222
6223 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6224 &dflt)
6225 && psidOwner)
6226 flags |= OWNER_SECURITY_INFORMATION;
6227 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6228 &dflt)
6229 && psidGroup)
6230 flags |= GROUP_SECURITY_INFORMATION;
6231 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6232 &pacl, &dflt)
6233 && dacl_present)
6234 flags |= DACL_SECURITY_INFORMATION;
6235 if (!flags)
6236 return 0;
6237
6238 /* According to KB-245153, setting the owner will succeed if either:
6239 (1) the caller is the user who will be the new owner, and has the
6240 SE_TAKE_OWNERSHIP privilege, or
6241 (2) the caller has the SE_RESTORE privilege, in which case she can
6242 set any valid user or group as the owner
6243
6244 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6245 privileges, and disregard any failures in obtaining them. If
6246 these privileges cannot be obtained, and do not already exist in
6247 the calling thread's security token, this function could fail
6248 with EPERM. */
6249 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6250 st++;
6251 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6252 st++;
6253
6254 e = errno;
6255 errno = 0;
6256 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6257 DACL inheritance is involved, but it seems to preserve ownership
6258 better than SetNamedSecurityInfo, which is important e.g., in
6259 copy-file. */
6260 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6261 {
6262 err = GetLastError ();
6263
6264 if (errno != ENOTSUP)
6265 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6266 psidOwner, psidGroup, pacl, NULL);
6267 }
6268 else
6269 err = ERROR_SUCCESS;
6270 if (err != ERROR_SUCCESS)
6271 {
6272 if (errno == ENOTSUP)
6273 ;
6274 else if (err == ERROR_INVALID_OWNER
6275 || err == ERROR_NOT_ALL_ASSIGNED
6276 || err == ERROR_ACCESS_DENIED)
6277 {
6278 /* Maybe the requested ACL and the one the file already has
6279 are identical, in which case we can silently ignore the
6280 failure. (And no, Windows doesn't.) */
6281 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6282
6283 errno = EPERM;
6284 if (current_acl)
6285 {
6286 char *acl_from = acl_to_text (current_acl, NULL);
6287 char *acl_to = acl_to_text (acl, NULL);
6288
6289 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6290 {
6291 retval = 0;
6292 errno = e;
6293 }
6294 if (acl_from)
6295 acl_free (acl_from);
6296 if (acl_to)
6297 acl_free (acl_to);
6298 acl_free (current_acl);
6299 }
6300 }
6301 else if (err == ERROR_FILE_NOT_FOUND
6302 || err == ERROR_PATH_NOT_FOUND
6303 /* ERROR_INVALID_NAME is what we get if
6304 w32-unicode-filenames is nil and the file cannot be
6305 encoded in the current ANSI codepage. */
6306 || err == ERROR_INVALID_NAME)
6307 errno = ENOENT;
6308 else
6309 errno = EACCES;
6310 }
6311 else
6312 {
6313 retval = 0;
6314 errno = e;
6315 }
6316
6317 if (st)
6318 {
6319 if (st >= 2)
6320 restore_privilege (&old2);
6321 restore_privilege (&old1);
6322 revert_to_self ();
6323 }
6324
6325 return retval;
6326 }
6327
6328 \f
6329 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6330 have a fixed max size for file names, so we don't need the kind of
6331 alloc/malloc/realloc dance the gnulib version does. We also don't
6332 support FD-relative symlinks. */
6333 char *
6334 careadlinkat (int fd, char const *filename,
6335 char *buffer, size_t buffer_size,
6336 struct allocator const *alloc,
6337 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6338 {
6339 char linkname[MAX_UTF8_PATH];
6340 ssize_t link_size;
6341
6342 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6343
6344 if (link_size > 0)
6345 {
6346 char *retval = buffer;
6347
6348 linkname[link_size++] = '\0';
6349 if (link_size > buffer_size)
6350 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6351 if (retval)
6352 memcpy (retval, linkname, link_size);
6353
6354 return retval;
6355 }
6356 return NULL;
6357 }
6358
6359 int
6360 w32_copy_file (const char *from, const char *to,
6361 int keep_time, int preserve_ownership, int copy_acls)
6362 {
6363 acl_t acl = NULL;
6364 BOOL copy_result;
6365 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6366 char from_a[MAX_PATH], to_a[MAX_PATH];
6367
6368 /* We ignore preserve_ownership for now. */
6369 preserve_ownership = preserve_ownership;
6370
6371 if (copy_acls)
6372 {
6373 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6374 if (acl == NULL && acl_errno_valid (errno))
6375 return -2;
6376 }
6377 if (w32_unicode_filenames)
6378 {
6379 filename_to_utf16 (from, from_w);
6380 filename_to_utf16 (to, to_w);
6381 copy_result = CopyFileW (from_w, to_w, FALSE);
6382 }
6383 else
6384 {
6385 filename_to_ansi (from, from_a);
6386 filename_to_ansi (to, to_a);
6387 copy_result = CopyFileA (from_a, to_a, FALSE);
6388 }
6389 if (!copy_result)
6390 {
6391 /* CopyFile doesn't set errno when it fails. By far the most
6392 "popular" reason is that the target is read-only. */
6393 DWORD err = GetLastError ();
6394
6395 switch (err)
6396 {
6397 case ERROR_FILE_NOT_FOUND:
6398 errno = ENOENT;
6399 break;
6400 case ERROR_ACCESS_DENIED:
6401 errno = EACCES;
6402 break;
6403 case ERROR_ENCRYPTION_FAILED:
6404 errno = EIO;
6405 break;
6406 default:
6407 errno = EPERM;
6408 break;
6409 }
6410
6411 if (acl)
6412 acl_free (acl);
6413 return -1;
6414 }
6415 /* CopyFile retains the timestamp by default. However, see
6416 "Community Additions" for CopyFile: it sounds like that is not
6417 entirely true. Testing on Windows XP confirms that modified time
6418 is copied, but creation and last-access times are not.
6419 FIXME? */
6420 else if (!keep_time)
6421 {
6422 struct timespec now;
6423 DWORD attributes;
6424
6425 if (w32_unicode_filenames)
6426 {
6427 /* Ensure file is writable while its times are set. */
6428 attributes = GetFileAttributesW (to_w);
6429 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6430 now = current_timespec ();
6431 if (set_file_times (-1, to, now, now))
6432 {
6433 /* Restore original attributes. */
6434 SetFileAttributesW (to_w, attributes);
6435 if (acl)
6436 acl_free (acl);
6437 return -3;
6438 }
6439 /* Restore original attributes. */
6440 SetFileAttributesW (to_w, attributes);
6441 }
6442 else
6443 {
6444 attributes = GetFileAttributesA (to_a);
6445 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6446 now = current_timespec ();
6447 if (set_file_times (-1, to, now, now))
6448 {
6449 SetFileAttributesA (to_a, attributes);
6450 if (acl)
6451 acl_free (acl);
6452 return -3;
6453 }
6454 SetFileAttributesA (to_a, attributes);
6455 }
6456 }
6457 if (acl != NULL)
6458 {
6459 bool fail =
6460 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6461 acl_free (acl);
6462 if (fail && acl_errno_valid (errno))
6463 return -4;
6464 }
6465
6466 return 0;
6467 }
6468
6469 \f
6470 /* Support for browsing other processes and their attributes. See
6471 process.c for the Lisp bindings. */
6472
6473 /* Helper wrapper functions. */
6474
6475 static HANDLE WINAPI
6476 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6477 {
6478 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6479
6480 if (g_b_init_create_toolhelp32_snapshot == 0)
6481 {
6482 g_b_init_create_toolhelp32_snapshot = 1;
6483 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6484 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6485 "CreateToolhelp32Snapshot");
6486 }
6487 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6488 {
6489 return INVALID_HANDLE_VALUE;
6490 }
6491 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6492 }
6493
6494 static BOOL WINAPI
6495 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6496 {
6497 static Process32First_Proc s_pfn_Process32_First = NULL;
6498
6499 if (g_b_init_process32_first == 0)
6500 {
6501 g_b_init_process32_first = 1;
6502 s_pfn_Process32_First = (Process32First_Proc)
6503 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6504 "Process32First");
6505 }
6506 if (s_pfn_Process32_First == NULL)
6507 {
6508 return FALSE;
6509 }
6510 return (s_pfn_Process32_First (hSnapshot, lppe));
6511 }
6512
6513 static BOOL WINAPI
6514 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6515 {
6516 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6517
6518 if (g_b_init_process32_next == 0)
6519 {
6520 g_b_init_process32_next = 1;
6521 s_pfn_Process32_Next = (Process32Next_Proc)
6522 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6523 "Process32Next");
6524 }
6525 if (s_pfn_Process32_Next == NULL)
6526 {
6527 return FALSE;
6528 }
6529 return (s_pfn_Process32_Next (hSnapshot, lppe));
6530 }
6531
6532 static BOOL WINAPI
6533 open_thread_token (HANDLE ThreadHandle,
6534 DWORD DesiredAccess,
6535 BOOL OpenAsSelf,
6536 PHANDLE TokenHandle)
6537 {
6538 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6539 HMODULE hm_advapi32 = NULL;
6540 if (is_windows_9x () == TRUE)
6541 {
6542 SetLastError (ERROR_NOT_SUPPORTED);
6543 return FALSE;
6544 }
6545 if (g_b_init_open_thread_token == 0)
6546 {
6547 g_b_init_open_thread_token = 1;
6548 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6549 s_pfn_Open_Thread_Token =
6550 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6551 }
6552 if (s_pfn_Open_Thread_Token == NULL)
6553 {
6554 SetLastError (ERROR_NOT_SUPPORTED);
6555 return FALSE;
6556 }
6557 return (
6558 s_pfn_Open_Thread_Token (
6559 ThreadHandle,
6560 DesiredAccess,
6561 OpenAsSelf,
6562 TokenHandle)
6563 );
6564 }
6565
6566 static BOOL WINAPI
6567 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6568 {
6569 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6570 HMODULE hm_advapi32 = NULL;
6571 if (is_windows_9x () == TRUE)
6572 {
6573 return FALSE;
6574 }
6575 if (g_b_init_impersonate_self == 0)
6576 {
6577 g_b_init_impersonate_self = 1;
6578 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6579 s_pfn_Impersonate_Self =
6580 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6581 }
6582 if (s_pfn_Impersonate_Self == NULL)
6583 {
6584 return FALSE;
6585 }
6586 return s_pfn_Impersonate_Self (ImpersonationLevel);
6587 }
6588
6589 static BOOL WINAPI
6590 revert_to_self (void)
6591 {
6592 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6593 HMODULE hm_advapi32 = NULL;
6594 if (is_windows_9x () == TRUE)
6595 {
6596 return FALSE;
6597 }
6598 if (g_b_init_revert_to_self == 0)
6599 {
6600 g_b_init_revert_to_self = 1;
6601 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6602 s_pfn_Revert_To_Self =
6603 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6604 }
6605 if (s_pfn_Revert_To_Self == NULL)
6606 {
6607 return FALSE;
6608 }
6609 return s_pfn_Revert_To_Self ();
6610 }
6611
6612 static BOOL WINAPI
6613 get_process_memory_info (HANDLE h_proc,
6614 PPROCESS_MEMORY_COUNTERS mem_counters,
6615 DWORD bufsize)
6616 {
6617 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6618 HMODULE hm_psapi = NULL;
6619 if (is_windows_9x () == TRUE)
6620 {
6621 return FALSE;
6622 }
6623 if (g_b_init_get_process_memory_info == 0)
6624 {
6625 g_b_init_get_process_memory_info = 1;
6626 hm_psapi = LoadLibrary ("Psapi.dll");
6627 if (hm_psapi)
6628 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6629 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6630 }
6631 if (s_pfn_Get_Process_Memory_Info == NULL)
6632 {
6633 return FALSE;
6634 }
6635 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6636 }
6637
6638 static BOOL WINAPI
6639 get_process_working_set_size (HANDLE h_proc,
6640 PSIZE_T minrss,
6641 PSIZE_T maxrss)
6642 {
6643 static GetProcessWorkingSetSize_Proc
6644 s_pfn_Get_Process_Working_Set_Size = NULL;
6645
6646 if (is_windows_9x () == TRUE)
6647 {
6648 return FALSE;
6649 }
6650 if (g_b_init_get_process_working_set_size == 0)
6651 {
6652 g_b_init_get_process_working_set_size = 1;
6653 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6654 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6655 "GetProcessWorkingSetSize");
6656 }
6657 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6658 {
6659 return FALSE;
6660 }
6661 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6662 }
6663
6664 static BOOL WINAPI
6665 global_memory_status (MEMORYSTATUS *buf)
6666 {
6667 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6668
6669 if (is_windows_9x () == TRUE)
6670 {
6671 return FALSE;
6672 }
6673 if (g_b_init_global_memory_status == 0)
6674 {
6675 g_b_init_global_memory_status = 1;
6676 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6677 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6678 "GlobalMemoryStatus");
6679 }
6680 if (s_pfn_Global_Memory_Status == NULL)
6681 {
6682 return FALSE;
6683 }
6684 return s_pfn_Global_Memory_Status (buf);
6685 }
6686
6687 static BOOL WINAPI
6688 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6689 {
6690 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6691
6692 if (is_windows_9x () == TRUE)
6693 {
6694 return FALSE;
6695 }
6696 if (g_b_init_global_memory_status_ex == 0)
6697 {
6698 g_b_init_global_memory_status_ex = 1;
6699 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6700 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6701 "GlobalMemoryStatusEx");
6702 }
6703 if (s_pfn_Global_Memory_Status_Ex == NULL)
6704 {
6705 return FALSE;
6706 }
6707 return s_pfn_Global_Memory_Status_Ex (buf);
6708 }
6709
6710 Lisp_Object
6711 list_system_processes (void)
6712 {
6713 Lisp_Object proclist = Qnil;
6714 HANDLE h_snapshot;
6715
6716 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6717
6718 if (h_snapshot != INVALID_HANDLE_VALUE)
6719 {
6720 PROCESSENTRY32 proc_entry;
6721 DWORD proc_id;
6722 BOOL res;
6723
6724 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6725 for (res = process32_first (h_snapshot, &proc_entry); res;
6726 res = process32_next (h_snapshot, &proc_entry))
6727 {
6728 proc_id = proc_entry.th32ProcessID;
6729 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6730 }
6731
6732 CloseHandle (h_snapshot);
6733 proclist = Fnreverse (proclist);
6734 }
6735
6736 return proclist;
6737 }
6738
6739 static int
6740 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6741 {
6742 TOKEN_PRIVILEGES priv;
6743 DWORD priv_size = sizeof (priv);
6744 DWORD opriv_size = sizeof (*old_priv);
6745 HANDLE h_token = NULL;
6746 HANDLE h_thread = GetCurrentThread ();
6747 int ret_val = 0;
6748 BOOL res;
6749
6750 res = open_thread_token (h_thread,
6751 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6752 FALSE, &h_token);
6753 if (!res && GetLastError () == ERROR_NO_TOKEN)
6754 {
6755 if (impersonate_self (SecurityImpersonation))
6756 res = open_thread_token (h_thread,
6757 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6758 FALSE, &h_token);
6759 }
6760 if (res)
6761 {
6762 priv.PrivilegeCount = 1;
6763 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6764 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6765 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6766 old_priv, &opriv_size)
6767 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6768 ret_val = 1;
6769 }
6770 if (h_token)
6771 CloseHandle (h_token);
6772
6773 return ret_val;
6774 }
6775
6776 static int
6777 restore_privilege (TOKEN_PRIVILEGES *priv)
6778 {
6779 DWORD priv_size = sizeof (*priv);
6780 HANDLE h_token = NULL;
6781 int ret_val = 0;
6782
6783 if (open_thread_token (GetCurrentThread (),
6784 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6785 FALSE, &h_token))
6786 {
6787 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6788 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6789 ret_val = 1;
6790 }
6791 if (h_token)
6792 CloseHandle (h_token);
6793
6794 return ret_val;
6795 }
6796
6797 static Lisp_Object
6798 ltime (ULONGLONG time_100ns)
6799 {
6800 ULONGLONG time_sec = time_100ns / 10000000;
6801 int subsec = time_100ns % 10000000;
6802 return list4i (time_sec >> 16, time_sec & 0xffff,
6803 subsec / 10, subsec % 10 * 100000);
6804 }
6805
6806 #define U64_TO_LISP_TIME(time) ltime (time)
6807
6808 static int
6809 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6810 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6811 double *pcpu)
6812 {
6813 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6814 ULONGLONG tem1, tem2, tem3, tem;
6815
6816 if (!h_proc
6817 || !get_process_times_fn
6818 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6819 &ft_kernel, &ft_user))
6820 return 0;
6821
6822 GetSystemTimeAsFileTime (&ft_current);
6823
6824 FILETIME_TO_U64 (tem1, ft_kernel);
6825 *stime = U64_TO_LISP_TIME (tem1);
6826
6827 FILETIME_TO_U64 (tem2, ft_user);
6828 *utime = U64_TO_LISP_TIME (tem2);
6829
6830 tem3 = tem1 + tem2;
6831 *ttime = U64_TO_LISP_TIME (tem3);
6832
6833 FILETIME_TO_U64 (tem, ft_creation);
6834 /* Process no 4 (System) returns zero creation time. */
6835 if (tem)
6836 tem -= utc_base;
6837 *ctime = U64_TO_LISP_TIME (tem);
6838
6839 if (tem)
6840 {
6841 FILETIME_TO_U64 (tem3, ft_current);
6842 tem = (tem3 - utc_base) - tem;
6843 }
6844 *etime = U64_TO_LISP_TIME (tem);
6845
6846 if (tem)
6847 {
6848 *pcpu = 100.0 * (tem1 + tem2) / tem;
6849 if (*pcpu > 100)
6850 *pcpu = 100.0;
6851 }
6852 else
6853 *pcpu = 0;
6854
6855 return 1;
6856 }
6857
6858 Lisp_Object
6859 system_process_attributes (Lisp_Object pid)
6860 {
6861 Lisp_Object attrs = Qnil;
6862 Lisp_Object cmd_str, decoded_cmd, tem;
6863 HANDLE h_snapshot, h_proc;
6864 DWORD proc_id;
6865 int found_proc = 0;
6866 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6867 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6868 DWORD glength = sizeof (gname);
6869 HANDLE token = NULL;
6870 SID_NAME_USE user_type;
6871 unsigned char *buf = NULL;
6872 DWORD blen = 0;
6873 TOKEN_USER user_token;
6874 TOKEN_PRIMARY_GROUP group_token;
6875 unsigned euid;
6876 unsigned egid;
6877 PROCESS_MEMORY_COUNTERS mem;
6878 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6879 SIZE_T minrss, maxrss;
6880 MEMORYSTATUS memst;
6881 MEMORY_STATUS_EX memstex;
6882 double totphys = 0.0;
6883 Lisp_Object ctime, stime, utime, etime, ttime;
6884 double pcpu;
6885 BOOL result = FALSE;
6886
6887 CHECK_NUMBER_OR_FLOAT (pid);
6888 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6889
6890 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6891
6892 if (h_snapshot != INVALID_HANDLE_VALUE)
6893 {
6894 PROCESSENTRY32 pe;
6895 BOOL res;
6896
6897 pe.dwSize = sizeof (PROCESSENTRY32);
6898 for (res = process32_first (h_snapshot, &pe); res;
6899 res = process32_next (h_snapshot, &pe))
6900 {
6901 if (proc_id == pe.th32ProcessID)
6902 {
6903 if (proc_id == 0)
6904 decoded_cmd = build_string ("Idle");
6905 else
6906 {
6907 /* Decode the command name from locale-specific
6908 encoding. */
6909 cmd_str = build_unibyte_string (pe.szExeFile);
6910
6911 decoded_cmd =
6912 code_convert_string_norecord (cmd_str,
6913 Vlocale_coding_system, 0);
6914 }
6915 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6916 attrs = Fcons (Fcons (Qppid,
6917 make_fixnum_or_float (pe.th32ParentProcessID)),
6918 attrs);
6919 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6920 attrs);
6921 attrs = Fcons (Fcons (Qthcount,
6922 make_fixnum_or_float (pe.cntThreads)),
6923 attrs);
6924 found_proc = 1;
6925 break;
6926 }
6927 }
6928
6929 CloseHandle (h_snapshot);
6930 }
6931
6932 if (!found_proc)
6933 return Qnil;
6934
6935 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6936 FALSE, proc_id);
6937 /* If we were denied a handle to the process, try again after
6938 enabling the SeDebugPrivilege in our process. */
6939 if (!h_proc)
6940 {
6941 TOKEN_PRIVILEGES priv_current;
6942
6943 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6944 {
6945 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6946 FALSE, proc_id);
6947 restore_privilege (&priv_current);
6948 revert_to_self ();
6949 }
6950 }
6951 if (h_proc)
6952 {
6953 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6954 if (result)
6955 {
6956 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6957 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6958 {
6959 buf = xmalloc (blen);
6960 result = get_token_information (token, TokenUser,
6961 (LPVOID)buf, blen, &needed);
6962 if (result)
6963 {
6964 memcpy (&user_token, buf, sizeof (user_token));
6965 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6966 {
6967 euid = get_rid (user_token.User.Sid);
6968 result = lookup_account_sid (NULL, user_token.User.Sid,
6969 uname, &ulength,
6970 domain, &dlength,
6971 &user_type);
6972 if (result)
6973 w32_add_to_cache (user_token.User.Sid, euid, uname);
6974 else
6975 {
6976 strcpy (uname, "unknown");
6977 result = TRUE;
6978 }
6979 }
6980 ulength = strlen (uname);
6981 }
6982 }
6983 }
6984 if (result)
6985 {
6986 /* Determine a reasonable euid and gid values. */
6987 if (xstrcasecmp ("administrator", uname) == 0)
6988 {
6989 euid = 500; /* well-known Administrator uid */
6990 egid = 513; /* well-known None gid */
6991 }
6992 else
6993 {
6994 /* Get group id and name. */
6995 result = get_token_information (token, TokenPrimaryGroup,
6996 (LPVOID)buf, blen, &needed);
6997 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6998 {
6999 buf = xrealloc (buf, blen = needed);
7000 result = get_token_information (token, TokenPrimaryGroup,
7001 (LPVOID)buf, blen, &needed);
7002 }
7003 if (result)
7004 {
7005 memcpy (&group_token, buf, sizeof (group_token));
7006 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
7007 {
7008 egid = get_rid (group_token.PrimaryGroup);
7009 dlength = sizeof (domain);
7010 result =
7011 lookup_account_sid (NULL, group_token.PrimaryGroup,
7012 gname, &glength, NULL, &dlength,
7013 &user_type);
7014 if (result)
7015 w32_add_to_cache (group_token.PrimaryGroup,
7016 egid, gname);
7017 else
7018 {
7019 strcpy (gname, "None");
7020 result = TRUE;
7021 }
7022 }
7023 glength = strlen (gname);
7024 }
7025 }
7026 }
7027 xfree (buf);
7028 }
7029 if (!result)
7030 {
7031 if (!is_windows_9x ())
7032 {
7033 /* We couldn't open the process token, presumably because of
7034 insufficient access rights. Assume this process is run
7035 by the system. */
7036 strcpy (uname, "SYSTEM");
7037 strcpy (gname, "None");
7038 euid = 18; /* SYSTEM */
7039 egid = 513; /* None */
7040 glength = strlen (gname);
7041 ulength = strlen (uname);
7042 }
7043 /* If we are running under Windows 9X, where security calls are
7044 not supported, we assume all processes are run by the current
7045 user. */
7046 else if (GetUserName (uname, &ulength))
7047 {
7048 if (xstrcasecmp ("administrator", uname) == 0)
7049 euid = 0;
7050 else
7051 euid = 123;
7052 egid = euid;
7053 strcpy (gname, "None");
7054 glength = strlen (gname);
7055 ulength = strlen (uname);
7056 }
7057 else
7058 {
7059 euid = 123;
7060 egid = 123;
7061 strcpy (uname, "administrator");
7062 ulength = strlen (uname);
7063 strcpy (gname, "None");
7064 glength = strlen (gname);
7065 }
7066 if (token)
7067 CloseHandle (token);
7068 }
7069
7070 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
7071 tem = make_unibyte_string (uname, ulength);
7072 attrs = Fcons (Fcons (Quser,
7073 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7074 attrs);
7075 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
7076 tem = make_unibyte_string (gname, glength);
7077 attrs = Fcons (Fcons (Qgroup,
7078 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
7079 attrs);
7080
7081 if (global_memory_status_ex (&memstex))
7082 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7083 totphys = memstex.ullTotalPhys / 1024.0;
7084 #else
7085 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7086 double, so we need to do this for it... */
7087 {
7088 DWORD tot_hi = memstex.ullTotalPhys >> 32;
7089 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
7090 DWORD tot_lo = memstex.ullTotalPhys % 1024;
7091
7092 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
7093 }
7094 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7095 else if (global_memory_status (&memst))
7096 totphys = memst.dwTotalPhys / 1024.0;
7097
7098 if (h_proc
7099 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
7100 sizeof (mem_ex)))
7101 {
7102 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7103
7104 attrs = Fcons (Fcons (Qmajflt,
7105 make_fixnum_or_float (mem_ex.PageFaultCount)),
7106 attrs);
7107 attrs = Fcons (Fcons (Qvsize,
7108 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
7109 attrs);
7110 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7111 if (totphys)
7112 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7113 }
7114 else if (h_proc
7115 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
7116 {
7117 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7118
7119 attrs = Fcons (Fcons (Qmajflt,
7120 make_fixnum_or_float (mem.PageFaultCount)),
7121 attrs);
7122 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
7123 if (totphys)
7124 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7125 }
7126 else if (h_proc
7127 && get_process_working_set_size (h_proc, &minrss, &maxrss))
7128 {
7129 DWORD rss = maxrss / 1024;
7130
7131 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
7132 if (totphys)
7133 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
7134 }
7135
7136 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7137 {
7138 attrs = Fcons (Fcons (Qutime, utime), attrs);
7139 attrs = Fcons (Fcons (Qstime, stime), attrs);
7140 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7141 attrs = Fcons (Fcons (Qstart, ctime), attrs);
7142 attrs = Fcons (Fcons (Qetime, etime), attrs);
7143 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
7144 }
7145
7146 /* FIXME: Retrieve command line by walking the PEB of the process. */
7147
7148 if (h_proc)
7149 CloseHandle (h_proc);
7150 return attrs;
7151 }
7152
7153 int
7154 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
7155 unsigned long long *totalswap, unsigned long long *freeswap)
7156 {
7157 MEMORYSTATUS memst;
7158 MEMORY_STATUS_EX memstex;
7159
7160 /* Use GlobalMemoryStatusEx if available, as it can report more than
7161 2GB of memory. */
7162 if (global_memory_status_ex (&memstex))
7163 {
7164 *totalram = memstex.ullTotalPhys;
7165 *freeram = memstex.ullAvailPhys;
7166 *totalswap = memstex.ullTotalPageFile;
7167 *freeswap = memstex.ullAvailPageFile;
7168 return 0;
7169 }
7170 else if (global_memory_status (&memst))
7171 {
7172 *totalram = memst.dwTotalPhys;
7173 *freeram = memst.dwAvailPhys;
7174 *totalswap = memst.dwTotalPageFile;
7175 *freeswap = memst.dwAvailPageFile;
7176 return 0;
7177 }
7178 else
7179 return -1;
7180 }
7181
7182 \f
7183 /* Wrappers for winsock functions to map between our file descriptors
7184 and winsock's handles; also set h_errno for convenience.
7185
7186 To allow Emacs to run on systems which don't have winsock support
7187 installed, we dynamically link to winsock on startup if present, and
7188 otherwise provide the minimum necessary functionality
7189 (eg. gethostname). */
7190
7191 /* function pointers for relevant socket functions */
7192 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7193 void (PASCAL *pfn_WSASetLastError) (int iError);
7194 int (PASCAL *pfn_WSAGetLastError) (void);
7195 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7196 int (PASCAL *pfn_WSAEnumNetworkEvents) (SOCKET s, HANDLE hEventObject,
7197 WSANETWORKEVENTS *NetworkEvents);
7198
7199 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7200 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7201 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7202 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7203 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7204 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7205 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7206 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7207 int (PASCAL *pfn_closesocket) (SOCKET s);
7208 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7209 int (PASCAL *pfn_WSACleanup) (void);
7210
7211 u_short (PASCAL *pfn_htons) (u_short hostshort);
7212 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7213 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7214 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7215 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7216 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7217 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7218 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7219 const char * optval, int optlen);
7220 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7221 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7222 int * namelen);
7223 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7224 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7225 struct sockaddr * from, int * fromlen);
7226 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7227 const struct sockaddr * to, int tolen);
7228
7229 int (PASCAL *pfn_getaddrinfo) (const char *, const char *,
7230 const struct addrinfo *, struct addrinfo **);
7231 void (PASCAL *pfn_freeaddrinfo) (struct addrinfo *);
7232
7233 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7234 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7235 #ifndef HANDLE_FLAG_INHERIT
7236 #define HANDLE_FLAG_INHERIT 1
7237 #endif
7238
7239 HANDLE winsock_lib;
7240 static int winsock_inuse;
7241
7242 BOOL term_winsock (void);
7243
7244 BOOL
7245 term_winsock (void)
7246 {
7247 if (winsock_lib != NULL && winsock_inuse == 0)
7248 {
7249 release_listen_threads ();
7250 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7251 after WSAStartup returns successfully, but it seems reasonable
7252 to allow unloading winsock anyway in that case. */
7253 if (pfn_WSACleanup () == 0 ||
7254 pfn_WSAGetLastError () == WSAENETDOWN)
7255 {
7256 if (FreeLibrary (winsock_lib))
7257 winsock_lib = NULL;
7258 return TRUE;
7259 }
7260 }
7261 return FALSE;
7262 }
7263
7264 BOOL
7265 init_winsock (int load_now)
7266 {
7267 WSADATA winsockData;
7268
7269 if (winsock_lib != NULL)
7270 return TRUE;
7271
7272 pfn_SetHandleInformation
7273 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7274 "SetHandleInformation");
7275
7276 winsock_lib = LoadLibrary ("Ws2_32.dll");
7277
7278 if (winsock_lib != NULL)
7279 {
7280 /* dynamically link to socket functions */
7281
7282 #define LOAD_PROC(fn) \
7283 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7284 goto fail;
7285
7286 LOAD_PROC (WSAStartup);
7287 LOAD_PROC (WSASetLastError);
7288 LOAD_PROC (WSAGetLastError);
7289 LOAD_PROC (WSAEventSelect);
7290 LOAD_PROC (WSAEnumNetworkEvents);
7291 LOAD_PROC (WSACreateEvent);
7292 LOAD_PROC (WSACloseEvent);
7293 LOAD_PROC (socket);
7294 LOAD_PROC (bind);
7295 LOAD_PROC (connect);
7296 LOAD_PROC (ioctlsocket);
7297 LOAD_PROC (recv);
7298 LOAD_PROC (send);
7299 LOAD_PROC (closesocket);
7300 LOAD_PROC (shutdown);
7301 LOAD_PROC (htons);
7302 LOAD_PROC (ntohs);
7303 LOAD_PROC (inet_addr);
7304 LOAD_PROC (gethostname);
7305 LOAD_PROC (gethostbyname);
7306 LOAD_PROC (getservbyname);
7307 LOAD_PROC (getpeername);
7308 LOAD_PROC (WSACleanup);
7309 LOAD_PROC (setsockopt);
7310 LOAD_PROC (listen);
7311 LOAD_PROC (getsockname);
7312 LOAD_PROC (accept);
7313 LOAD_PROC (recvfrom);
7314 LOAD_PROC (sendto);
7315 #undef LOAD_PROC
7316
7317 /* Try loading functions not available before XP. */
7318 pfn_getaddrinfo = (void *) GetProcAddress (winsock_lib, "getaddrinfo");
7319 pfn_freeaddrinfo = (void *) GetProcAddress (winsock_lib, "freeaddrinfo");
7320 /* Paranoia: these two functions should go together, so if one
7321 is absent, we cannot use the other. */
7322 if (pfn_getaddrinfo == NULL)
7323 pfn_freeaddrinfo = NULL;
7324 else if (pfn_freeaddrinfo == NULL)
7325 pfn_getaddrinfo = NULL;
7326
7327 /* specify version 1.1 of winsock */
7328 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7329 {
7330 if (winsockData.wVersion != 0x101)
7331 goto fail;
7332
7333 if (!load_now)
7334 {
7335 /* Report that winsock exists and is usable, but leave
7336 socket functions disabled. I am assuming that calling
7337 WSAStartup does not require any network interaction,
7338 and in particular does not cause or require a dial-up
7339 connection to be established. */
7340
7341 pfn_WSACleanup ();
7342 FreeLibrary (winsock_lib);
7343 winsock_lib = NULL;
7344 }
7345 winsock_inuse = 0;
7346 return TRUE;
7347 }
7348
7349 fail:
7350 FreeLibrary (winsock_lib);
7351 winsock_lib = NULL;
7352 }
7353
7354 return FALSE;
7355 }
7356
7357
7358 int h_errno = 0;
7359
7360 /* Function to map winsock error codes to errno codes for those errno
7361 code defined in errno.h (errno values not defined by errno.h are
7362 already in nt/inc/sys/socket.h). */
7363 static void
7364 set_errno (void)
7365 {
7366 int wsa_err;
7367
7368 h_errno = 0;
7369 if (winsock_lib == NULL)
7370 wsa_err = EINVAL;
7371 else
7372 wsa_err = pfn_WSAGetLastError ();
7373
7374 switch (wsa_err)
7375 {
7376 case WSAEACCES: errno = EACCES; break;
7377 case WSAEBADF: errno = EBADF; break;
7378 case WSAEFAULT: errno = EFAULT; break;
7379 case WSAEINTR: errno = EINTR; break;
7380 case WSAEINVAL: errno = EINVAL; break;
7381 case WSAEMFILE: errno = EMFILE; break;
7382 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7383 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7384 case WSAEWOULDBLOCK: errno = EWOULDBLOCK; break;
7385 case WSAENOTCONN: errno = ENOTCONN; break;
7386 default: errno = wsa_err; break;
7387 }
7388 }
7389
7390 static void
7391 check_errno (void)
7392 {
7393 h_errno = 0;
7394 if (winsock_lib != NULL)
7395 pfn_WSASetLastError (0);
7396 }
7397
7398 /* Extend strerror to handle the winsock-specific error codes. */
7399 struct {
7400 int errnum;
7401 const char * msg;
7402 } _wsa_errlist[] = {
7403 {WSAEINTR , "Interrupted function call"},
7404 {WSAEBADF , "Bad file descriptor"},
7405 {WSAEACCES , "Permission denied"},
7406 {WSAEFAULT , "Bad address"},
7407 {WSAEINVAL , "Invalid argument"},
7408 {WSAEMFILE , "Too many open files"},
7409
7410 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7411 {WSAEINPROGRESS , "Operation now in progress"},
7412 {WSAEALREADY , "Operation already in progress"},
7413 {WSAENOTSOCK , "Socket operation on non-socket"},
7414 {WSAEDESTADDRREQ , "Destination address required"},
7415 {WSAEMSGSIZE , "Message too long"},
7416 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7417 {WSAENOPROTOOPT , "Bad protocol option"},
7418 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7419 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7420 {WSAEOPNOTSUPP , "Operation not supported"},
7421 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7422 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7423 {WSAEADDRINUSE , "Address already in use"},
7424 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7425 {WSAENETDOWN , "Network is down"},
7426 {WSAENETUNREACH , "Network is unreachable"},
7427 {WSAENETRESET , "Network dropped connection on reset"},
7428 {WSAECONNABORTED , "Software caused connection abort"},
7429 {WSAECONNRESET , "Connection reset by peer"},
7430 {WSAENOBUFS , "No buffer space available"},
7431 {WSAEISCONN , "Socket is already connected"},
7432 {WSAENOTCONN , "Socket is not connected"},
7433 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7434 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7435 {WSAETIMEDOUT , "Connection timed out"},
7436 {WSAECONNREFUSED , "Connection refused"},
7437 {WSAELOOP , "Network loop"}, /* not sure */
7438 {WSAENAMETOOLONG , "Name is too long"},
7439 {WSAEHOSTDOWN , "Host is down"},
7440 {WSAEHOSTUNREACH , "No route to host"},
7441 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7442 {WSAEPROCLIM , "Too many processes"},
7443 {WSAEUSERS , "Too many users"}, /* not sure */
7444 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7445 {WSAESTALE , "Data is stale"}, /* not sure */
7446 {WSAEREMOTE , "Remote error"}, /* not sure */
7447
7448 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7449 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7450 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7451 {WSAEDISCON , "Graceful shutdown in progress"},
7452 #ifdef WSAENOMORE
7453 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7454 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7455 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7456 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7457 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7458 {WSASYSCALLFAILURE , "System call failure"},
7459 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7460 {WSATYPE_NOT_FOUND , "Class type not found"},
7461 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7462 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7463 {WSAEREFUSED , "Operation refused"}, /* not sure */
7464 #endif
7465
7466 {WSAHOST_NOT_FOUND , "Host not found"},
7467 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7468 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7469 {WSANO_DATA , "Valid name, no data record of requested type"},
7470
7471 {-1, NULL}
7472 };
7473
7474 char *
7475 sys_strerror (int error_no)
7476 {
7477 int i;
7478 static char unknown_msg[40];
7479
7480 if (error_no >= 0 && error_no < sys_nerr)
7481 return sys_errlist[error_no];
7482
7483 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7484 if (_wsa_errlist[i].errnum == error_no)
7485 return (char *)_wsa_errlist[i].msg;
7486
7487 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7488 return unknown_msg;
7489 }
7490
7491 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7492 but I believe the method of keeping the socket handle separate (and
7493 insuring it is not inheritable) is the correct one. */
7494
7495 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7496
7497 static int socket_to_fd (SOCKET s);
7498
7499 int
7500 sys_socket (int af, int type, int protocol)
7501 {
7502 SOCKET s;
7503
7504 if (winsock_lib == NULL)
7505 {
7506 errno = ENETDOWN;
7507 return -1;
7508 }
7509
7510 check_errno ();
7511
7512 /* call the real socket function */
7513 s = pfn_socket (af, type, protocol);
7514
7515 if (s != INVALID_SOCKET)
7516 return socket_to_fd (s);
7517
7518 set_errno ();
7519 return -1;
7520 }
7521
7522 /* Convert a SOCKET to a file descriptor. */
7523 static int
7524 socket_to_fd (SOCKET s)
7525 {
7526 int fd;
7527 child_process * cp;
7528
7529 /* Although under NT 3.5 _open_osfhandle will accept a socket
7530 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7531 that does not work under NT 3.1. However, we can get the same
7532 effect by using a backdoor function to replace an existing
7533 descriptor handle with the one we want. */
7534
7535 /* allocate a file descriptor (with appropriate flags) */
7536 fd = _open ("NUL:", _O_RDWR);
7537 if (fd >= 0)
7538 {
7539 /* Make a non-inheritable copy of the socket handle. Note
7540 that it is possible that sockets aren't actually kernel
7541 handles, which appears to be the case on Windows 9x when
7542 the MS Proxy winsock client is installed. */
7543 {
7544 /* Apparently there is a bug in NT 3.51 with some service
7545 packs, which prevents using DuplicateHandle to make a
7546 socket handle non-inheritable (causes WSACleanup to
7547 hang). The work-around is to use SetHandleInformation
7548 instead if it is available and implemented. */
7549 if (pfn_SetHandleInformation)
7550 {
7551 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7552 }
7553 else
7554 {
7555 HANDLE parent = GetCurrentProcess ();
7556 HANDLE new_s = INVALID_HANDLE_VALUE;
7557
7558 if (DuplicateHandle (parent,
7559 (HANDLE) s,
7560 parent,
7561 &new_s,
7562 0,
7563 FALSE,
7564 DUPLICATE_SAME_ACCESS))
7565 {
7566 /* It is possible that DuplicateHandle succeeds even
7567 though the socket wasn't really a kernel handle,
7568 because a real handle has the same value. So
7569 test whether the new handle really is a socket. */
7570 unsigned long nonblocking = 0;
7571 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7572 {
7573 pfn_closesocket (s);
7574 s = (SOCKET) new_s;
7575 }
7576 else
7577 {
7578 CloseHandle (new_s);
7579 }
7580 }
7581 }
7582 }
7583 eassert (fd < MAXDESC);
7584 fd_info[fd].hnd = (HANDLE) s;
7585
7586 /* set our own internal flags */
7587 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7588
7589 cp = new_child ();
7590 if (cp)
7591 {
7592 cp->fd = fd;
7593 cp->status = STATUS_READ_ACKNOWLEDGED;
7594
7595 /* attach child_process to fd_info */
7596 if (fd_info[ fd ].cp != NULL)
7597 {
7598 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7599 emacs_abort ();
7600 }
7601
7602 fd_info[ fd ].cp = cp;
7603
7604 /* success! */
7605 winsock_inuse++; /* count open sockets */
7606 return fd;
7607 }
7608
7609 /* clean up */
7610 _close (fd);
7611 }
7612 else
7613 pfn_closesocket (s);
7614 errno = EMFILE;
7615 return -1;
7616 }
7617
7618 int
7619 sys_bind (int s, const struct sockaddr * addr, int namelen)
7620 {
7621 if (winsock_lib == NULL)
7622 {
7623 errno = ENOTSOCK;
7624 return SOCKET_ERROR;
7625 }
7626
7627 check_errno ();
7628 if (fd_info[s].flags & FILE_SOCKET)
7629 {
7630 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7631 if (rc == SOCKET_ERROR)
7632 set_errno ();
7633 return rc;
7634 }
7635 errno = ENOTSOCK;
7636 return SOCKET_ERROR;
7637 }
7638
7639 int
7640 sys_connect (int s, const struct sockaddr * name, int namelen)
7641 {
7642 if (winsock_lib == NULL)
7643 {
7644 errno = ENOTSOCK;
7645 return SOCKET_ERROR;
7646 }
7647
7648 check_errno ();
7649 if (fd_info[s].flags & FILE_SOCKET)
7650 {
7651 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7652 if (rc == SOCKET_ERROR)
7653 {
7654 set_errno ();
7655 /* If this is a non-blocking 'connect', set the bit in flags
7656 that will tell reader_thread to wait for connection
7657 before trying to read. */
7658 if (errno == EWOULDBLOCK && (fd_info[s].flags & FILE_NDELAY) != 0)
7659 {
7660 errno = EINPROGRESS; /* that's what process.c expects */
7661 fd_info[s].flags |= FILE_CONNECT;
7662 }
7663 }
7664 return rc;
7665 }
7666 errno = ENOTSOCK;
7667 return SOCKET_ERROR;
7668 }
7669
7670 u_short
7671 sys_htons (u_short hostshort)
7672 {
7673 return (winsock_lib != NULL) ?
7674 pfn_htons (hostshort) : hostshort;
7675 }
7676
7677 u_short
7678 sys_ntohs (u_short netshort)
7679 {
7680 return (winsock_lib != NULL) ?
7681 pfn_ntohs (netshort) : netshort;
7682 }
7683
7684 unsigned long
7685 sys_inet_addr (const char * cp)
7686 {
7687 return (winsock_lib != NULL) ?
7688 pfn_inet_addr (cp) : INADDR_NONE;
7689 }
7690
7691 int
7692 sys_gethostname (char * name, int namelen)
7693 {
7694 if (winsock_lib != NULL)
7695 {
7696 int retval;
7697
7698 check_errno ();
7699 retval = pfn_gethostname (name, namelen);
7700 if (retval == SOCKET_ERROR)
7701 set_errno ();
7702 return retval;
7703 }
7704
7705 if (namelen > MAX_COMPUTERNAME_LENGTH)
7706 return !GetComputerName (name, (DWORD *)&namelen);
7707
7708 errno = EFAULT;
7709 return SOCKET_ERROR;
7710 }
7711
7712 struct hostent *
7713 sys_gethostbyname (const char * name)
7714 {
7715 struct hostent * host;
7716 int h_err = h_errno;
7717
7718 if (winsock_lib == NULL)
7719 {
7720 h_errno = NO_RECOVERY;
7721 errno = ENETDOWN;
7722 return NULL;
7723 }
7724
7725 check_errno ();
7726 host = pfn_gethostbyname (name);
7727 if (!host)
7728 {
7729 set_errno ();
7730 h_errno = errno;
7731 }
7732 else
7733 h_errno = h_err;
7734 return host;
7735 }
7736
7737 struct servent *
7738 sys_getservbyname (const char * name, const char * proto)
7739 {
7740 struct servent * serv;
7741
7742 if (winsock_lib == NULL)
7743 {
7744 errno = ENETDOWN;
7745 return NULL;
7746 }
7747
7748 check_errno ();
7749 serv = pfn_getservbyname (name, proto);
7750 if (!serv)
7751 set_errno ();
7752 return serv;
7753 }
7754
7755 int
7756 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7757 {
7758 if (winsock_lib == NULL)
7759 {
7760 errno = ENETDOWN;
7761 return SOCKET_ERROR;
7762 }
7763
7764 check_errno ();
7765 if (fd_info[s].flags & FILE_SOCKET)
7766 {
7767 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7768 if (rc == SOCKET_ERROR)
7769 set_errno ();
7770 return rc;
7771 }
7772 errno = ENOTSOCK;
7773 return SOCKET_ERROR;
7774 }
7775
7776 int
7777 sys_getaddrinfo (const char *node, const char *service,
7778 const struct addrinfo *hints, struct addrinfo **res)
7779 {
7780 int rc;
7781
7782 if (winsock_lib == NULL)
7783 {
7784 errno = ENETDOWN;
7785 return SOCKET_ERROR;
7786 }
7787
7788 check_errno ();
7789 if (pfn_getaddrinfo)
7790 rc = pfn_getaddrinfo (node, service, hints, res);
7791 else
7792 {
7793 int port = 0;
7794 struct hostent *host_info;
7795 struct gai_storage {
7796 struct addrinfo addrinfo;
7797 struct sockaddr_in sockaddr_in;
7798 } *gai_storage;
7799
7800 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7801 if (hints && hints->ai_flags != 0)
7802 return WSAEINVAL;
7803 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7804 if (!node)
7805 return WSAHOST_NOT_FOUND;
7806
7807 if (service)
7808 {
7809 const char *protocol =
7810 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
7811 struct servent *srv = sys_getservbyname (service, protocol);
7812
7813 if (srv)
7814 port = srv->s_port;
7815 else if (*service >= '0' && *service <= '9')
7816 {
7817 char *endp;
7818
7819 port = strtoul (service, &endp, 10);
7820 if (*endp || port > 65536)
7821 return WSAHOST_NOT_FOUND;
7822 port = sys_htons ((unsigned short) port);
7823 }
7824 else
7825 return WSAHOST_NOT_FOUND;
7826 }
7827
7828 gai_storage = xzalloc (sizeof *gai_storage);
7829 gai_storage->sockaddr_in.sin_port = port;
7830 host_info = sys_gethostbyname (node);
7831 if (host_info)
7832 {
7833 memcpy (&gai_storage->sockaddr_in.sin_addr,
7834 host_info->h_addr, host_info->h_length);
7835 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
7836 }
7837 else
7838 {
7839 /* Attempt to interpret host as numeric inet address. */
7840 unsigned long numeric_addr = sys_inet_addr (node);
7841
7842 if (numeric_addr == -1)
7843 {
7844 free (gai_storage);
7845 return WSAHOST_NOT_FOUND;
7846 }
7847
7848 memcpy (&gai_storage->sockaddr_in.sin_addr, &numeric_addr,
7849 sizeof (gai_storage->sockaddr_in.sin_addr));
7850 gai_storage->sockaddr_in.sin_family = (hints) ? hints->ai_family : 0;
7851 }
7852
7853 gai_storage->addrinfo.ai_addr =
7854 (struct sockaddr *)&gai_storage->sockaddr_in;
7855 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
7856 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
7857 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
7858 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
7859 gai_storage->addrinfo.ai_next = NULL;
7860
7861 *res = &gai_storage->addrinfo;
7862 rc = 0;
7863 }
7864
7865 return rc;
7866 }
7867
7868 void
7869 sys_freeaddrinfo (struct addrinfo *ai)
7870 {
7871 if (winsock_lib == NULL)
7872 {
7873 errno = ENETDOWN;
7874 return;
7875 }
7876
7877 check_errno ();
7878 if (pfn_freeaddrinfo)
7879 pfn_freeaddrinfo (ai);
7880 else
7881 {
7882 eassert (ai->ai_next == NULL);
7883 xfree (ai);
7884 }
7885 }
7886
7887 int
7888 sys_shutdown (int s, int how)
7889 {
7890 if (winsock_lib == NULL)
7891 {
7892 errno = ENETDOWN;
7893 return SOCKET_ERROR;
7894 }
7895
7896 check_errno ();
7897 if (fd_info[s].flags & FILE_SOCKET)
7898 {
7899 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7900 if (rc == SOCKET_ERROR)
7901 set_errno ();
7902 return rc;
7903 }
7904 errno = ENOTSOCK;
7905 return SOCKET_ERROR;
7906 }
7907
7908 int
7909 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7910 {
7911 if (winsock_lib == NULL)
7912 {
7913 errno = ENETDOWN;
7914 return SOCKET_ERROR;
7915 }
7916
7917 check_errno ();
7918 if (fd_info[s].flags & FILE_SOCKET)
7919 {
7920 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7921 (const char *)optval, optlen);
7922 if (rc == SOCKET_ERROR)
7923 set_errno ();
7924 return rc;
7925 }
7926 errno = ENOTSOCK;
7927 return SOCKET_ERROR;
7928 }
7929
7930 int
7931 sys_listen (int s, int backlog)
7932 {
7933 if (winsock_lib == NULL)
7934 {
7935 errno = ENETDOWN;
7936 return SOCKET_ERROR;
7937 }
7938
7939 check_errno ();
7940 if (fd_info[s].flags & FILE_SOCKET)
7941 {
7942 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7943 if (rc == SOCKET_ERROR)
7944 set_errno ();
7945 else
7946 fd_info[s].flags |= FILE_LISTEN;
7947 return rc;
7948 }
7949 errno = ENOTSOCK;
7950 return SOCKET_ERROR;
7951 }
7952
7953 int
7954 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7955 {
7956 if (winsock_lib == NULL)
7957 {
7958 errno = ENETDOWN;
7959 return SOCKET_ERROR;
7960 }
7961
7962 check_errno ();
7963 if (fd_info[s].flags & FILE_SOCKET)
7964 {
7965 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7966 if (rc == SOCKET_ERROR)
7967 set_errno ();
7968 return rc;
7969 }
7970 errno = ENOTSOCK;
7971 return SOCKET_ERROR;
7972 }
7973
7974 int
7975 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7976 {
7977 if (winsock_lib == NULL)
7978 {
7979 errno = ENETDOWN;
7980 return -1;
7981 }
7982
7983 check_errno ();
7984 if (fd_info[s].flags & FILE_LISTEN)
7985 {
7986 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7987 int fd = -1;
7988 if (t == INVALID_SOCKET)
7989 set_errno ();
7990 else
7991 fd = socket_to_fd (t);
7992
7993 if (fd >= 0)
7994 {
7995 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7996 ResetEvent (fd_info[s].cp->char_avail);
7997 }
7998 return fd;
7999 }
8000 errno = ENOTSOCK;
8001 return -1;
8002 }
8003
8004 int
8005 sys_recvfrom (int s, char * buf, int len, int flags,
8006 struct sockaddr * from, int * fromlen)
8007 {
8008 if (winsock_lib == NULL)
8009 {
8010 errno = ENETDOWN;
8011 return SOCKET_ERROR;
8012 }
8013
8014 check_errno ();
8015 if (fd_info[s].flags & FILE_SOCKET)
8016 {
8017 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
8018 if (rc == SOCKET_ERROR)
8019 set_errno ();
8020 return rc;
8021 }
8022 errno = ENOTSOCK;
8023 return SOCKET_ERROR;
8024 }
8025
8026 int
8027 sys_sendto (int s, const char * buf, int len, int flags,
8028 const struct sockaddr * to, int tolen)
8029 {
8030 if (winsock_lib == NULL)
8031 {
8032 errno = ENETDOWN;
8033 return SOCKET_ERROR;
8034 }
8035
8036 check_errno ();
8037 if (fd_info[s].flags & FILE_SOCKET)
8038 {
8039 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
8040 if (rc == SOCKET_ERROR)
8041 set_errno ();
8042 return rc;
8043 }
8044 errno = ENOTSOCK;
8045 return SOCKET_ERROR;
8046 }
8047
8048 /* Windows does not have an fcntl function. Provide an implementation
8049 good enough for Emacs. */
8050 int
8051 fcntl (int s, int cmd, int options)
8052 {
8053 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8054 invoked in a context where fd1 is closed and all descriptors less
8055 than fd1 are open, so sys_dup is an adequate implementation. */
8056 if (cmd == F_DUPFD_CLOEXEC)
8057 return sys_dup (s);
8058
8059 check_errno ();
8060 if (fd_info[s].flags & FILE_SOCKET)
8061 {
8062 if (winsock_lib == NULL)
8063 {
8064 errno = ENETDOWN;
8065 return -1;
8066 }
8067
8068 if (cmd == F_SETFL && options == O_NONBLOCK)
8069 {
8070 unsigned long nblock = 1;
8071 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
8072 if (rc == SOCKET_ERROR)
8073 set_errno ();
8074 /* Keep track of the fact that we set this to non-blocking. */
8075 fd_info[s].flags |= FILE_NDELAY;
8076 return rc;
8077 }
8078 else
8079 {
8080 errno = EINVAL;
8081 return SOCKET_ERROR;
8082 }
8083 }
8084 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
8085 == (FILE_PIPE | FILE_WRITE))
8086 {
8087 /* Force our writes to pipes be non-blocking. */
8088 if (cmd == F_SETFL && options == O_NONBLOCK)
8089 {
8090 HANDLE h = (HANDLE)_get_osfhandle (s);
8091 DWORD pipe_mode = PIPE_NOWAIT;
8092
8093 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
8094 {
8095 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8096 return SOCKET_ERROR;
8097 }
8098 fd_info[s].flags |= FILE_NDELAY;
8099 return 0;
8100 }
8101 else
8102 {
8103 errno = EINVAL;
8104 return SOCKET_ERROR;
8105 }
8106 }
8107 errno = ENOTSOCK;
8108 return SOCKET_ERROR;
8109 }
8110
8111
8112 /* Shadow main io functions: we need to handle pipes and sockets more
8113 intelligently. */
8114
8115 int
8116 sys_close (int fd)
8117 {
8118 int rc;
8119
8120 if (fd < 0)
8121 {
8122 errno = EBADF;
8123 return -1;
8124 }
8125
8126 if (fd < MAXDESC && fd_info[fd].cp)
8127 {
8128 child_process * cp = fd_info[fd].cp;
8129
8130 fd_info[fd].cp = NULL;
8131
8132 if (CHILD_ACTIVE (cp))
8133 {
8134 /* if last descriptor to active child_process then cleanup */
8135 int i;
8136 for (i = 0; i < MAXDESC; i++)
8137 {
8138 if (i == fd)
8139 continue;
8140 if (fd_info[i].cp == cp)
8141 break;
8142 }
8143 if (i == MAXDESC)
8144 {
8145 if (fd_info[fd].flags & FILE_SOCKET)
8146 {
8147 if (winsock_lib == NULL) emacs_abort ();
8148
8149 pfn_shutdown (SOCK_HANDLE (fd), 2);
8150 rc = pfn_closesocket (SOCK_HANDLE (fd));
8151
8152 winsock_inuse--; /* count open sockets */
8153 }
8154 /* If the process handle is NULL, it's either a socket
8155 or serial connection, or a subprocess that was
8156 already reaped by reap_subprocess, but whose
8157 resources were not yet freed, because its output was
8158 not fully read yet by the time it was reaped. (This
8159 usually happens with async subprocesses whose output
8160 is being read by Emacs.) Otherwise, this process was
8161 not reaped yet, so we set its FD to a negative value
8162 to make sure sys_select will eventually get to
8163 calling the SIGCHLD handler for it, which will then
8164 invoke waitpid and reap_subprocess. */
8165 if (cp->procinfo.hProcess == NULL)
8166 delete_child (cp);
8167 else
8168 cp->fd = -1;
8169 }
8170 }
8171 }
8172
8173 if (fd >= 0 && fd < MAXDESC)
8174 fd_info[fd].flags = 0;
8175
8176 /* Note that sockets do not need special treatment here (at least on
8177 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8178 closesocket is equivalent to CloseHandle, which is to be expected
8179 because socket handles are fully fledged kernel handles. */
8180 rc = _close (fd);
8181
8182 return rc;
8183 }
8184
8185 int
8186 sys_dup (int fd)
8187 {
8188 int new_fd;
8189
8190 new_fd = _dup (fd);
8191 if (new_fd >= 0 && new_fd < MAXDESC)
8192 {
8193 /* duplicate our internal info as well */
8194 fd_info[new_fd] = fd_info[fd];
8195 }
8196 return new_fd;
8197 }
8198
8199 int
8200 sys_dup2 (int src, int dst)
8201 {
8202 int rc;
8203
8204 if (dst < 0 || dst >= MAXDESC)
8205 {
8206 errno = EBADF;
8207 return -1;
8208 }
8209
8210 /* MS _dup2 seems to have weird side effect when invoked with 2
8211 identical arguments: an attempt to fclose the corresponding stdio
8212 stream after that hangs (we do close standard streams in
8213 init_ntproc). Attempt to avoid that by not calling _dup2 that
8214 way: if SRC is valid, we know that dup2 should be a no-op, so do
8215 nothing and return DST. */
8216 if (src == dst)
8217 {
8218 if ((HANDLE)_get_osfhandle (src) == INVALID_HANDLE_VALUE)
8219 {
8220 errno = EBADF;
8221 return -1;
8222 }
8223 return dst;
8224 }
8225
8226 /* Make sure we close the destination first if it's a pipe or socket. */
8227 if (fd_info[dst].flags != 0)
8228 sys_close (dst);
8229
8230 rc = _dup2 (src, dst);
8231 if (rc == 0)
8232 {
8233 /* Duplicate our internal info as well. */
8234 fd_info[dst] = fd_info[src];
8235 }
8236 return rc == 0 ? dst : rc;
8237 }
8238
8239 int
8240 pipe2 (int * phandles, int pipe2_flags)
8241 {
8242 int rc;
8243 unsigned flags;
8244 unsigned pipe_size = 0;
8245
8246 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
8247
8248 /* Allow Lisp to override the default buffer size of the pipe. */
8249 if (w32_pipe_buffer_size > 0 && w32_pipe_buffer_size < UINT_MAX)
8250 pipe_size = w32_pipe_buffer_size;
8251
8252 /* make pipe handles non-inheritable; when we spawn a child, we
8253 replace the relevant handle with an inheritable one. Also put
8254 pipes into binary mode; we will do text mode translation ourselves
8255 if required. */
8256 rc = _pipe (phandles, pipe_size, _O_NOINHERIT | _O_BINARY);
8257
8258 if (rc == 0)
8259 {
8260 /* Protect against overflow, since Windows can open more handles than
8261 our fd_info array has room for. */
8262 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
8263 {
8264 _close (phandles[0]);
8265 _close (phandles[1]);
8266 errno = EMFILE;
8267 rc = -1;
8268 }
8269 else
8270 {
8271 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
8272 fd_info[phandles[0]].flags = flags;
8273
8274 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
8275 fd_info[phandles[1]].flags = flags;
8276 }
8277 }
8278
8279 return rc;
8280 }
8281
8282 /* Function to do blocking read of one byte, needed to implement
8283 select. It is only allowed on communication ports, sockets, or
8284 pipes. */
8285 int
8286 _sys_read_ahead (int fd)
8287 {
8288 child_process * cp;
8289 int rc;
8290
8291 if (fd < 0 || fd >= MAXDESC)
8292 return STATUS_READ_ERROR;
8293
8294 cp = fd_info[fd].cp;
8295
8296 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8297 return STATUS_READ_ERROR;
8298
8299 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
8300 || (fd_info[fd].flags & FILE_READ) == 0)
8301 {
8302 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
8303 emacs_abort ();
8304 }
8305
8306 if ((fd_info[fd].flags & FILE_CONNECT) != 0)
8307 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd));
8308 cp->status = STATUS_READ_IN_PROGRESS;
8309
8310 if (fd_info[fd].flags & FILE_PIPE)
8311 {
8312 rc = _read (fd, &cp->chr, sizeof (char));
8313
8314 /* Give subprocess time to buffer some more output for us before
8315 reporting that input is available; we need this because Windows 95
8316 connects DOS programs to pipes by making the pipe appear to be
8317 the normal console stdout - as a result most DOS programs will
8318 write to stdout without buffering, ie. one character at a
8319 time. Even some W32 programs do this - "dir" in a command
8320 shell on NT is very slow if we don't do this. */
8321 if (rc > 0)
8322 {
8323 int wait = w32_pipe_read_delay;
8324
8325 if (wait > 0)
8326 Sleep (wait);
8327 else if (wait < 0)
8328 while (++wait <= 0)
8329 /* Yield remainder of our time slice, effectively giving a
8330 temporary priority boost to the child process. */
8331 Sleep (0);
8332 }
8333 }
8334 else if (fd_info[fd].flags & FILE_SERIAL)
8335 {
8336 HANDLE hnd = fd_info[fd].hnd;
8337 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8338 COMMTIMEOUTS ct;
8339
8340 /* Configure timeouts for blocking read. */
8341 if (!GetCommTimeouts (hnd, &ct))
8342 {
8343 cp->status = STATUS_READ_ERROR;
8344 return STATUS_READ_ERROR;
8345 }
8346 ct.ReadIntervalTimeout = 0;
8347 ct.ReadTotalTimeoutMultiplier = 0;
8348 ct.ReadTotalTimeoutConstant = 0;
8349 if (!SetCommTimeouts (hnd, &ct))
8350 {
8351 cp->status = STATUS_READ_ERROR;
8352 return STATUS_READ_ERROR;
8353 }
8354
8355 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
8356 {
8357 if (GetLastError () != ERROR_IO_PENDING)
8358 {
8359 cp->status = STATUS_READ_ERROR;
8360 return STATUS_READ_ERROR;
8361 }
8362 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8363 {
8364 cp->status = STATUS_READ_ERROR;
8365 return STATUS_READ_ERROR;
8366 }
8367 }
8368 }
8369 else if (fd_info[fd].flags & FILE_SOCKET)
8370 {
8371 unsigned long nblock = 0;
8372 /* We always want this to block, so temporarily disable NDELAY. */
8373 if (fd_info[fd].flags & FILE_NDELAY)
8374 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8375
8376 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8377
8378 if (fd_info[fd].flags & FILE_NDELAY)
8379 {
8380 nblock = 1;
8381 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8382 }
8383 }
8384
8385 if (rc == sizeof (char))
8386 cp->status = STATUS_READ_SUCCEEDED;
8387 else
8388 cp->status = STATUS_READ_FAILED;
8389
8390 return cp->status;
8391 }
8392
8393 int
8394 _sys_wait_accept (int fd)
8395 {
8396 HANDLE hEv;
8397 child_process * cp;
8398 int rc;
8399
8400 if (fd < 0 || fd >= MAXDESC)
8401 return STATUS_READ_ERROR;
8402
8403 cp = fd_info[fd].cp;
8404
8405 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8406 return STATUS_READ_ERROR;
8407
8408 cp->status = STATUS_READ_FAILED;
8409
8410 hEv = pfn_WSACreateEvent ();
8411 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8412 if (rc != SOCKET_ERROR)
8413 {
8414 do {
8415 rc = WaitForSingleObject (hEv, 500);
8416 Sleep (5);
8417 } while (rc == WAIT_TIMEOUT
8418 && cp->status != STATUS_READ_ERROR
8419 && cp->char_avail);
8420 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8421 if (rc == WAIT_OBJECT_0)
8422 cp->status = STATUS_READ_SUCCEEDED;
8423 }
8424 pfn_WSACloseEvent (hEv);
8425
8426 return cp->status;
8427 }
8428
8429 int
8430 _sys_wait_connect (int fd)
8431 {
8432 HANDLE hEv;
8433 child_process * cp;
8434 int rc;
8435
8436 if (fd < 0 || fd >= MAXDESC)
8437 return STATUS_READ_ERROR;
8438
8439 cp = fd_info[fd].cp;
8440 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8441 return STATUS_READ_ERROR;
8442
8443 cp->status = STATUS_READ_FAILED;
8444
8445 hEv = pfn_WSACreateEvent ();
8446 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_CONNECT);
8447 if (rc != SOCKET_ERROR)
8448 {
8449 do {
8450 rc = WaitForSingleObject (hEv, 500);
8451 Sleep (5);
8452 } while (rc == WAIT_TIMEOUT
8453 && cp->status != STATUS_READ_ERROR
8454 && cp->char_avail);
8455 if (rc == WAIT_OBJECT_0)
8456 {
8457 /* We've got an event, but it could be a successful
8458 connection, or it could be a failure. Find out
8459 which one is it. */
8460 WSANETWORKEVENTS events;
8461
8462 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd), hEv, &events);
8463 if ((events.lNetworkEvents & FD_CONNECT) != 0
8464 && events.iErrorCode[FD_CONNECT_BIT])
8465 {
8466 cp->status = STATUS_CONNECT_FAILED;
8467 cp->errcode = events.iErrorCode[FD_CONNECT_BIT];
8468 }
8469 else
8470 {
8471 cp->status = STATUS_READ_SUCCEEDED;
8472 cp->errcode = 0;
8473 }
8474 }
8475 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8476 }
8477 else
8478 pfn_WSACloseEvent (hEv);
8479
8480 return cp->status;
8481 }
8482
8483 int
8484 sys_read (int fd, char * buffer, unsigned int count)
8485 {
8486 int nchars;
8487 int to_read;
8488 DWORD waiting;
8489 char * orig_buffer = buffer;
8490
8491 if (fd < 0)
8492 {
8493 errno = EBADF;
8494 return -1;
8495 }
8496
8497 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8498 {
8499 child_process *cp = fd_info[fd].cp;
8500
8501 if ((fd_info[fd].flags & FILE_READ) == 0)
8502 {
8503 errno = EBADF;
8504 return -1;
8505 }
8506
8507 nchars = 0;
8508
8509 /* re-read CR carried over from last read */
8510 if (fd_info[fd].flags & FILE_LAST_CR)
8511 {
8512 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8513 *buffer++ = 0x0d;
8514 count--;
8515 nchars++;
8516 fd_info[fd].flags &= ~FILE_LAST_CR;
8517 }
8518
8519 /* presence of a child_process structure means we are operating in
8520 non-blocking mode - otherwise we just call _read directly.
8521 Note that the child_process structure might be missing because
8522 reap_subprocess has been called; in this case the pipe is
8523 already broken, so calling _read on it is okay. */
8524 if (cp)
8525 {
8526 int current_status = cp->status;
8527
8528 switch (current_status)
8529 {
8530 case STATUS_READ_FAILED:
8531 case STATUS_READ_ERROR:
8532 /* report normal EOF if nothing in buffer */
8533 if (nchars <= 0)
8534 fd_info[fd].flags |= FILE_AT_EOF;
8535 return nchars;
8536
8537 case STATUS_READ_READY:
8538 case STATUS_READ_IN_PROGRESS:
8539 #if 0
8540 /* This happens all the time during GnuTLS handshake
8541 with the remote, evidently because GnuTLS waits for
8542 the read to complete by retrying the read operation
8543 upon EAGAIN. So I'm disabling the DebPrint to avoid
8544 wasting cycles on something that is not a real
8545 problem. Enable if you need to debug something that
8546 bumps into this. */
8547 DebPrint (("sys_read called when read is in progress %d\n",
8548 current_status));
8549 #endif
8550 errno = EWOULDBLOCK;
8551 return -1;
8552
8553 case STATUS_READ_SUCCEEDED:
8554 /* consume read-ahead char */
8555 *buffer++ = cp->chr;
8556 count--;
8557 nchars++;
8558 cp->status = STATUS_READ_ACKNOWLEDGED;
8559 ResetEvent (cp->char_avail);
8560
8561 case STATUS_READ_ACKNOWLEDGED:
8562 case STATUS_CONNECT_FAILED:
8563 break;
8564
8565 default:
8566 DebPrint (("sys_read: bad status %d\n", current_status));
8567 errno = EBADF;
8568 return -1;
8569 }
8570
8571 if (fd_info[fd].flags & FILE_PIPE)
8572 {
8573 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8574 to_read = min (waiting, (DWORD) count);
8575
8576 if (to_read > 0)
8577 nchars += _read (fd, buffer, to_read);
8578 }
8579 else if (fd_info[fd].flags & FILE_SERIAL)
8580 {
8581 HANDLE hnd = fd_info[fd].hnd;
8582 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8583 int rc = 0;
8584 COMMTIMEOUTS ct;
8585
8586 if (count > 0)
8587 {
8588 /* Configure timeouts for non-blocking read. */
8589 if (!GetCommTimeouts (hnd, &ct))
8590 {
8591 errno = EIO;
8592 return -1;
8593 }
8594 ct.ReadIntervalTimeout = MAXDWORD;
8595 ct.ReadTotalTimeoutMultiplier = 0;
8596 ct.ReadTotalTimeoutConstant = 0;
8597 if (!SetCommTimeouts (hnd, &ct))
8598 {
8599 errno = EIO;
8600 return -1;
8601 }
8602
8603 if (!ResetEvent (ovl->hEvent))
8604 {
8605 errno = EIO;
8606 return -1;
8607 }
8608 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8609 {
8610 if (GetLastError () != ERROR_IO_PENDING)
8611 {
8612 errno = EIO;
8613 return -1;
8614 }
8615 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8616 {
8617 errno = EIO;
8618 return -1;
8619 }
8620 }
8621 nchars += rc;
8622 }
8623 }
8624 else /* FILE_SOCKET */
8625 {
8626 if (winsock_lib == NULL) emacs_abort ();
8627
8628 /* When a non-blocking 'connect' call fails,
8629 wait_reading_process_output detects this by calling
8630 'getpeername', and then attempts to obtain the connection
8631 error code by trying to read 1 byte from the socket. If
8632 we try to serve that read by calling 'recv' below, the
8633 error we get is a generic WSAENOTCONN, not the actual
8634 connection error. So instead, we use the actual error
8635 code stashed by '_sys_wait_connect' in cp->errcode.
8636 Alternatively, we could have used 'getsockopt', like on
8637 GNU/Linux, but: (a) I have no idea whether the winsock
8638 version could hang, as it does "on some systems" (see the
8639 comment in process.c); and (b) 'getsockopt' on Windows is
8640 documented to clear the socket error for the entire
8641 process, which I'm not sure is TRT; FIXME. */
8642 if (current_status == STATUS_CONNECT_FAILED
8643 && (fd_info[fd].flags & FILE_CONNECT) != 0
8644 && cp->errcode != 0)
8645 {
8646 pfn_WSASetLastError (cp->errcode);
8647 set_errno ();
8648 return -1;
8649 }
8650 /* Do the equivalent of a non-blocking read. */
8651 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8652 if (waiting == 0 && nchars == 0)
8653 {
8654 errno = EWOULDBLOCK;
8655 return -1;
8656 }
8657
8658 if (waiting)
8659 {
8660 /* always use binary mode for sockets */
8661 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8662 if (res == SOCKET_ERROR)
8663 {
8664 set_errno ();
8665 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8666 errno, SOCK_HANDLE (fd)));
8667 return -1;
8668 }
8669 nchars += res;
8670 }
8671 }
8672 }
8673 else
8674 {
8675 int nread = _read (fd, buffer, count);
8676 if (nread >= 0)
8677 nchars += nread;
8678 else if (nchars == 0)
8679 nchars = nread;
8680 }
8681
8682 if (nchars <= 0)
8683 fd_info[fd].flags |= FILE_AT_EOF;
8684 /* Perform text mode translation if required. */
8685 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8686 {
8687 nchars = crlf_to_lf (nchars, orig_buffer);
8688 /* If buffer contains only CR, return that. To be absolutely
8689 sure we should attempt to read the next char, but in
8690 practice a CR to be followed by LF would not appear by
8691 itself in the buffer. */
8692 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8693 {
8694 fd_info[fd].flags |= FILE_LAST_CR;
8695 nchars--;
8696 }
8697 }
8698 }
8699 else
8700 nchars = _read (fd, buffer, count);
8701
8702 return nchars;
8703 }
8704
8705 /* From w32xfns.c */
8706 extern HANDLE interrupt_handle;
8707
8708 int
8709 sys_write (int fd, const void * buffer, unsigned int count)
8710 {
8711 int nchars;
8712 USE_SAFE_ALLOCA;
8713
8714 if (fd < 0)
8715 {
8716 errno = EBADF;
8717 return -1;
8718 }
8719
8720 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8721 {
8722 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8723 {
8724 errno = EBADF;
8725 return -1;
8726 }
8727
8728 /* Perform text mode translation if required. */
8729 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8730 {
8731 char * tmpbuf;
8732 const unsigned char * src = buffer;
8733 unsigned char * dst;
8734 int nbytes = count;
8735
8736 SAFE_NALLOCA (tmpbuf, 2, count);
8737 dst = (unsigned char *)tmpbuf;
8738
8739 while (1)
8740 {
8741 unsigned char *next;
8742 /* Copy next line or remaining bytes. */
8743 next = _memccpy (dst, src, '\n', nbytes);
8744 if (next)
8745 {
8746 /* Copied one line ending with '\n'. */
8747 int copied = next - dst;
8748 nbytes -= copied;
8749 src += copied;
8750 /* Insert '\r' before '\n'. */
8751 next[-1] = '\r';
8752 next[0] = '\n';
8753 dst = next + 1;
8754 count++;
8755 }
8756 else
8757 /* Copied remaining partial line -> now finished. */
8758 break;
8759 }
8760 buffer = tmpbuf;
8761 }
8762 }
8763
8764 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8765 {
8766 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8767 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8768 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8769 DWORD active = 0;
8770
8771 /* This is async (a.k.a. "overlapped") I/O, so the return value
8772 of FALSE from WriteFile means either an error or the output
8773 will be completed asynchronously (ERROR_IO_PENDING). */
8774 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8775 {
8776 if (GetLastError () != ERROR_IO_PENDING)
8777 {
8778 errno = EIO;
8779 nchars = -1;
8780 }
8781 else
8782 {
8783 /* Wait for the write to complete, and watch C-g while
8784 at that. */
8785 if (detect_input_pending ())
8786 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8787 INFINITE, QS_ALLINPUT);
8788 else
8789 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8790 switch (active)
8791 {
8792 case WAIT_OBJECT_0:
8793 /* User pressed C-g, cancel write, then leave.
8794 Don't bother cleaning up as we may only get stuck
8795 in buggy drivers. */
8796 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8797 CancelIo (hnd);
8798 errno = EIO; /* Why not EINTR? */
8799 nchars = -1;
8800 break;
8801 case WAIT_OBJECT_0 + 1:
8802 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8803 {
8804 errno = EIO;
8805 nchars = -1;
8806 }
8807 break;
8808 }
8809 }
8810 }
8811 }
8812 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8813 {
8814 unsigned long nblock = 0;
8815 if (winsock_lib == NULL) emacs_abort ();
8816
8817 child_process *cp = fd_info[fd].cp;
8818
8819 /* If this is a non-blocking socket whose connection is in
8820 progress or terminated with an error already, return the
8821 proper error code to the caller. */
8822 if (cp != NULL && (fd_info[fd].flags & FILE_CONNECT) != 0)
8823 {
8824 /* In case connection is in progress, ENOTCONN that would
8825 result from calling pfn_send is not what callers expect. */
8826 if (cp->status != STATUS_CONNECT_FAILED)
8827 {
8828 errno = EWOULDBLOCK;
8829 return -1;
8830 }
8831 /* In case connection failed, use the actual error code
8832 stashed by '_sys_wait_connect' in cp->errcode. */
8833 else if (cp->errcode != 0)
8834 {
8835 pfn_WSASetLastError (cp->errcode);
8836 set_errno ();
8837 return -1;
8838 }
8839 }
8840
8841 /* TODO: implement select() properly so non-blocking I/O works. */
8842 /* For now, make sure the write blocks. */
8843 if (fd_info[fd].flags & FILE_NDELAY)
8844 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8845
8846 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8847
8848 if (nchars == SOCKET_ERROR)
8849 {
8850 set_errno ();
8851 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8852 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8853 }
8854
8855 /* Set the socket back to non-blocking if it was before,
8856 for other operations that support it. */
8857 if (fd_info[fd].flags & FILE_NDELAY)
8858 {
8859 nblock = 1;
8860 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8861 }
8862 }
8863 else
8864 {
8865 /* Some networked filesystems don't like too large writes, so
8866 break them into smaller chunks. See the Comments section of
8867 the MSDN documentation of WriteFile for details behind the
8868 choice of the value of CHUNK below. See also the thread
8869 http://thread.gmane.org/gmane.comp.version-control.git/145294
8870 in the git mailing list. */
8871 const unsigned char *p = buffer;
8872 const bool is_pipe = (fd < MAXDESC
8873 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8874 == (FILE_PIPE | FILE_NDELAY)));
8875 /* Some programs, notably Node.js's node.exe, seem to never
8876 completely empty the pipe, so writing more than the size of
8877 the pipe's buffer always returns ENOSPC, and we loop forever
8878 between send_process and here. As a workaround, write no
8879 more than the pipe's buffer can hold. */
8880 DWORD pipe_buffer_size;
8881 if (is_pipe)
8882 {
8883 if (!GetNamedPipeInfo ((HANDLE)_get_osfhandle (fd),
8884 NULL, &pipe_buffer_size, NULL, NULL))
8885 {
8886 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8887 pipe_buffer_size = 4096;
8888 }
8889 }
8890 const unsigned chunk = is_pipe ? pipe_buffer_size : 30 * 1024 * 1024;
8891
8892 nchars = 0;
8893 errno = 0;
8894 while (count > 0)
8895 {
8896 unsigned this_chunk = count < chunk ? count : chunk;
8897 int n = _write (fd, p, this_chunk);
8898
8899 if (n > 0)
8900 nchars += n;
8901 if (n < 0)
8902 {
8903 /* When there's no buffer space in a pipe that is in the
8904 non-blocking mode, _write returns ENOSPC. We return
8905 EAGAIN instead, which should trigger the logic in
8906 send_process that enters waiting loop and calls
8907 wait_reading_process_output to allow process input to
8908 be accepted during the wait. Those calls to
8909 wait_reading_process_output allow sys_select to
8910 notice when process input becomes available, thus
8911 avoiding deadlock whereby each side of the pipe is
8912 blocked on write, waiting for the other party to read
8913 its end of the pipe. */
8914 if (errno == ENOSPC && is_pipe)
8915 errno = EAGAIN;
8916 if (nchars == 0)
8917 nchars = -1;
8918 break;
8919 }
8920 else if (n < this_chunk)
8921 break;
8922 count -= n;
8923 p += n;
8924 }
8925 }
8926
8927 SAFE_FREE ();
8928 return nchars;
8929 }
8930
8931 \f
8932 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8933
8934 /* Return information about network interface IFNAME, or about all
8935 interfaces (if IFNAME is nil). */
8936 static Lisp_Object
8937 network_interface_get_info (Lisp_Object ifname)
8938 {
8939 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8940 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8941 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8942 Lisp_Object res = Qnil;
8943
8944 if (retval == ERROR_BUFFER_OVERFLOW)
8945 {
8946 ainfo = xrealloc (ainfo, ainfo_len);
8947 retval = get_adapters_info (ainfo, &ainfo_len);
8948 }
8949
8950 if (retval == ERROR_SUCCESS)
8951 {
8952 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8953 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8954 int if_num;
8955 struct sockaddr_in sa;
8956
8957 /* For the below, we need some winsock functions, so make sure
8958 the winsock DLL is loaded. If we cannot successfully load
8959 it, they will have no use of the information we provide,
8960 anyway, so punt. */
8961 if (!winsock_lib && !init_winsock (1))
8962 goto done;
8963
8964 for (adapter = ainfo; adapter; adapter = adapter->Next)
8965 {
8966 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8967 u_long ip_addr;
8968 /* Present Unix-compatible interface names, instead of the
8969 Windows names, which are really GUIDs not readable by
8970 humans. */
8971 static const char *ifmt[] = {
8972 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8973 "lo", "ifx%d"
8974 };
8975 enum {
8976 NONE = -1,
8977 ETHERNET = 0,
8978 TOKENRING = 1,
8979 FDDI = 2,
8980 PPP = 3,
8981 SLIP = 4,
8982 WLAN = 5,
8983 LOOPBACK = 6,
8984 OTHER_IF = 7
8985 } ifmt_idx;
8986
8987 switch (adapter->Type)
8988 {
8989 case MIB_IF_TYPE_ETHERNET:
8990 /* Windows before Vista reports wireless adapters as
8991 Ethernet. Work around by looking at the Description
8992 string. */
8993 if (strstr (adapter->Description, "Wireless "))
8994 {
8995 ifmt_idx = WLAN;
8996 if_num = wlan_count++;
8997 }
8998 else
8999 {
9000 ifmt_idx = ETHERNET;
9001 if_num = eth_count++;
9002 }
9003 break;
9004 case MIB_IF_TYPE_TOKENRING:
9005 ifmt_idx = TOKENRING;
9006 if_num = tr_count++;
9007 break;
9008 case MIB_IF_TYPE_FDDI:
9009 ifmt_idx = FDDI;
9010 if_num = fddi_count++;
9011 break;
9012 case MIB_IF_TYPE_PPP:
9013 ifmt_idx = PPP;
9014 if_num = ppp_count++;
9015 break;
9016 case MIB_IF_TYPE_SLIP:
9017 ifmt_idx = SLIP;
9018 if_num = sl_count++;
9019 break;
9020 case IF_TYPE_IEEE80211:
9021 ifmt_idx = WLAN;
9022 if_num = wlan_count++;
9023 break;
9024 case MIB_IF_TYPE_LOOPBACK:
9025 if (lo_count < 0)
9026 {
9027 ifmt_idx = LOOPBACK;
9028 if_num = lo_count++;
9029 }
9030 else
9031 ifmt_idx = NONE;
9032 break;
9033 default:
9034 ifmt_idx = OTHER_IF;
9035 if_num = ifx_count++;
9036 break;
9037 }
9038 if (ifmt_idx == NONE)
9039 continue;
9040 sprintf (namebuf, ifmt[ifmt_idx], if_num);
9041
9042 sa.sin_family = AF_INET;
9043 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
9044 if (ip_addr == INADDR_NONE)
9045 {
9046 /* Bogus address, skip this interface. */
9047 continue;
9048 }
9049 sa.sin_addr.s_addr = ip_addr;
9050 sa.sin_port = 0;
9051 if (NILP (ifname))
9052 res = Fcons (Fcons (build_string (namebuf),
9053 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9054 sizeof (struct sockaddr))),
9055 res);
9056 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
9057 {
9058 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
9059 register struct Lisp_Vector *p = XVECTOR (hwaddr);
9060 Lisp_Object flags = Qnil;
9061 int n;
9062 u_long net_mask;
9063
9064 /* Flags. We guess most of them by type, since the
9065 Windows flags are different and hard to get by. */
9066 flags = Fcons (intern ("up"), flags);
9067 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
9068 {
9069 flags = Fcons (intern ("broadcast"), flags);
9070 flags = Fcons (intern ("multicast"), flags);
9071 }
9072 flags = Fcons (intern ("running"), flags);
9073 if (ifmt_idx == PPP)
9074 {
9075 flags = Fcons (intern ("pointopoint"), flags);
9076 flags = Fcons (intern ("noarp"), flags);
9077 }
9078 if (adapter->HaveWins)
9079 flags = Fcons (intern ("WINS"), flags);
9080 if (adapter->DhcpEnabled)
9081 flags = Fcons (intern ("dynamic"), flags);
9082
9083 res = Fcons (flags, res);
9084
9085 /* Hardware address and its family. */
9086 for (n = 0; n < adapter->AddressLength; n++)
9087 p->contents[n] = make_number ((int) adapter->Address[n]);
9088 /* Windows does not support AF_LINK or AF_PACKET family
9089 of addresses. Use an arbitrary family number that is
9090 identical to what GNU/Linux returns. */
9091 res = Fcons (Fcons (make_number (1), hwaddr), res);
9092
9093 /* Network mask. */
9094 sa.sin_family = AF_INET;
9095 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
9096 if (net_mask != INADDR_NONE)
9097 {
9098 sa.sin_addr.s_addr = net_mask;
9099 sa.sin_port = 0;
9100 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9101 sizeof (struct sockaddr)),
9102 res);
9103 }
9104 else
9105 res = Fcons (Qnil, res);
9106
9107 sa.sin_family = AF_INET;
9108 if (ip_addr != INADDR_NONE)
9109 {
9110 /* Broadcast address is only reported by
9111 GetAdaptersAddresses, which is of limited
9112 availability. Generate it on our own. */
9113 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
9114
9115 sa.sin_addr.s_addr = bcast_addr;
9116 sa.sin_port = 0;
9117 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9118 sizeof (struct sockaddr)),
9119 res);
9120
9121 /* IP address. */
9122 sa.sin_addr.s_addr = ip_addr;
9123 sa.sin_port = 0;
9124 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9125 sizeof (struct sockaddr)),
9126 res);
9127 }
9128 else
9129 res = Fcons (Qnil, Fcons (Qnil, res));
9130 }
9131 }
9132 /* GetAdaptersInfo is documented to not report loopback
9133 interfaces, so we generate one out of thin air. */
9134 if (!lo_count)
9135 {
9136 sa.sin_family = AF_INET;
9137 sa.sin_port = 0;
9138 if (NILP (ifname))
9139 {
9140 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9141 res = Fcons (Fcons (build_string ("lo"),
9142 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
9143 sizeof (struct sockaddr))),
9144 res);
9145 }
9146 else if (strcmp (SSDATA (ifname), "lo") == 0)
9147 {
9148 res = Fcons (Fcons (intern ("running"),
9149 Fcons (intern ("loopback"),
9150 Fcons (intern ("up"), Qnil))), Qnil);
9151 /* 772 is what 3 different GNU/Linux systems report for
9152 the loopback interface. */
9153 res = Fcons (Fcons (make_number (772),
9154 Fmake_vector (make_number (6),
9155 make_number (0))),
9156 res);
9157 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
9158 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9159 sizeof (struct sockaddr)),
9160 res);
9161 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
9162 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9163 sizeof (struct sockaddr)),
9164 res);
9165 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
9166 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
9167 sizeof (struct sockaddr)),
9168 res);
9169 }
9170
9171 }
9172 }
9173
9174 done:
9175 xfree (ainfo);
9176 return res;
9177 }
9178
9179 Lisp_Object
9180 network_interface_list (void)
9181 {
9182 return network_interface_get_info (Qnil);
9183 }
9184
9185 Lisp_Object
9186 network_interface_info (Lisp_Object ifname)
9187 {
9188 CHECK_STRING (ifname);
9189 return network_interface_get_info (ifname);
9190 }
9191
9192 \f
9193 /* The Windows CRT functions are "optimized for speed", so they don't
9194 check for timezone and DST changes if they were last called less
9195 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9196 all Emacs features that repeatedly call time functions (e.g.,
9197 display-time) are in real danger of missing timezone and DST
9198 changes. Calling tzset before each localtime call fixes that. */
9199 struct tm *
9200 sys_localtime (const time_t *t)
9201 {
9202 tzset ();
9203 return localtime (t);
9204 }
9205
9206
9207 \f
9208 /* Try loading LIBRARY_ID from the file(s) specified in
9209 Vdynamic_library_alist. If the library is loaded successfully,
9210 return the handle of the DLL, and record the filename in the
9211 property :loaded-from of LIBRARY_ID. If the library could not be
9212 found, or when it was already loaded (because the handle is not
9213 recorded anywhere, and so is lost after use), return NULL.
9214
9215 We could also save the handle in :loaded-from, but currently
9216 there's no use case for it. */
9217 HMODULE
9218 w32_delayed_load (Lisp_Object library_id)
9219 {
9220 HMODULE dll_handle = NULL;
9221
9222 CHECK_SYMBOL (library_id);
9223
9224 if (CONSP (Vdynamic_library_alist)
9225 && NILP (Fassq (library_id, Vlibrary_cache)))
9226 {
9227 Lisp_Object found = Qnil;
9228 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
9229
9230 if (CONSP (dlls))
9231 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
9232 {
9233 Lisp_Object dll = XCAR (dlls);
9234 char name[MAX_UTF8_PATH];
9235 DWORD res = -1;
9236
9237 CHECK_STRING (dll);
9238 dll = ENCODE_FILE (dll);
9239 if (w32_unicode_filenames)
9240 {
9241 wchar_t name_w[MAX_PATH];
9242
9243 filename_to_utf16 (SSDATA (dll), name_w);
9244 dll_handle = LoadLibraryW (name_w);
9245 if (dll_handle)
9246 {
9247 res = GetModuleFileNameW (dll_handle, name_w,
9248 sizeof (name_w));
9249 if (res > 0)
9250 filename_from_utf16 (name_w, name);
9251 }
9252 }
9253 else
9254 {
9255 char name_a[MAX_PATH];
9256
9257 filename_to_ansi (SSDATA (dll), name_a);
9258 dll_handle = LoadLibraryA (name_a);
9259 if (dll_handle)
9260 {
9261 res = GetModuleFileNameA (dll_handle, name_a,
9262 sizeof (name_a));
9263 if (res > 0)
9264 filename_from_ansi (name_a, name);
9265 }
9266 }
9267 if (dll_handle)
9268 {
9269 ptrdiff_t len = strlen (name);
9270 found = Fcons (dll,
9271 (res > 0)
9272 /* Possibly truncated */
9273 ? make_specified_string (name, -1, len, 1)
9274 : Qnil);
9275 /* This prevents thread start and end notifications
9276 from being sent to the DLL, for every thread we
9277 start. We don't need those notifications because
9278 threads we create never use any of these DLLs, only
9279 the main thread uses them. This is supposed to
9280 speed up thread creation. */
9281 DisableThreadLibraryCalls (dll_handle);
9282 break;
9283 }
9284 }
9285
9286 Fput (library_id, QCloaded_from, found);
9287 }
9288
9289 return dll_handle;
9290 }
9291
9292 \f
9293 void
9294 check_windows_init_file (void)
9295 {
9296 /* A common indication that Emacs is not installed properly is when
9297 it cannot find the Windows installation file. If this file does
9298 not exist in the expected place, tell the user. */
9299
9300 if (!noninteractive && !inhibit_window_system
9301 /* Vload_path is not yet initialized when we are loading
9302 loadup.el. */
9303 && NILP (Vpurify_flag))
9304 {
9305 Lisp_Object init_file;
9306 int fd;
9307
9308 /* Implementation note: this function runs early during Emacs
9309 startup, before startup.el is run. So Vload_path is still in
9310 its initial unibyte form, but it holds UTF-8 encoded file
9311 names, since init_callproc was already called. So we do not
9312 need to ENCODE_FILE here, but we do need to convert the file
9313 names from UTF-8 to ANSI. */
9314 init_file = build_string ("term/w32-win");
9315 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
9316 if (fd < 0)
9317 {
9318 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
9319 char *init_file_name = SSDATA (init_file);
9320 char *load_path = SSDATA (load_path_print);
9321 char *buffer = alloca (1024
9322 + strlen (init_file_name)
9323 + strlen (load_path));
9324 char *msg = buffer;
9325 int needed;
9326
9327 sprintf (buffer,
9328 "The Emacs Windows initialization file \"%s.el\" "
9329 "could not be found in your Emacs installation. "
9330 "Emacs checked the following directories for this file:\n"
9331 "\n%s\n\n"
9332 "When Emacs cannot find this file, it usually means that it "
9333 "was not installed properly, or its distribution file was "
9334 "not unpacked properly.\nSee the README.W32 file in the "
9335 "top-level Emacs directory for more information.",
9336 init_file_name, load_path);
9337 needed = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9338 buffer, -1, NULL, 0);
9339 if (needed > 0)
9340 {
9341 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
9342
9343 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags, buffer,
9344 -1, msg_w, needed);
9345 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
9346 NULL, 0, NULL, NULL);
9347 if (needed > 0)
9348 {
9349 char *msg_a = alloca (needed + 1);
9350
9351 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
9352 NULL, NULL);
9353 msg = msg_a;
9354 }
9355 }
9356 MessageBox (NULL,
9357 msg,
9358 "Emacs Abort Dialog",
9359 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
9360 /* Use the low-level system abort. */
9361 abort ();
9362 }
9363 else
9364 {
9365 _close (fd);
9366 }
9367 }
9368 }
9369
9370 void
9371 term_ntproc (int ignored)
9372 {
9373 (void)ignored;
9374
9375 term_timers ();
9376
9377 /* shutdown the socket interface if necessary */
9378 term_winsock ();
9379
9380 term_w32select ();
9381 }
9382
9383 void
9384 init_ntproc (int dumping)
9385 {
9386 sigset_t initial_mask = 0;
9387
9388 /* Initialize the socket interface now if available and requested by
9389 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9390 delayed until open-network-stream is called (w32-has-winsock can
9391 also be used to dynamically load or reload winsock).
9392
9393 Conveniently, init_environment is called before us, so
9394 PRELOAD_WINSOCK can be set in the registry. */
9395
9396 /* Always initialize this correctly. */
9397 winsock_lib = NULL;
9398
9399 if (getenv ("PRELOAD_WINSOCK") != NULL)
9400 init_winsock (TRUE);
9401
9402 /* Initial preparation for subprocess support: replace our standard
9403 handles with non-inheritable versions. */
9404 {
9405 HANDLE parent;
9406 HANDLE stdin_save = INVALID_HANDLE_VALUE;
9407 HANDLE stdout_save = INVALID_HANDLE_VALUE;
9408 HANDLE stderr_save = INVALID_HANDLE_VALUE;
9409
9410 parent = GetCurrentProcess ();
9411
9412 /* ignore errors when duplicating and closing; typically the
9413 handles will be invalid when running as a gui program. */
9414 DuplicateHandle (parent,
9415 GetStdHandle (STD_INPUT_HANDLE),
9416 parent,
9417 &stdin_save,
9418 0,
9419 FALSE,
9420 DUPLICATE_SAME_ACCESS);
9421
9422 DuplicateHandle (parent,
9423 GetStdHandle (STD_OUTPUT_HANDLE),
9424 parent,
9425 &stdout_save,
9426 0,
9427 FALSE,
9428 DUPLICATE_SAME_ACCESS);
9429
9430 DuplicateHandle (parent,
9431 GetStdHandle (STD_ERROR_HANDLE),
9432 parent,
9433 &stderr_save,
9434 0,
9435 FALSE,
9436 DUPLICATE_SAME_ACCESS);
9437
9438 fclose (stdin);
9439 fclose (stdout);
9440 fclose (stderr);
9441
9442 if (stdin_save != INVALID_HANDLE_VALUE)
9443 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
9444 else
9445 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
9446 _fdopen (0, "r");
9447
9448 if (stdout_save != INVALID_HANDLE_VALUE)
9449 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
9450 else
9451 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9452 _fdopen (1, "w");
9453
9454 if (stderr_save != INVALID_HANDLE_VALUE)
9455 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
9456 else
9457 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
9458 _fdopen (2, "w");
9459 }
9460
9461 /* unfortunately, atexit depends on implementation of malloc */
9462 /* atexit (term_ntproc); */
9463 if (!dumping)
9464 {
9465 /* Make sure we start with all signals unblocked. */
9466 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
9467 signal (SIGABRT, term_ntproc);
9468 }
9469 init_timers ();
9470
9471 /* determine which drives are fixed, for GetCachedVolumeInformation */
9472 {
9473 /* GetDriveType must have trailing backslash. */
9474 char drive[] = "A:\\";
9475
9476 /* Loop over all possible drive letters */
9477 while (*drive <= 'Z')
9478 {
9479 /* Record if this drive letter refers to a fixed drive. */
9480 fixed_drives[DRIVE_INDEX (*drive)] =
9481 (GetDriveType (drive) == DRIVE_FIXED);
9482
9483 (*drive)++;
9484 }
9485
9486 /* Reset the volume info cache. */
9487 volume_cache = NULL;
9488 }
9489 }
9490
9491 /*
9492 shutdown_handler ensures that buffers' autosave files are
9493 up to date when the user logs off, or the system shuts down.
9494 */
9495 static BOOL WINAPI
9496 shutdown_handler (DWORD type)
9497 {
9498 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9499 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9500 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9501 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9502 {
9503 /* Shut down cleanly, making sure autosave files are up to date. */
9504 shut_down_emacs (0, Qnil);
9505 }
9506
9507 /* Allow other handlers to handle this signal. */
9508 return FALSE;
9509 }
9510
9511 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9512 NT, return a handle to GDI32.DLL. */
9513 HANDLE
9514 maybe_load_unicows_dll (void)
9515 {
9516 if (os_subtype == OS_9X)
9517 {
9518 HANDLE ret = LoadLibrary ("Unicows.dll");
9519 if (ret)
9520 {
9521 /* These two functions are present on Windows 9X as stubs
9522 that always fail. We need the real implementations from
9523 UNICOWS.DLL, so we must call these functions through
9524 pointers, and assign the correct addresses to these
9525 pointers at program startup (see emacs.c, which calls
9526 this function early on). */
9527 pMultiByteToWideChar =
9528 (MultiByteToWideChar_Proc)GetProcAddress (ret, "MultiByteToWideChar");
9529 pWideCharToMultiByte =
9530 (WideCharToMultiByte_Proc)GetProcAddress (ret, "WideCharToMultiByte");
9531 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9532 return ret;
9533 }
9534 else
9535 {
9536 int button;
9537
9538 button = MessageBox (NULL,
9539 "Emacs cannot load the UNICOWS.DLL library.\n"
9540 "This library is essential for using Emacs\n"
9541 "on this system. You need to install it.\n\n"
9542 "Emacs will exit when you click OK.",
9543 "Emacs cannot load UNICOWS.DLL",
9544 MB_ICONERROR | MB_TASKMODAL
9545 | MB_SETFOREGROUND | MB_OK);
9546 switch (button)
9547 {
9548 case IDOK:
9549 default:
9550 exit (1);
9551 }
9552 }
9553 }
9554 else
9555 {
9556 /* On NT family of Windows, these two functions are always
9557 linked in, so we just assign their addresses to the 2
9558 pointers; no need for the LoadLibrary dance. */
9559 pMultiByteToWideChar = MultiByteToWideChar;
9560 pWideCharToMultiByte = WideCharToMultiByte;
9561 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9562 if (w32_major_version < 5)
9563 multiByteToWideCharFlags = 0;
9564 else
9565 multiByteToWideCharFlags = MB_ERR_INVALID_CHARS;
9566 return LoadLibrary ("Gdi32.dll");
9567 }
9568 }
9569
9570 /*
9571 globals_of_w32 is used to initialize those global variables that
9572 must always be initialized on startup even when the global variable
9573 initialized is non zero (see the function main in emacs.c).
9574 */
9575 void
9576 globals_of_w32 (void)
9577 {
9578 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9579
9580 get_process_times_fn = (GetProcessTimes_Proc)
9581 GetProcAddress (kernel32, "GetProcessTimes");
9582
9583 DEFSYM (QCloaded_from, ":loaded-from");
9584
9585 g_b_init_is_windows_9x = 0;
9586 g_b_init_open_process_token = 0;
9587 g_b_init_get_token_information = 0;
9588 g_b_init_lookup_account_sid = 0;
9589 g_b_init_get_sid_sub_authority = 0;
9590 g_b_init_get_sid_sub_authority_count = 0;
9591 g_b_init_get_security_info = 0;
9592 g_b_init_get_file_security_w = 0;
9593 g_b_init_get_file_security_a = 0;
9594 g_b_init_get_security_descriptor_owner = 0;
9595 g_b_init_get_security_descriptor_group = 0;
9596 g_b_init_is_valid_sid = 0;
9597 g_b_init_create_toolhelp32_snapshot = 0;
9598 g_b_init_process32_first = 0;
9599 g_b_init_process32_next = 0;
9600 g_b_init_open_thread_token = 0;
9601 g_b_init_impersonate_self = 0;
9602 g_b_init_revert_to_self = 0;
9603 g_b_init_get_process_memory_info = 0;
9604 g_b_init_get_process_working_set_size = 0;
9605 g_b_init_global_memory_status = 0;
9606 g_b_init_global_memory_status_ex = 0;
9607 g_b_init_equal_sid = 0;
9608 g_b_init_copy_sid = 0;
9609 g_b_init_get_length_sid = 0;
9610 g_b_init_get_native_system_info = 0;
9611 g_b_init_get_system_times = 0;
9612 g_b_init_create_symbolic_link_w = 0;
9613 g_b_init_create_symbolic_link_a = 0;
9614 g_b_init_get_security_descriptor_dacl = 0;
9615 g_b_init_convert_sd_to_sddl = 0;
9616 g_b_init_convert_sddl_to_sd = 0;
9617 g_b_init_is_valid_security_descriptor = 0;
9618 g_b_init_set_file_security_w = 0;
9619 g_b_init_set_file_security_a = 0;
9620 g_b_init_set_named_security_info_w = 0;
9621 g_b_init_set_named_security_info_a = 0;
9622 g_b_init_get_adapters_info = 0;
9623 g_b_init_compare_string_w = 0;
9624 num_of_processors = 0;
9625 /* The following sets a handler for shutdown notifications for
9626 console apps. This actually applies to Emacs in both console and
9627 GUI modes, since we had to fool windows into thinking emacs is a
9628 console application to get console mode to work. */
9629 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9630
9631 /* "None" is the default group name on standalone workstations. */
9632 strcpy (dflt_group_name, "None");
9633
9634 /* Reset, in case it has some value inherited from dump time. */
9635 w32_stat_get_owner_group = 0;
9636
9637 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9638 (a.k.a. "wide") APIs to invoke functions that accept file
9639 names. */
9640 if (is_windows_9x ())
9641 w32_unicode_filenames = 0;
9642 else
9643 w32_unicode_filenames = 1;
9644
9645 #ifdef HAVE_MODULES
9646 dynlib_reset_last_error ();
9647 #endif
9648
9649 w32_crypto_hprov = (HCRYPTPROV)0;
9650 }
9651
9652 /* For make-serial-process */
9653 int
9654 serial_open (Lisp_Object port_obj)
9655 {
9656 char *port = SSDATA (port_obj);
9657 HANDLE hnd;
9658 child_process *cp;
9659 int fd = -1;
9660
9661 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9662 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9663 if (hnd == INVALID_HANDLE_VALUE)
9664 error ("Could not open %s", port);
9665 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9666 if (fd == -1)
9667 error ("Could not open %s", port);
9668
9669 cp = new_child ();
9670 if (!cp)
9671 error ("Could not create child process");
9672 cp->fd = fd;
9673 cp->status = STATUS_READ_ACKNOWLEDGED;
9674 fd_info[ fd ].hnd = hnd;
9675 fd_info[ fd ].flags |=
9676 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9677 if (fd_info[ fd ].cp != NULL)
9678 {
9679 error ("fd_info[fd = %d] is already in use", fd);
9680 }
9681 fd_info[ fd ].cp = cp;
9682 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9683 if (cp->ovl_read.hEvent == NULL)
9684 error ("Could not create read event");
9685 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9686 if (cp->ovl_write.hEvent == NULL)
9687 error ("Could not create write event");
9688
9689 return fd;
9690 }
9691
9692 /* For serial-process-configure */
9693 void
9694 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9695 {
9696 Lisp_Object childp2 = Qnil;
9697 Lisp_Object tem = Qnil;
9698 HANDLE hnd;
9699 DCB dcb;
9700 COMMTIMEOUTS ct;
9701 char summary[4] = "???"; /* This usually becomes "8N1". */
9702
9703 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9704 error ("Not a serial process");
9705 hnd = fd_info[ p->outfd ].hnd;
9706
9707 childp2 = Fcopy_sequence (p->childp);
9708
9709 /* Initialize timeouts for blocking read and blocking write. */
9710 if (!GetCommTimeouts (hnd, &ct))
9711 error ("GetCommTimeouts() failed");
9712 ct.ReadIntervalTimeout = 0;
9713 ct.ReadTotalTimeoutMultiplier = 0;
9714 ct.ReadTotalTimeoutConstant = 0;
9715 ct.WriteTotalTimeoutMultiplier = 0;
9716 ct.WriteTotalTimeoutConstant = 0;
9717 if (!SetCommTimeouts (hnd, &ct))
9718 error ("SetCommTimeouts() failed");
9719 /* Read port attributes and prepare default configuration. */
9720 memset (&dcb, 0, sizeof (dcb));
9721 dcb.DCBlength = sizeof (DCB);
9722 if (!GetCommState (hnd, &dcb))
9723 error ("GetCommState() failed");
9724 dcb.fBinary = TRUE;
9725 dcb.fNull = FALSE;
9726 dcb.fAbortOnError = FALSE;
9727 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9728 dcb.ErrorChar = 0;
9729 dcb.EofChar = 0;
9730 dcb.EvtChar = 0;
9731
9732 /* Configure speed. */
9733 if (!NILP (Fplist_member (contact, QCspeed)))
9734 tem = Fplist_get (contact, QCspeed);
9735 else
9736 tem = Fplist_get (p->childp, QCspeed);
9737 CHECK_NUMBER (tem);
9738 dcb.BaudRate = XINT (tem);
9739 childp2 = Fplist_put (childp2, QCspeed, tem);
9740
9741 /* Configure bytesize. */
9742 if (!NILP (Fplist_member (contact, QCbytesize)))
9743 tem = Fplist_get (contact, QCbytesize);
9744 else
9745 tem = Fplist_get (p->childp, QCbytesize);
9746 if (NILP (tem))
9747 tem = make_number (8);
9748 CHECK_NUMBER (tem);
9749 if (XINT (tem) != 7 && XINT (tem) != 8)
9750 error (":bytesize must be nil (8), 7, or 8");
9751 dcb.ByteSize = XINT (tem);
9752 summary[0] = XINT (tem) + '0';
9753 childp2 = Fplist_put (childp2, QCbytesize, tem);
9754
9755 /* Configure parity. */
9756 if (!NILP (Fplist_member (contact, QCparity)))
9757 tem = Fplist_get (contact, QCparity);
9758 else
9759 tem = Fplist_get (p->childp, QCparity);
9760 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9761 error (":parity must be nil (no parity), `even', or `odd'");
9762 dcb.fParity = FALSE;
9763 dcb.Parity = NOPARITY;
9764 dcb.fErrorChar = FALSE;
9765 if (NILP (tem))
9766 {
9767 summary[1] = 'N';
9768 }
9769 else if (EQ (tem, Qeven))
9770 {
9771 summary[1] = 'E';
9772 dcb.fParity = TRUE;
9773 dcb.Parity = EVENPARITY;
9774 dcb.fErrorChar = TRUE;
9775 }
9776 else if (EQ (tem, Qodd))
9777 {
9778 summary[1] = 'O';
9779 dcb.fParity = TRUE;
9780 dcb.Parity = ODDPARITY;
9781 dcb.fErrorChar = TRUE;
9782 }
9783 childp2 = Fplist_put (childp2, QCparity, tem);
9784
9785 /* Configure stopbits. */
9786 if (!NILP (Fplist_member (contact, QCstopbits)))
9787 tem = Fplist_get (contact, QCstopbits);
9788 else
9789 tem = Fplist_get (p->childp, QCstopbits);
9790 if (NILP (tem))
9791 tem = make_number (1);
9792 CHECK_NUMBER (tem);
9793 if (XINT (tem) != 1 && XINT (tem) != 2)
9794 error (":stopbits must be nil (1 stopbit), 1, or 2");
9795 summary[2] = XINT (tem) + '0';
9796 if (XINT (tem) == 1)
9797 dcb.StopBits = ONESTOPBIT;
9798 else if (XINT (tem) == 2)
9799 dcb.StopBits = TWOSTOPBITS;
9800 childp2 = Fplist_put (childp2, QCstopbits, tem);
9801
9802 /* Configure flowcontrol. */
9803 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9804 tem = Fplist_get (contact, QCflowcontrol);
9805 else
9806 tem = Fplist_get (p->childp, QCflowcontrol);
9807 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9808 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9809 dcb.fOutxCtsFlow = FALSE;
9810 dcb.fOutxDsrFlow = FALSE;
9811 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9812 dcb.fDsrSensitivity = FALSE;
9813 dcb.fTXContinueOnXoff = FALSE;
9814 dcb.fOutX = FALSE;
9815 dcb.fInX = FALSE;
9816 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9817 dcb.XonChar = 17; /* Control-Q */
9818 dcb.XoffChar = 19; /* Control-S */
9819 if (NILP (tem))
9820 {
9821 /* Already configured. */
9822 }
9823 else if (EQ (tem, Qhw))
9824 {
9825 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9826 dcb.fOutxCtsFlow = TRUE;
9827 }
9828 else if (EQ (tem, Qsw))
9829 {
9830 dcb.fOutX = TRUE;
9831 dcb.fInX = TRUE;
9832 }
9833 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9834
9835 /* Activate configuration. */
9836 if (!SetCommState (hnd, &dcb))
9837 error ("SetCommState() failed");
9838
9839 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9840 pset_childp (p, childp2);
9841 }
9842
9843 /* For make-pipe-process */
9844 void
9845 register_aux_fd (int infd)
9846 {
9847 child_process *cp;
9848
9849 cp = new_child ();
9850 if (!cp)
9851 error ("Could not create child process");
9852 cp->fd = infd;
9853 cp->status = STATUS_READ_ACKNOWLEDGED;
9854
9855 if (fd_info[ infd ].cp != NULL)
9856 {
9857 error ("fd_info[fd = %d] is already in use", infd);
9858 }
9859 fd_info[ infd ].cp = cp;
9860 fd_info[ infd ].hnd = (HANDLE) _get_osfhandle (infd);
9861 }
9862
9863 #ifdef HAVE_GNUTLS
9864
9865 ssize_t
9866 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9867 {
9868 int n, err;
9869 struct Lisp_Process *process = (struct Lisp_Process *)p;
9870 int fd = process->infd;
9871
9872 n = sys_read (fd, (char*)buf, sz);
9873
9874 if (n >= 0)
9875 return n;
9876
9877 err = errno;
9878
9879 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9880 if (err == EWOULDBLOCK)
9881 err = EAGAIN;
9882
9883 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9884
9885 return -1;
9886 }
9887
9888 ssize_t
9889 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9890 {
9891 struct Lisp_Process *process = (struct Lisp_Process *)p;
9892 int fd = process->outfd;
9893 ssize_t n = sys_write (fd, buf, sz);
9894
9895 /* 0 or more bytes written means everything went fine. */
9896 if (n >= 0)
9897 return n;
9898
9899 /* Negative bytes written means we got an error in errno.
9900 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9901 emacs_gnutls_transport_set_errno (process->gnutls_state,
9902 errno == EWOULDBLOCK ? EAGAIN : errno);
9903
9904 return -1;
9905 }
9906 #endif /* HAVE_GNUTLS */
9907
9908 /* end of w32.c */