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