]> code.delx.au - gnu-emacs/blob - src/w32.c
Merge branch 'emacs-24'
[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 (_W64) 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) - 1;
3409 if (!IS_DIRECTORY_SEP (filename[ln]))
3410 strcat (filename, "\\");
3411 strcat (filename, "*");
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 strcat (name, "\\");
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 tem[p - linkfn] = '\0';
5442 strcat (tem, filename);
5443 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
5444 }
5445 else
5446 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
5447
5448 /* Since Windows distinguishes between symlinks to directories and
5449 to files, we provide a kludgy feature: if FILENAME doesn't
5450 exist, but ends in a slash, we create a symlink to directory. If
5451 FILENAME exists and is a directory, we always create a symlink to
5452 directory. */
5453 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5454 if (dir_access == 0 || filename_ends_in_slash)
5455 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5456
5457 tgtfn = (char *)map_w32_filename (filename, NULL);
5458 if (filename_ends_in_slash)
5459 tgtfn[strlen (tgtfn) - 1] = '\0';
5460
5461 errno = 0;
5462 if (!create_symbolic_link (linkfn, tgtfn, flags))
5463 {
5464 /* ENOSYS is set by create_symbolic_link, when it detects that
5465 the OS doesn't support the CreateSymbolicLink API. */
5466 if (errno != ENOSYS)
5467 {
5468 DWORD w32err = GetLastError ();
5469
5470 switch (w32err)
5471 {
5472 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5473 TGTFN point to the same file name, go figure. */
5474 case ERROR_SUCCESS:
5475 case ERROR_FILE_EXISTS:
5476 errno = EEXIST;
5477 break;
5478 case ERROR_ACCESS_DENIED:
5479 errno = EACCES;
5480 break;
5481 case ERROR_FILE_NOT_FOUND:
5482 case ERROR_PATH_NOT_FOUND:
5483 case ERROR_BAD_NETPATH:
5484 case ERROR_INVALID_REPARSE_DATA:
5485 errno = ENOENT;
5486 break;
5487 case ERROR_DIRECTORY:
5488 errno = EISDIR;
5489 break;
5490 case ERROR_PRIVILEGE_NOT_HELD:
5491 case ERROR_NOT_ALL_ASSIGNED:
5492 errno = EPERM;
5493 break;
5494 case ERROR_DISK_FULL:
5495 errno = ENOSPC;
5496 break;
5497 default:
5498 errno = EINVAL;
5499 break;
5500 }
5501 }
5502 return -1;
5503 }
5504 return 0;
5505 }
5506
5507 /* A quick inexpensive test of whether FILENAME identifies a file that
5508 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5509 must already be in the normalized form returned by
5510 map_w32_filename.
5511
5512 Note: for repeated operations on many files, it is best to test
5513 whether the underlying volume actually supports symlinks, by
5514 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5515 avoid the call to this function if it doesn't. That's because the
5516 call to GetFileAttributes takes a non-negligible time, especially
5517 on non-local or removable filesystems. See stat_worker for an
5518 example of how to do that. */
5519 static int
5520 is_symlink (const char *filename)
5521 {
5522 DWORD attrs;
5523 wchar_t filename_w[MAX_PATH];
5524 char filename_a[MAX_PATH];
5525 WIN32_FIND_DATAW wfdw;
5526 WIN32_FIND_DATAA wfda;
5527 HANDLE fh;
5528 int attrs_mean_symlink;
5529
5530 if (w32_unicode_filenames)
5531 {
5532 filename_to_utf16 (filename, filename_w);
5533 attrs = GetFileAttributesW (filename_w);
5534 }
5535 else
5536 {
5537 filename_to_ansi (filename, filename_a);
5538 attrs = GetFileAttributesA (filename_a);
5539 }
5540 if (attrs == -1)
5541 {
5542 DWORD w32err = GetLastError ();
5543
5544 switch (w32err)
5545 {
5546 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5547 break;
5548 case ERROR_ACCESS_DENIED:
5549 errno = EACCES;
5550 break;
5551 case ERROR_FILE_NOT_FOUND:
5552 case ERROR_PATH_NOT_FOUND:
5553 default:
5554 errno = ENOENT;
5555 break;
5556 }
5557 return 0;
5558 }
5559 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5560 return 0;
5561 logon_network_drive (filename);
5562 if (w32_unicode_filenames)
5563 {
5564 fh = FindFirstFileW (filename_w, &wfdw);
5565 attrs_mean_symlink =
5566 (wfdw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5567 && (wfdw.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5568 }
5569 else if (_mbspbrk (filename_a, "?"))
5570 {
5571 /* filename_to_ansi failed to convert the file name. */
5572 errno = ENOENT;
5573 return 0;
5574 }
5575 else
5576 {
5577 fh = FindFirstFileA (filename_a, &wfda);
5578 attrs_mean_symlink =
5579 (wfda.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5580 && (wfda.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5581 }
5582 if (fh == INVALID_HANDLE_VALUE)
5583 return 0;
5584 FindClose (fh);
5585 return attrs_mean_symlink;
5586 }
5587
5588 /* If NAME identifies a symbolic link, copy into BUF the file name of
5589 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5590 null-terminate the target name, even if it fits. Return the number
5591 of bytes copied, or -1 if NAME is not a symlink or any error was
5592 encountered while resolving it. The file name copied into BUF is
5593 encoded in the current ANSI codepage. */
5594 ssize_t
5595 readlink (const char *name, char *buf, size_t buf_size)
5596 {
5597 const char *path;
5598 TOKEN_PRIVILEGES privs;
5599 int restore_privs = 0;
5600 HANDLE sh;
5601 ssize_t retval;
5602 char resolved[MAX_UTF8_PATH];
5603
5604 if (name == NULL)
5605 {
5606 errno = EFAULT;
5607 return -1;
5608 }
5609 if (!*name)
5610 {
5611 errno = ENOENT;
5612 return -1;
5613 }
5614
5615 path = map_w32_filename (name, NULL);
5616
5617 if (strlen (path) > MAX_UTF8_PATH)
5618 {
5619 errno = ENAMETOOLONG;
5620 return -1;
5621 }
5622
5623 errno = 0;
5624 if (is_windows_9x () == TRUE
5625 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5626 || !is_symlink (path))
5627 {
5628 if (!errno)
5629 errno = EINVAL; /* not a symlink */
5630 return -1;
5631 }
5632
5633 /* Done with simple tests, now we're in for some _real_ work. */
5634 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5635 restore_privs = 1;
5636 /* Implementation note: From here and onward, don't return early,
5637 since that will fail to restore the original set of privileges of
5638 the calling thread. */
5639
5640 retval = -1; /* not too optimistic, are we? */
5641
5642 /* Note: In the next call to CreateFile, we use zero as the 2nd
5643 argument because, when the symlink is a hidden/system file,
5644 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5645 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5646 and directory symlinks. */
5647 if (w32_unicode_filenames)
5648 {
5649 wchar_t path_w[MAX_PATH];
5650
5651 filename_to_utf16 (path, path_w);
5652 sh = CreateFileW (path_w, 0, 0, NULL, OPEN_EXISTING,
5653 FILE_FLAG_OPEN_REPARSE_POINT
5654 | FILE_FLAG_BACKUP_SEMANTICS,
5655 NULL);
5656 }
5657 else
5658 {
5659 char path_a[MAX_PATH];
5660
5661 filename_to_ansi (path, path_a);
5662 sh = CreateFileA (path_a, 0, 0, NULL, OPEN_EXISTING,
5663 FILE_FLAG_OPEN_REPARSE_POINT
5664 | FILE_FLAG_BACKUP_SEMANTICS,
5665 NULL);
5666 }
5667 if (sh != INVALID_HANDLE_VALUE)
5668 {
5669 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5670 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5671 DWORD retbytes;
5672
5673 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5674 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5675 &retbytes, NULL))
5676 errno = EIO;
5677 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5678 errno = EINVAL;
5679 else
5680 {
5681 /* Copy the link target name, in wide characters, from
5682 reparse_data, then convert it to multibyte encoding in
5683 the current locale's codepage. */
5684 WCHAR *lwname;
5685 size_t lname_size;
5686 USHORT lwname_len =
5687 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5688 WCHAR *lwname_src =
5689 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5690 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
5691 size_t size_to_copy = buf_size;
5692
5693 /* According to MSDN, PrintNameLength does not include the
5694 terminating null character. */
5695 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5696 memcpy (lwname, lwname_src, lwname_len);
5697 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5698 filename_from_utf16 (lwname, resolved);
5699 dostounix_filename (resolved);
5700 lname_size = strlen (resolved) + 1;
5701 if (lname_size <= buf_size)
5702 size_to_copy = lname_size;
5703 strncpy (buf, resolved, size_to_copy);
5704 /* Success! */
5705 retval = size_to_copy;
5706 }
5707 CloseHandle (sh);
5708 }
5709 else
5710 {
5711 /* CreateFile failed. */
5712 DWORD w32err2 = GetLastError ();
5713
5714 switch (w32err2)
5715 {
5716 case ERROR_FILE_NOT_FOUND:
5717 case ERROR_PATH_NOT_FOUND:
5718 errno = ENOENT;
5719 break;
5720 case ERROR_ACCESS_DENIED:
5721 case ERROR_TOO_MANY_OPEN_FILES:
5722 errno = EACCES;
5723 break;
5724 default:
5725 errno = EPERM;
5726 break;
5727 }
5728 }
5729 if (restore_privs)
5730 {
5731 restore_privilege (&privs);
5732 revert_to_self ();
5733 }
5734
5735 return retval;
5736 }
5737
5738 ssize_t
5739 readlinkat (int fd, char const *name, char *buffer,
5740 size_t buffer_size)
5741 {
5742 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5743 as in fstatat. FIXME: Add proper support for readlinkat. */
5744 char fullname[MAX_UTF8_PATH];
5745
5746 if (fd != AT_FDCWD)
5747 {
5748 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5749 < 0)
5750 {
5751 errno = ENAMETOOLONG;
5752 return -1;
5753 }
5754 name = fullname;
5755 }
5756
5757 return readlink (name, buffer, buffer_size);
5758 }
5759
5760 /* If FILE is a symlink, return its target (stored in a static
5761 buffer); otherwise return FILE.
5762
5763 This function repeatedly resolves symlinks in the last component of
5764 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5765 until it arrives at a file whose last component is not a symlink,
5766 or some error occurs. It returns the target of the last
5767 successfully resolved symlink in the chain. If it succeeds to
5768 resolve even a single symlink, the value returned is an absolute
5769 file name with backslashes (result of GetFullPathName). By
5770 contrast, if the original FILE is returned, it is unaltered.
5771
5772 Note: This function can set errno even if it succeeds.
5773
5774 Implementation note: we only resolve the last portion ("basename")
5775 of the argument FILE and of each following file in the chain,
5776 disregarding any possible symlinks in its leading directories.
5777 This is because Windows system calls and library functions
5778 transparently resolve symlinks in leading directories and return
5779 correct information, as long as the basename is not a symlink. */
5780 static char *
5781 chase_symlinks (const char *file)
5782 {
5783 static char target[MAX_UTF8_PATH];
5784 char link[MAX_UTF8_PATH];
5785 wchar_t target_w[MAX_PATH], link_w[MAX_PATH];
5786 char target_a[MAX_PATH], link_a[MAX_PATH];
5787 ssize_t res, link_len;
5788 int loop_count = 0;
5789
5790 if (is_windows_9x () == TRUE || !is_symlink (file))
5791 return (char *)file;
5792
5793 if (w32_unicode_filenames)
5794 {
5795 wchar_t file_w[MAX_PATH];
5796
5797 filename_to_utf16 (file, file_w);
5798 if (GetFullPathNameW (file_w, MAX_PATH, link_w, NULL) == 0)
5799 return (char *)file;
5800 filename_from_utf16 (link_w, link);
5801 }
5802 else
5803 {
5804 char file_a[MAX_PATH];
5805
5806 filename_to_ansi (file, file_a);
5807 if (GetFullPathNameA (file_a, MAX_PATH, link_a, NULL) == 0)
5808 return (char *)file;
5809 filename_from_ansi (link_a, link);
5810 }
5811 link_len = strlen (link);
5812
5813 target[0] = '\0';
5814 do {
5815
5816 /* Remove trailing slashes, as we want to resolve the last
5817 non-trivial part of the link name. */
5818 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5819 link[link_len--] = '\0';
5820
5821 res = readlink (link, target, MAX_UTF8_PATH);
5822 if (res > 0)
5823 {
5824 target[res] = '\0';
5825 if (!(IS_DEVICE_SEP (target[1])
5826 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5827 {
5828 /* Target is relative. Append it to the directory part of
5829 the symlink, then copy the result back to target. */
5830 char *p = link + link_len;
5831
5832 while (p > link && !IS_ANY_SEP (p[-1]))
5833 p--;
5834 strcpy (p, target);
5835 strcpy (target, link);
5836 }
5837 /* Resolve any "." and ".." to get a fully-qualified file name
5838 in link[] again. */
5839 if (w32_unicode_filenames)
5840 {
5841 filename_to_utf16 (target, target_w);
5842 link_len = GetFullPathNameW (target_w, MAX_PATH, link_w, NULL);
5843 if (link_len > 0)
5844 filename_from_utf16 (link_w, link);
5845 }
5846 else
5847 {
5848 filename_to_ansi (target, target_a);
5849 link_len = GetFullPathNameA (target_a, MAX_PATH, link_a, NULL);
5850 if (link_len > 0)
5851 filename_from_ansi (link_a, link);
5852 }
5853 link_len = strlen (link);
5854 }
5855 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5856
5857 if (loop_count > 100)
5858 errno = ELOOP;
5859
5860 if (target[0] == '\0') /* not a single call to readlink succeeded */
5861 return (char *)file;
5862 return target;
5863 }
5864
5865 \f
5866 /* Posix ACL emulation. */
5867
5868 int
5869 acl_valid (acl_t acl)
5870 {
5871 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5872 }
5873
5874 char *
5875 acl_to_text (acl_t acl, ssize_t *size)
5876 {
5877 LPTSTR str_acl;
5878 SECURITY_INFORMATION flags =
5879 OWNER_SECURITY_INFORMATION |
5880 GROUP_SECURITY_INFORMATION |
5881 DACL_SECURITY_INFORMATION;
5882 char *retval = NULL;
5883 ULONG local_size;
5884 int e = errno;
5885
5886 errno = 0;
5887
5888 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5889 {
5890 errno = e;
5891 /* We don't want to mix heaps, so we duplicate the string in our
5892 heap and free the one allocated by the API. */
5893 retval = xstrdup (str_acl);
5894 if (size)
5895 *size = local_size;
5896 LocalFree (str_acl);
5897 }
5898 else if (errno != ENOTSUP)
5899 errno = EINVAL;
5900
5901 return retval;
5902 }
5903
5904 acl_t
5905 acl_from_text (const char *acl_str)
5906 {
5907 PSECURITY_DESCRIPTOR psd, retval = NULL;
5908 ULONG sd_size;
5909 int e = errno;
5910
5911 errno = 0;
5912
5913 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5914 {
5915 errno = e;
5916 retval = xmalloc (sd_size);
5917 memcpy (retval, psd, sd_size);
5918 LocalFree (psd);
5919 }
5920 else if (errno != ENOTSUP)
5921 errno = EINVAL;
5922
5923 return retval;
5924 }
5925
5926 int
5927 acl_free (void *ptr)
5928 {
5929 xfree (ptr);
5930 return 0;
5931 }
5932
5933 acl_t
5934 acl_get_file (const char *fname, acl_type_t type)
5935 {
5936 PSECURITY_DESCRIPTOR psd = NULL;
5937 const char *filename;
5938
5939 if (type == ACL_TYPE_ACCESS)
5940 {
5941 DWORD sd_len, err;
5942 SECURITY_INFORMATION si =
5943 OWNER_SECURITY_INFORMATION |
5944 GROUP_SECURITY_INFORMATION |
5945 DACL_SECURITY_INFORMATION ;
5946 int e = errno;
5947
5948 filename = map_w32_filename (fname, NULL);
5949 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5950 fname = chase_symlinks (filename);
5951 else
5952 fname = filename;
5953
5954 errno = 0;
5955 if (!get_file_security (fname, si, psd, 0, &sd_len)
5956 && errno != ENOTSUP)
5957 {
5958 err = GetLastError ();
5959 if (err == ERROR_INSUFFICIENT_BUFFER)
5960 {
5961 psd = xmalloc (sd_len);
5962 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5963 {
5964 xfree (psd);
5965 errno = EIO;
5966 psd = NULL;
5967 }
5968 }
5969 else if (err == ERROR_FILE_NOT_FOUND
5970 || err == ERROR_PATH_NOT_FOUND
5971 /* ERROR_INVALID_NAME is what we get if
5972 w32-unicode-filenames is nil and the file cannot
5973 be encoded in the current ANSI codepage. */
5974 || err == ERROR_INVALID_NAME)
5975 errno = ENOENT;
5976 else
5977 errno = EIO;
5978 }
5979 else if (!errno)
5980 errno = e;
5981 }
5982 else if (type != ACL_TYPE_DEFAULT)
5983 errno = EINVAL;
5984
5985 return psd;
5986 }
5987
5988 int
5989 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5990 {
5991 TOKEN_PRIVILEGES old1, old2;
5992 DWORD err;
5993 int st = 0, retval = -1;
5994 SECURITY_INFORMATION flags = 0;
5995 PSID psidOwner, psidGroup;
5996 PACL pacl;
5997 BOOL dflt;
5998 BOOL dacl_present;
5999 int e;
6000 const char *filename;
6001
6002 if (acl_valid (acl) != 0
6003 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
6004 {
6005 errno = EINVAL;
6006 return -1;
6007 }
6008
6009 if (type == ACL_TYPE_DEFAULT)
6010 {
6011 errno = ENOSYS;
6012 return -1;
6013 }
6014
6015 filename = map_w32_filename (fname, NULL);
6016 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
6017 fname = chase_symlinks (filename);
6018 else
6019 fname = filename;
6020
6021 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psidOwner,
6022 &dflt)
6023 && psidOwner)
6024 flags |= OWNER_SECURITY_INFORMATION;
6025 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psidGroup,
6026 &dflt)
6027 && psidGroup)
6028 flags |= GROUP_SECURITY_INFORMATION;
6029 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
6030 &pacl, &dflt)
6031 && dacl_present)
6032 flags |= DACL_SECURITY_INFORMATION;
6033 if (!flags)
6034 return 0;
6035
6036 /* According to KB-245153, setting the owner will succeed if either:
6037 (1) the caller is the user who will be the new owner, and has the
6038 SE_TAKE_OWNERSHIP privilege, or
6039 (2) the caller has the SE_RESTORE privilege, in which case she can
6040 set any valid user or group as the owner
6041
6042 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6043 privileges, and disregard any failures in obtaining them. If
6044 these privileges cannot be obtained, and do not already exist in
6045 the calling thread's security token, this function could fail
6046 with EPERM. */
6047 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
6048 st++;
6049 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
6050 st++;
6051
6052 e = errno;
6053 errno = 0;
6054 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6055 DACL inheritance is involved, but it seems to preserve ownership
6056 better than SetNamedSecurityInfo, which is important e.g., in
6057 copy-file. */
6058 if (!set_file_security (fname, flags, (PSECURITY_DESCRIPTOR)acl))
6059 {
6060 err = GetLastError ();
6061
6062 if (errno != ENOTSUP)
6063 err = set_named_security_info (fname, SE_FILE_OBJECT, flags,
6064 psidOwner, psidGroup, pacl, NULL);
6065 }
6066 else
6067 err = ERROR_SUCCESS;
6068 if (err != ERROR_SUCCESS)
6069 {
6070 if (errno == ENOTSUP)
6071 ;
6072 else if (err == ERROR_INVALID_OWNER
6073 || err == ERROR_NOT_ALL_ASSIGNED
6074 || err == ERROR_ACCESS_DENIED)
6075 {
6076 /* Maybe the requested ACL and the one the file already has
6077 are identical, in which case we can silently ignore the
6078 failure. (And no, Windows doesn't.) */
6079 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
6080
6081 errno = EPERM;
6082 if (current_acl)
6083 {
6084 char *acl_from = acl_to_text (current_acl, NULL);
6085 char *acl_to = acl_to_text (acl, NULL);
6086
6087 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
6088 {
6089 retval = 0;
6090 errno = e;
6091 }
6092 if (acl_from)
6093 acl_free (acl_from);
6094 if (acl_to)
6095 acl_free (acl_to);
6096 acl_free (current_acl);
6097 }
6098 }
6099 else if (err == ERROR_FILE_NOT_FOUND
6100 || err == ERROR_PATH_NOT_FOUND
6101 /* ERROR_INVALID_NAME is what we get if
6102 w32-unicode-filenames is nil and the file cannot be
6103 encoded in the current ANSI codepage. */
6104 || err == ERROR_INVALID_NAME)
6105 errno = ENOENT;
6106 else
6107 errno = EACCES;
6108 }
6109 else
6110 {
6111 retval = 0;
6112 errno = e;
6113 }
6114
6115 if (st)
6116 {
6117 if (st >= 2)
6118 restore_privilege (&old2);
6119 restore_privilege (&old1);
6120 revert_to_self ();
6121 }
6122
6123 return retval;
6124 }
6125
6126 \f
6127 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6128 have a fixed max size for file names, so we don't need the kind of
6129 alloc/malloc/realloc dance the gnulib version does. We also don't
6130 support FD-relative symlinks. */
6131 char *
6132 careadlinkat (int fd, char const *filename,
6133 char *buffer, size_t buffer_size,
6134 struct allocator const *alloc,
6135 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
6136 {
6137 char linkname[MAX_UTF8_PATH];
6138 ssize_t link_size;
6139
6140 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
6141
6142 if (link_size > 0)
6143 {
6144 char *retval = buffer;
6145
6146 linkname[link_size++] = '\0';
6147 if (link_size > buffer_size)
6148 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
6149 if (retval)
6150 memcpy (retval, linkname, link_size);
6151
6152 return retval;
6153 }
6154 return NULL;
6155 }
6156
6157 int
6158 w32_copy_file (const char *from, const char *to,
6159 int keep_time, int preserve_ownership, int copy_acls)
6160 {
6161 acl_t acl = NULL;
6162 BOOL copy_result;
6163 wchar_t from_w[MAX_PATH], to_w[MAX_PATH];
6164 char from_a[MAX_PATH], to_a[MAX_PATH];
6165
6166 /* We ignore preserve_ownership for now. */
6167 preserve_ownership = preserve_ownership;
6168
6169 if (copy_acls)
6170 {
6171 acl = acl_get_file (from, ACL_TYPE_ACCESS);
6172 if (acl == NULL && acl_errno_valid (errno))
6173 return -2;
6174 }
6175 if (w32_unicode_filenames)
6176 {
6177 filename_to_utf16 (from, from_w);
6178 filename_to_utf16 (to, to_w);
6179 copy_result = CopyFileW (from_w, to_w, FALSE);
6180 }
6181 else
6182 {
6183 filename_to_ansi (from, from_a);
6184 filename_to_ansi (to, to_a);
6185 copy_result = CopyFileA (from_a, to_a, FALSE);
6186 }
6187 if (!copy_result)
6188 {
6189 /* CopyFile doesn't set errno when it fails. By far the most
6190 "popular" reason is that the target is read-only. */
6191 DWORD err = GetLastError ();
6192
6193 switch (err)
6194 {
6195 case ERROR_FILE_NOT_FOUND:
6196 errno = ENOENT;
6197 break;
6198 case ERROR_ACCESS_DENIED:
6199 errno = EACCES;
6200 break;
6201 case ERROR_ENCRYPTION_FAILED:
6202 errno = EIO;
6203 break;
6204 default:
6205 errno = EPERM;
6206 break;
6207 }
6208
6209 if (acl)
6210 acl_free (acl);
6211 return -1;
6212 }
6213 /* CopyFile retains the timestamp by default. However, see
6214 "Community Additions" for CopyFile: it sounds like that is not
6215 entirely true. Testing on Windows XP confirms that modified time
6216 is copied, but creation and last-access times are not.
6217 FIXME? */
6218 else if (!keep_time)
6219 {
6220 struct timespec now;
6221 DWORD attributes;
6222
6223 if (w32_unicode_filenames)
6224 {
6225 /* Ensure file is writable while its times are set. */
6226 attributes = GetFileAttributesW (to_w);
6227 SetFileAttributesW (to_w, attributes & ~FILE_ATTRIBUTE_READONLY);
6228 now = current_timespec ();
6229 if (set_file_times (-1, to, now, now))
6230 {
6231 /* Restore original attributes. */
6232 SetFileAttributesW (to_w, attributes);
6233 if (acl)
6234 acl_free (acl);
6235 return -3;
6236 }
6237 /* Restore original attributes. */
6238 SetFileAttributesW (to_w, attributes);
6239 }
6240 else
6241 {
6242 attributes = GetFileAttributesA (to_a);
6243 SetFileAttributesA (to_a, attributes & ~FILE_ATTRIBUTE_READONLY);
6244 now = current_timespec ();
6245 if (set_file_times (-1, to, now, now))
6246 {
6247 SetFileAttributesA (to_a, attributes);
6248 if (acl)
6249 acl_free (acl);
6250 return -3;
6251 }
6252 SetFileAttributesA (to_a, attributes);
6253 }
6254 }
6255 if (acl != NULL)
6256 {
6257 bool fail =
6258 acl_set_file (to, ACL_TYPE_ACCESS, acl) != 0;
6259 acl_free (acl);
6260 if (fail && acl_errno_valid (errno))
6261 return -4;
6262 }
6263
6264 return 0;
6265 }
6266
6267 \f
6268 /* Support for browsing other processes and their attributes. See
6269 process.c for the Lisp bindings. */
6270
6271 /* Helper wrapper functions. */
6272
6273 static HANDLE WINAPI
6274 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
6275 {
6276 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
6277
6278 if (g_b_init_create_toolhelp32_snapshot == 0)
6279 {
6280 g_b_init_create_toolhelp32_snapshot = 1;
6281 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
6282 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6283 "CreateToolhelp32Snapshot");
6284 }
6285 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
6286 {
6287 return INVALID_HANDLE_VALUE;
6288 }
6289 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
6290 }
6291
6292 static BOOL WINAPI
6293 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6294 {
6295 static Process32First_Proc s_pfn_Process32_First = NULL;
6296
6297 if (g_b_init_process32_first == 0)
6298 {
6299 g_b_init_process32_first = 1;
6300 s_pfn_Process32_First = (Process32First_Proc)
6301 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6302 "Process32First");
6303 }
6304 if (s_pfn_Process32_First == NULL)
6305 {
6306 return FALSE;
6307 }
6308 return (s_pfn_Process32_First (hSnapshot, lppe));
6309 }
6310
6311 static BOOL WINAPI
6312 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
6313 {
6314 static Process32Next_Proc s_pfn_Process32_Next = NULL;
6315
6316 if (g_b_init_process32_next == 0)
6317 {
6318 g_b_init_process32_next = 1;
6319 s_pfn_Process32_Next = (Process32Next_Proc)
6320 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6321 "Process32Next");
6322 }
6323 if (s_pfn_Process32_Next == NULL)
6324 {
6325 return FALSE;
6326 }
6327 return (s_pfn_Process32_Next (hSnapshot, lppe));
6328 }
6329
6330 static BOOL WINAPI
6331 open_thread_token (HANDLE ThreadHandle,
6332 DWORD DesiredAccess,
6333 BOOL OpenAsSelf,
6334 PHANDLE TokenHandle)
6335 {
6336 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
6337 HMODULE hm_advapi32 = NULL;
6338 if (is_windows_9x () == TRUE)
6339 {
6340 SetLastError (ERROR_NOT_SUPPORTED);
6341 return FALSE;
6342 }
6343 if (g_b_init_open_thread_token == 0)
6344 {
6345 g_b_init_open_thread_token = 1;
6346 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6347 s_pfn_Open_Thread_Token =
6348 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
6349 }
6350 if (s_pfn_Open_Thread_Token == NULL)
6351 {
6352 SetLastError (ERROR_NOT_SUPPORTED);
6353 return FALSE;
6354 }
6355 return (
6356 s_pfn_Open_Thread_Token (
6357 ThreadHandle,
6358 DesiredAccess,
6359 OpenAsSelf,
6360 TokenHandle)
6361 );
6362 }
6363
6364 static BOOL WINAPI
6365 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
6366 {
6367 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
6368 HMODULE hm_advapi32 = NULL;
6369 if (is_windows_9x () == TRUE)
6370 {
6371 return FALSE;
6372 }
6373 if (g_b_init_impersonate_self == 0)
6374 {
6375 g_b_init_impersonate_self = 1;
6376 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6377 s_pfn_Impersonate_Self =
6378 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
6379 }
6380 if (s_pfn_Impersonate_Self == NULL)
6381 {
6382 return FALSE;
6383 }
6384 return s_pfn_Impersonate_Self (ImpersonationLevel);
6385 }
6386
6387 static BOOL WINAPI
6388 revert_to_self (void)
6389 {
6390 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
6391 HMODULE hm_advapi32 = NULL;
6392 if (is_windows_9x () == TRUE)
6393 {
6394 return FALSE;
6395 }
6396 if (g_b_init_revert_to_self == 0)
6397 {
6398 g_b_init_revert_to_self = 1;
6399 hm_advapi32 = LoadLibrary ("Advapi32.dll");
6400 s_pfn_Revert_To_Self =
6401 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
6402 }
6403 if (s_pfn_Revert_To_Self == NULL)
6404 {
6405 return FALSE;
6406 }
6407 return s_pfn_Revert_To_Self ();
6408 }
6409
6410 static BOOL WINAPI
6411 get_process_memory_info (HANDLE h_proc,
6412 PPROCESS_MEMORY_COUNTERS mem_counters,
6413 DWORD bufsize)
6414 {
6415 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
6416 HMODULE hm_psapi = NULL;
6417 if (is_windows_9x () == TRUE)
6418 {
6419 return FALSE;
6420 }
6421 if (g_b_init_get_process_memory_info == 0)
6422 {
6423 g_b_init_get_process_memory_info = 1;
6424 hm_psapi = LoadLibrary ("Psapi.dll");
6425 if (hm_psapi)
6426 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
6427 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
6428 }
6429 if (s_pfn_Get_Process_Memory_Info == NULL)
6430 {
6431 return FALSE;
6432 }
6433 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
6434 }
6435
6436 static BOOL WINAPI
6437 get_process_working_set_size (HANDLE h_proc,
6438 PSIZE_T minrss,
6439 PSIZE_T maxrss)
6440 {
6441 static GetProcessWorkingSetSize_Proc
6442 s_pfn_Get_Process_Working_Set_Size = NULL;
6443
6444 if (is_windows_9x () == TRUE)
6445 {
6446 return FALSE;
6447 }
6448 if (g_b_init_get_process_working_set_size == 0)
6449 {
6450 g_b_init_get_process_working_set_size = 1;
6451 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
6452 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6453 "GetProcessWorkingSetSize");
6454 }
6455 if (s_pfn_Get_Process_Working_Set_Size == NULL)
6456 {
6457 return FALSE;
6458 }
6459 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
6460 }
6461
6462 static BOOL WINAPI
6463 global_memory_status (MEMORYSTATUS *buf)
6464 {
6465 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
6466
6467 if (is_windows_9x () == TRUE)
6468 {
6469 return FALSE;
6470 }
6471 if (g_b_init_global_memory_status == 0)
6472 {
6473 g_b_init_global_memory_status = 1;
6474 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
6475 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6476 "GlobalMemoryStatus");
6477 }
6478 if (s_pfn_Global_Memory_Status == NULL)
6479 {
6480 return FALSE;
6481 }
6482 return s_pfn_Global_Memory_Status (buf);
6483 }
6484
6485 static BOOL WINAPI
6486 global_memory_status_ex (MEMORY_STATUS_EX *buf)
6487 {
6488 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
6489
6490 if (is_windows_9x () == TRUE)
6491 {
6492 return FALSE;
6493 }
6494 if (g_b_init_global_memory_status_ex == 0)
6495 {
6496 g_b_init_global_memory_status_ex = 1;
6497 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
6498 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6499 "GlobalMemoryStatusEx");
6500 }
6501 if (s_pfn_Global_Memory_Status_Ex == NULL)
6502 {
6503 return FALSE;
6504 }
6505 return s_pfn_Global_Memory_Status_Ex (buf);
6506 }
6507
6508 Lisp_Object
6509 list_system_processes (void)
6510 {
6511 struct gcpro gcpro1;
6512 Lisp_Object proclist = Qnil;
6513 HANDLE h_snapshot;
6514
6515 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6516
6517 if (h_snapshot != INVALID_HANDLE_VALUE)
6518 {
6519 PROCESSENTRY32 proc_entry;
6520 DWORD proc_id;
6521 BOOL res;
6522
6523 GCPRO1 (proclist);
6524
6525 proc_entry.dwSize = sizeof (PROCESSENTRY32);
6526 for (res = process32_first (h_snapshot, &proc_entry); res;
6527 res = process32_next (h_snapshot, &proc_entry))
6528 {
6529 proc_id = proc_entry.th32ProcessID;
6530 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6531 }
6532
6533 CloseHandle (h_snapshot);
6534 UNGCPRO;
6535 proclist = Fnreverse (proclist);
6536 }
6537
6538 return proclist;
6539 }
6540
6541 static int
6542 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6543 {
6544 TOKEN_PRIVILEGES priv;
6545 DWORD priv_size = sizeof (priv);
6546 DWORD opriv_size = sizeof (*old_priv);
6547 HANDLE h_token = NULL;
6548 HANDLE h_thread = GetCurrentThread ();
6549 int ret_val = 0;
6550 BOOL res;
6551
6552 res = open_thread_token (h_thread,
6553 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6554 FALSE, &h_token);
6555 if (!res && GetLastError () == ERROR_NO_TOKEN)
6556 {
6557 if (impersonate_self (SecurityImpersonation))
6558 res = open_thread_token (h_thread,
6559 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6560 FALSE, &h_token);
6561 }
6562 if (res)
6563 {
6564 priv.PrivilegeCount = 1;
6565 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6566 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6567 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6568 old_priv, &opriv_size)
6569 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6570 ret_val = 1;
6571 }
6572 if (h_token)
6573 CloseHandle (h_token);
6574
6575 return ret_val;
6576 }
6577
6578 static int
6579 restore_privilege (TOKEN_PRIVILEGES *priv)
6580 {
6581 DWORD priv_size = sizeof (*priv);
6582 HANDLE h_token = NULL;
6583 int ret_val = 0;
6584
6585 if (open_thread_token (GetCurrentThread (),
6586 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6587 FALSE, &h_token))
6588 {
6589 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6590 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6591 ret_val = 1;
6592 }
6593 if (h_token)
6594 CloseHandle (h_token);
6595
6596 return ret_val;
6597 }
6598
6599 static Lisp_Object
6600 ltime (ULONGLONG time_100ns)
6601 {
6602 ULONGLONG time_sec = time_100ns / 10000000;
6603 int subsec = time_100ns % 10000000;
6604 return list4i (time_sec >> 16, time_sec & 0xffff,
6605 subsec / 10, subsec % 10 * 100000);
6606 }
6607
6608 #define U64_TO_LISP_TIME(time) ltime (time)
6609
6610 static int
6611 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6612 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6613 double *pcpu)
6614 {
6615 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
6616 ULONGLONG tem1, tem2, tem3, tem;
6617
6618 if (!h_proc
6619 || !get_process_times_fn
6620 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6621 &ft_kernel, &ft_user))
6622 return 0;
6623
6624 GetSystemTimeAsFileTime (&ft_current);
6625
6626 FILETIME_TO_U64 (tem1, ft_kernel);
6627 *stime = U64_TO_LISP_TIME (tem1);
6628
6629 FILETIME_TO_U64 (tem2, ft_user);
6630 *utime = U64_TO_LISP_TIME (tem2);
6631
6632 tem3 = tem1 + tem2;
6633 *ttime = U64_TO_LISP_TIME (tem3);
6634
6635 FILETIME_TO_U64 (tem, ft_creation);
6636 /* Process no 4 (System) returns zero creation time. */
6637 if (tem)
6638 tem -= utc_base;
6639 *ctime = U64_TO_LISP_TIME (tem);
6640
6641 if (tem)
6642 {
6643 FILETIME_TO_U64 (tem3, ft_current);
6644 tem = (tem3 - utc_base) - tem;
6645 }
6646 *etime = U64_TO_LISP_TIME (tem);
6647
6648 if (tem)
6649 {
6650 *pcpu = 100.0 * (tem1 + tem2) / tem;
6651 if (*pcpu > 100)
6652 *pcpu = 100.0;
6653 }
6654 else
6655 *pcpu = 0;
6656
6657 return 1;
6658 }
6659
6660 Lisp_Object
6661 system_process_attributes (Lisp_Object pid)
6662 {
6663 struct gcpro gcpro1, gcpro2, gcpro3;
6664 Lisp_Object attrs = Qnil;
6665 Lisp_Object cmd_str, decoded_cmd, tem;
6666 HANDLE h_snapshot, h_proc;
6667 DWORD proc_id;
6668 int found_proc = 0;
6669 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
6670 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
6671 DWORD glength = sizeof (gname);
6672 HANDLE token = NULL;
6673 SID_NAME_USE user_type;
6674 unsigned char *buf = NULL;
6675 DWORD blen = 0;
6676 TOKEN_USER user_token;
6677 TOKEN_PRIMARY_GROUP group_token;
6678 unsigned euid;
6679 unsigned egid;
6680 PROCESS_MEMORY_COUNTERS mem;
6681 PROCESS_MEMORY_COUNTERS_EX mem_ex;
6682 SIZE_T minrss, maxrss;
6683 MEMORYSTATUS memst;
6684 MEMORY_STATUS_EX memstex;
6685 double totphys = 0.0;
6686 Lisp_Object ctime, stime, utime, etime, ttime;
6687 double pcpu;
6688 BOOL result = FALSE;
6689
6690 CHECK_NUMBER_OR_FLOAT (pid);
6691 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6692
6693 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6694
6695 GCPRO3 (attrs, decoded_cmd, tem);
6696
6697 if (h_snapshot != INVALID_HANDLE_VALUE)
6698 {
6699 PROCESSENTRY32 pe;
6700 BOOL res;
6701
6702 pe.dwSize = sizeof (PROCESSENTRY32);
6703 for (res = process32_first (h_snapshot, &pe); res;
6704 res = process32_next (h_snapshot, &pe))
6705 {
6706 if (proc_id == pe.th32ProcessID)
6707 {
6708 if (proc_id == 0)
6709 decoded_cmd = build_string ("Idle");
6710 else
6711 {
6712 /* Decode the command name from locale-specific
6713 encoding. */
6714 cmd_str = build_unibyte_string (pe.szExeFile);
6715
6716 decoded_cmd =
6717 code_convert_string_norecord (cmd_str,
6718 Vlocale_coding_system, 0);
6719 }
6720 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6721 attrs = Fcons (Fcons (Qppid,
6722 make_fixnum_or_float (pe.th32ParentProcessID)),
6723 attrs);
6724 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6725 attrs);
6726 attrs = Fcons (Fcons (Qthcount,
6727 make_fixnum_or_float (pe.cntThreads)),
6728 attrs);
6729 found_proc = 1;
6730 break;
6731 }
6732 }
6733
6734 CloseHandle (h_snapshot);
6735 }
6736
6737 if (!found_proc)
6738 {
6739 UNGCPRO;
6740 return Qnil;
6741 }
6742
6743 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6744 FALSE, proc_id);
6745 /* If we were denied a handle to the process, try again after
6746 enabling the SeDebugPrivilege in our process. */
6747 if (!h_proc)
6748 {
6749 TOKEN_PRIVILEGES priv_current;
6750
6751 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6752 {
6753 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6754 FALSE, proc_id);
6755 restore_privilege (&priv_current);
6756 revert_to_self ();
6757 }
6758 }
6759 if (h_proc)
6760 {
6761 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6762 if (result)
6763 {
6764 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6765 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6766 {
6767 buf = xmalloc (blen);
6768 result = get_token_information (token, TokenUser,
6769 (LPVOID)buf, blen, &needed);
6770 if (result)
6771 {
6772 memcpy (&user_token, buf, sizeof (user_token));
6773 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6774 {
6775 euid = get_rid (user_token.User.Sid);
6776 result = lookup_account_sid (NULL, user_token.User.Sid,
6777 uname, &ulength,
6778 domain, &dlength,
6779 &user_type);
6780 if (result)
6781 w32_add_to_cache (user_token.User.Sid, euid, uname);
6782 else
6783 {
6784 strcpy (uname, "unknown");
6785 result = TRUE;
6786 }
6787 }
6788 ulength = strlen (uname);
6789 }
6790 }
6791 }
6792 if (result)
6793 {
6794 /* Determine a reasonable euid and gid values. */
6795 if (xstrcasecmp ("administrator", uname) == 0)
6796 {
6797 euid = 500; /* well-known Administrator uid */
6798 egid = 513; /* well-known None gid */
6799 }
6800 else
6801 {
6802 /* Get group id and name. */
6803 result = get_token_information (token, TokenPrimaryGroup,
6804 (LPVOID)buf, blen, &needed);
6805 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6806 {
6807 buf = xrealloc (buf, blen = needed);
6808 result = get_token_information (token, TokenPrimaryGroup,
6809 (LPVOID)buf, blen, &needed);
6810 }
6811 if (result)
6812 {
6813 memcpy (&group_token, buf, sizeof (group_token));
6814 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6815 {
6816 egid = get_rid (group_token.PrimaryGroup);
6817 dlength = sizeof (domain);
6818 result =
6819 lookup_account_sid (NULL, group_token.PrimaryGroup,
6820 gname, &glength, NULL, &dlength,
6821 &user_type);
6822 if (result)
6823 w32_add_to_cache (group_token.PrimaryGroup,
6824 egid, gname);
6825 else
6826 {
6827 strcpy (gname, "None");
6828 result = TRUE;
6829 }
6830 }
6831 glength = strlen (gname);
6832 }
6833 }
6834 }
6835 xfree (buf);
6836 }
6837 if (!result)
6838 {
6839 if (!is_windows_9x ())
6840 {
6841 /* We couldn't open the process token, presumably because of
6842 insufficient access rights. Assume this process is run
6843 by the system. */
6844 strcpy (uname, "SYSTEM");
6845 strcpy (gname, "None");
6846 euid = 18; /* SYSTEM */
6847 egid = 513; /* None */
6848 glength = strlen (gname);
6849 ulength = strlen (uname);
6850 }
6851 /* If we are running under Windows 9X, where security calls are
6852 not supported, we assume all processes are run by the current
6853 user. */
6854 else if (GetUserName (uname, &ulength))
6855 {
6856 if (xstrcasecmp ("administrator", uname) == 0)
6857 euid = 0;
6858 else
6859 euid = 123;
6860 egid = euid;
6861 strcpy (gname, "None");
6862 glength = strlen (gname);
6863 ulength = strlen (uname);
6864 }
6865 else
6866 {
6867 euid = 123;
6868 egid = 123;
6869 strcpy (uname, "administrator");
6870 ulength = strlen (uname);
6871 strcpy (gname, "None");
6872 glength = strlen (gname);
6873 }
6874 if (token)
6875 CloseHandle (token);
6876 }
6877
6878 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
6879 tem = make_unibyte_string (uname, ulength);
6880 attrs = Fcons (Fcons (Quser,
6881 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6882 attrs);
6883 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
6884 tem = make_unibyte_string (gname, glength);
6885 attrs = Fcons (Fcons (Qgroup,
6886 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6887 attrs);
6888
6889 if (global_memory_status_ex (&memstex))
6890 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6891 totphys = memstex.ullTotalPhys / 1024.0;
6892 #else
6893 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6894 double, so we need to do this for it... */
6895 {
6896 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6897 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6898 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6899
6900 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6901 }
6902 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6903 else if (global_memory_status (&memst))
6904 totphys = memst.dwTotalPhys / 1024.0;
6905
6906 if (h_proc
6907 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6908 sizeof (mem_ex)))
6909 {
6910 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6911
6912 attrs = Fcons (Fcons (Qmajflt,
6913 make_fixnum_or_float (mem_ex.PageFaultCount)),
6914 attrs);
6915 attrs = Fcons (Fcons (Qvsize,
6916 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6917 attrs);
6918 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6919 if (totphys)
6920 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6921 }
6922 else if (h_proc
6923 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6924 {
6925 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6926
6927 attrs = Fcons (Fcons (Qmajflt,
6928 make_fixnum_or_float (mem.PageFaultCount)),
6929 attrs);
6930 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6931 if (totphys)
6932 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6933 }
6934 else if (h_proc
6935 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6936 {
6937 DWORD rss = maxrss / 1024;
6938
6939 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6940 if (totphys)
6941 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6942 }
6943
6944 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6945 {
6946 attrs = Fcons (Fcons (Qutime, utime), attrs);
6947 attrs = Fcons (Fcons (Qstime, stime), attrs);
6948 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6949 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6950 attrs = Fcons (Fcons (Qetime, etime), attrs);
6951 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6952 }
6953
6954 /* FIXME: Retrieve command line by walking the PEB of the process. */
6955
6956 if (h_proc)
6957 CloseHandle (h_proc);
6958 UNGCPRO;
6959 return attrs;
6960 }
6961
6962 int
6963 w32_memory_info (unsigned long long *totalram, unsigned long long *freeram,
6964 unsigned long long *totalswap, unsigned long long *freeswap)
6965 {
6966 MEMORYSTATUS memst;
6967 MEMORY_STATUS_EX memstex;
6968
6969 /* Use GlobalMemoryStatusEx if available, as it can report more than
6970 2GB of memory. */
6971 if (global_memory_status_ex (&memstex))
6972 {
6973 *totalram = memstex.ullTotalPhys;
6974 *freeram = memstex.ullAvailPhys;
6975 *totalswap = memstex.ullTotalPageFile;
6976 *freeswap = memstex.ullAvailPageFile;
6977 return 0;
6978 }
6979 else if (global_memory_status (&memst))
6980 {
6981 *totalram = memst.dwTotalPhys;
6982 *freeram = memst.dwAvailPhys;
6983 *totalswap = memst.dwTotalPageFile;
6984 *freeswap = memst.dwAvailPageFile;
6985 return 0;
6986 }
6987 else
6988 return -1;
6989 }
6990
6991 \f
6992 /* Wrappers for winsock functions to map between our file descriptors
6993 and winsock's handles; also set h_errno for convenience.
6994
6995 To allow Emacs to run on systems which don't have winsock support
6996 installed, we dynamically link to winsock on startup if present, and
6997 otherwise provide the minimum necessary functionality
6998 (eg. gethostname). */
6999
7000 /* function pointers for relevant socket functions */
7001 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
7002 void (PASCAL *pfn_WSASetLastError) (int iError);
7003 int (PASCAL *pfn_WSAGetLastError) (void);
7004 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
7005 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
7006 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
7007 int (PASCAL *pfn_socket) (int af, int type, int protocol);
7008 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
7009 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
7010 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
7011 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
7012 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
7013 int (PASCAL *pfn_closesocket) (SOCKET s);
7014 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
7015 int (PASCAL *pfn_WSACleanup) (void);
7016
7017 u_short (PASCAL *pfn_htons) (u_short hostshort);
7018 u_short (PASCAL *pfn_ntohs) (u_short netshort);
7019 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
7020 int (PASCAL *pfn_gethostname) (char * name, int namelen);
7021 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
7022 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
7023 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
7024 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
7025 const char * optval, int optlen);
7026 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
7027 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
7028 int * namelen);
7029 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
7030 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
7031 struct sockaddr * from, int * fromlen);
7032 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
7033 const struct sockaddr * to, int tolen);
7034
7035 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7036 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
7037 #ifndef HANDLE_FLAG_INHERIT
7038 #define HANDLE_FLAG_INHERIT 1
7039 #endif
7040
7041 HANDLE winsock_lib;
7042 static int winsock_inuse;
7043
7044 BOOL
7045 term_winsock (void)
7046 {
7047 if (winsock_lib != NULL && winsock_inuse == 0)
7048 {
7049 release_listen_threads ();
7050 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7051 after WSAStartup returns successfully, but it seems reasonable
7052 to allow unloading winsock anyway in that case. */
7053 if (pfn_WSACleanup () == 0 ||
7054 pfn_WSAGetLastError () == WSAENETDOWN)
7055 {
7056 if (FreeLibrary (winsock_lib))
7057 winsock_lib = NULL;
7058 return TRUE;
7059 }
7060 }
7061 return FALSE;
7062 }
7063
7064 BOOL
7065 init_winsock (int load_now)
7066 {
7067 WSADATA winsockData;
7068
7069 if (winsock_lib != NULL)
7070 return TRUE;
7071
7072 pfn_SetHandleInformation
7073 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7074 "SetHandleInformation");
7075
7076 winsock_lib = LoadLibrary ("Ws2_32.dll");
7077
7078 if (winsock_lib != NULL)
7079 {
7080 /* dynamically link to socket functions */
7081
7082 #define LOAD_PROC(fn) \
7083 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7084 goto fail;
7085
7086 LOAD_PROC (WSAStartup);
7087 LOAD_PROC (WSASetLastError);
7088 LOAD_PROC (WSAGetLastError);
7089 LOAD_PROC (WSAEventSelect);
7090 LOAD_PROC (WSACreateEvent);
7091 LOAD_PROC (WSACloseEvent);
7092 LOAD_PROC (socket);
7093 LOAD_PROC (bind);
7094 LOAD_PROC (connect);
7095 LOAD_PROC (ioctlsocket);
7096 LOAD_PROC (recv);
7097 LOAD_PROC (send);
7098 LOAD_PROC (closesocket);
7099 LOAD_PROC (shutdown);
7100 LOAD_PROC (htons);
7101 LOAD_PROC (ntohs);
7102 LOAD_PROC (inet_addr);
7103 LOAD_PROC (gethostname);
7104 LOAD_PROC (gethostbyname);
7105 LOAD_PROC (getservbyname);
7106 LOAD_PROC (getpeername);
7107 LOAD_PROC (WSACleanup);
7108 LOAD_PROC (setsockopt);
7109 LOAD_PROC (listen);
7110 LOAD_PROC (getsockname);
7111 LOAD_PROC (accept);
7112 LOAD_PROC (recvfrom);
7113 LOAD_PROC (sendto);
7114 #undef LOAD_PROC
7115
7116 /* specify version 1.1 of winsock */
7117 if (pfn_WSAStartup (0x101, &winsockData) == 0)
7118 {
7119 if (winsockData.wVersion != 0x101)
7120 goto fail;
7121
7122 if (!load_now)
7123 {
7124 /* Report that winsock exists and is usable, but leave
7125 socket functions disabled. I am assuming that calling
7126 WSAStartup does not require any network interaction,
7127 and in particular does not cause or require a dial-up
7128 connection to be established. */
7129
7130 pfn_WSACleanup ();
7131 FreeLibrary (winsock_lib);
7132 winsock_lib = NULL;
7133 }
7134 winsock_inuse = 0;
7135 return TRUE;
7136 }
7137
7138 fail:
7139 FreeLibrary (winsock_lib);
7140 winsock_lib = NULL;
7141 }
7142
7143 return FALSE;
7144 }
7145
7146
7147 int h_errno = 0;
7148
7149 /* Function to map winsock error codes to errno codes for those errno
7150 code defined in errno.h (errno values not defined by errno.h are
7151 already in nt/inc/sys/socket.h). */
7152 static void
7153 set_errno (void)
7154 {
7155 int wsa_err;
7156
7157 h_errno = 0;
7158 if (winsock_lib == NULL)
7159 wsa_err = EINVAL;
7160 else
7161 wsa_err = pfn_WSAGetLastError ();
7162
7163 switch (wsa_err)
7164 {
7165 case WSAEACCES: errno = EACCES; break;
7166 case WSAEBADF: errno = EBADF; break;
7167 case WSAEFAULT: errno = EFAULT; break;
7168 case WSAEINTR: errno = EINTR; break;
7169 case WSAEINVAL: errno = EINVAL; break;
7170 case WSAEMFILE: errno = EMFILE; break;
7171 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
7172 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
7173 default: errno = wsa_err; break;
7174 }
7175 }
7176
7177 static void
7178 check_errno (void)
7179 {
7180 h_errno = 0;
7181 if (winsock_lib != NULL)
7182 pfn_WSASetLastError (0);
7183 }
7184
7185 /* Extend strerror to handle the winsock-specific error codes. */
7186 struct {
7187 int errnum;
7188 char * msg;
7189 } _wsa_errlist[] = {
7190 {WSAEINTR , "Interrupted function call"},
7191 {WSAEBADF , "Bad file descriptor"},
7192 {WSAEACCES , "Permission denied"},
7193 {WSAEFAULT , "Bad address"},
7194 {WSAEINVAL , "Invalid argument"},
7195 {WSAEMFILE , "Too many open files"},
7196
7197 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
7198 {WSAEINPROGRESS , "Operation now in progress"},
7199 {WSAEALREADY , "Operation already in progress"},
7200 {WSAENOTSOCK , "Socket operation on non-socket"},
7201 {WSAEDESTADDRREQ , "Destination address required"},
7202 {WSAEMSGSIZE , "Message too long"},
7203 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
7204 {WSAENOPROTOOPT , "Bad protocol option"},
7205 {WSAEPROTONOSUPPORT , "Protocol not supported"},
7206 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
7207 {WSAEOPNOTSUPP , "Operation not supported"},
7208 {WSAEPFNOSUPPORT , "Protocol family not supported"},
7209 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
7210 {WSAEADDRINUSE , "Address already in use"},
7211 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
7212 {WSAENETDOWN , "Network is down"},
7213 {WSAENETUNREACH , "Network is unreachable"},
7214 {WSAENETRESET , "Network dropped connection on reset"},
7215 {WSAECONNABORTED , "Software caused connection abort"},
7216 {WSAECONNRESET , "Connection reset by peer"},
7217 {WSAENOBUFS , "No buffer space available"},
7218 {WSAEISCONN , "Socket is already connected"},
7219 {WSAENOTCONN , "Socket is not connected"},
7220 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
7221 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
7222 {WSAETIMEDOUT , "Connection timed out"},
7223 {WSAECONNREFUSED , "Connection refused"},
7224 {WSAELOOP , "Network loop"}, /* not sure */
7225 {WSAENAMETOOLONG , "Name is too long"},
7226 {WSAEHOSTDOWN , "Host is down"},
7227 {WSAEHOSTUNREACH , "No route to host"},
7228 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
7229 {WSAEPROCLIM , "Too many processes"},
7230 {WSAEUSERS , "Too many users"}, /* not sure */
7231 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
7232 {WSAESTALE , "Data is stale"}, /* not sure */
7233 {WSAEREMOTE , "Remote error"}, /* not sure */
7234
7235 {WSASYSNOTREADY , "Network subsystem is unavailable"},
7236 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
7237 {WSANOTINITIALISED , "Winsock not initialized successfully"},
7238 {WSAEDISCON , "Graceful shutdown in progress"},
7239 #ifdef WSAENOMORE
7240 {WSAENOMORE , "No more operations allowed"}, /* not sure */
7241 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
7242 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
7243 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
7244 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
7245 {WSASYSCALLFAILURE , "System call failure"},
7246 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
7247 {WSATYPE_NOT_FOUND , "Class type not found"},
7248 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
7249 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
7250 {WSAEREFUSED , "Operation refused"}, /* not sure */
7251 #endif
7252
7253 {WSAHOST_NOT_FOUND , "Host not found"},
7254 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
7255 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
7256 {WSANO_DATA , "Valid name, no data record of requested type"},
7257
7258 {-1, NULL}
7259 };
7260
7261 char *
7262 sys_strerror (int error_no)
7263 {
7264 int i;
7265 static char unknown_msg[40];
7266
7267 if (error_no >= 0 && error_no < sys_nerr)
7268 return sys_errlist[error_no];
7269
7270 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
7271 if (_wsa_errlist[i].errnum == error_no)
7272 return _wsa_errlist[i].msg;
7273
7274 sprintf (unknown_msg, "Unidentified error: %d", error_no);
7275 return unknown_msg;
7276 }
7277
7278 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7279 but I believe the method of keeping the socket handle separate (and
7280 insuring it is not inheritable) is the correct one. */
7281
7282 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7283
7284 static int socket_to_fd (SOCKET s);
7285
7286 int
7287 sys_socket (int af, int type, int protocol)
7288 {
7289 SOCKET s;
7290
7291 if (winsock_lib == NULL)
7292 {
7293 errno = ENETDOWN;
7294 return INVALID_SOCKET;
7295 }
7296
7297 check_errno ();
7298
7299 /* call the real socket function */
7300 s = pfn_socket (af, type, protocol);
7301
7302 if (s != INVALID_SOCKET)
7303 return socket_to_fd (s);
7304
7305 set_errno ();
7306 return -1;
7307 }
7308
7309 /* Convert a SOCKET to a file descriptor. */
7310 static int
7311 socket_to_fd (SOCKET s)
7312 {
7313 int fd;
7314 child_process * cp;
7315
7316 /* Although under NT 3.5 _open_osfhandle will accept a socket
7317 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7318 that does not work under NT 3.1. However, we can get the same
7319 effect by using a backdoor function to replace an existing
7320 descriptor handle with the one we want. */
7321
7322 /* allocate a file descriptor (with appropriate flags) */
7323 fd = _open ("NUL:", _O_RDWR);
7324 if (fd >= 0)
7325 {
7326 /* Make a non-inheritable copy of the socket handle. Note
7327 that it is possible that sockets aren't actually kernel
7328 handles, which appears to be the case on Windows 9x when
7329 the MS Proxy winsock client is installed. */
7330 {
7331 /* Apparently there is a bug in NT 3.51 with some service
7332 packs, which prevents using DuplicateHandle to make a
7333 socket handle non-inheritable (causes WSACleanup to
7334 hang). The work-around is to use SetHandleInformation
7335 instead if it is available and implemented. */
7336 if (pfn_SetHandleInformation)
7337 {
7338 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
7339 }
7340 else
7341 {
7342 HANDLE parent = GetCurrentProcess ();
7343 HANDLE new_s = INVALID_HANDLE_VALUE;
7344
7345 if (DuplicateHandle (parent,
7346 (HANDLE) s,
7347 parent,
7348 &new_s,
7349 0,
7350 FALSE,
7351 DUPLICATE_SAME_ACCESS))
7352 {
7353 /* It is possible that DuplicateHandle succeeds even
7354 though the socket wasn't really a kernel handle,
7355 because a real handle has the same value. So
7356 test whether the new handle really is a socket. */
7357 long nonblocking = 0;
7358 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
7359 {
7360 pfn_closesocket (s);
7361 s = (SOCKET) new_s;
7362 }
7363 else
7364 {
7365 CloseHandle (new_s);
7366 }
7367 }
7368 }
7369 }
7370 eassert (fd < MAXDESC);
7371 fd_info[fd].hnd = (HANDLE) s;
7372
7373 /* set our own internal flags */
7374 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
7375
7376 cp = new_child ();
7377 if (cp)
7378 {
7379 cp->fd = fd;
7380 cp->status = STATUS_READ_ACKNOWLEDGED;
7381
7382 /* attach child_process to fd_info */
7383 if (fd_info[ fd ].cp != NULL)
7384 {
7385 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
7386 emacs_abort ();
7387 }
7388
7389 fd_info[ fd ].cp = cp;
7390
7391 /* success! */
7392 winsock_inuse++; /* count open sockets */
7393 return fd;
7394 }
7395
7396 /* clean up */
7397 _close (fd);
7398 }
7399 else
7400 pfn_closesocket (s);
7401 errno = EMFILE;
7402 return -1;
7403 }
7404
7405 int
7406 sys_bind (int s, const struct sockaddr * addr, int namelen)
7407 {
7408 if (winsock_lib == NULL)
7409 {
7410 errno = ENOTSOCK;
7411 return SOCKET_ERROR;
7412 }
7413
7414 check_errno ();
7415 if (fd_info[s].flags & FILE_SOCKET)
7416 {
7417 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
7418 if (rc == SOCKET_ERROR)
7419 set_errno ();
7420 return rc;
7421 }
7422 errno = ENOTSOCK;
7423 return SOCKET_ERROR;
7424 }
7425
7426 int
7427 sys_connect (int s, const struct sockaddr * name, int namelen)
7428 {
7429 if (winsock_lib == NULL)
7430 {
7431 errno = ENOTSOCK;
7432 return SOCKET_ERROR;
7433 }
7434
7435 check_errno ();
7436 if (fd_info[s].flags & FILE_SOCKET)
7437 {
7438 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
7439 if (rc == SOCKET_ERROR)
7440 set_errno ();
7441 return rc;
7442 }
7443 errno = ENOTSOCK;
7444 return SOCKET_ERROR;
7445 }
7446
7447 u_short
7448 sys_htons (u_short hostshort)
7449 {
7450 return (winsock_lib != NULL) ?
7451 pfn_htons (hostshort) : hostshort;
7452 }
7453
7454 u_short
7455 sys_ntohs (u_short netshort)
7456 {
7457 return (winsock_lib != NULL) ?
7458 pfn_ntohs (netshort) : netshort;
7459 }
7460
7461 unsigned long
7462 sys_inet_addr (const char * cp)
7463 {
7464 return (winsock_lib != NULL) ?
7465 pfn_inet_addr (cp) : INADDR_NONE;
7466 }
7467
7468 int
7469 sys_gethostname (char * name, int namelen)
7470 {
7471 if (winsock_lib != NULL)
7472 {
7473 int retval;
7474
7475 check_errno ();
7476 retval = pfn_gethostname (name, namelen);
7477 if (retval == SOCKET_ERROR)
7478 set_errno ();
7479 return retval;
7480 }
7481
7482 if (namelen > MAX_COMPUTERNAME_LENGTH)
7483 return !GetComputerName (name, (DWORD *)&namelen);
7484
7485 errno = EFAULT;
7486 return SOCKET_ERROR;
7487 }
7488
7489 struct hostent *
7490 sys_gethostbyname (const char * name)
7491 {
7492 struct hostent * host;
7493 int h_err = h_errno;
7494
7495 if (winsock_lib == NULL)
7496 {
7497 h_errno = NO_RECOVERY;
7498 errno = ENETDOWN;
7499 return NULL;
7500 }
7501
7502 check_errno ();
7503 host = pfn_gethostbyname (name);
7504 if (!host)
7505 {
7506 set_errno ();
7507 h_errno = errno;
7508 }
7509 else
7510 h_errno = h_err;
7511 return host;
7512 }
7513
7514 struct servent *
7515 sys_getservbyname (const char * name, const char * proto)
7516 {
7517 struct servent * serv;
7518
7519 if (winsock_lib == NULL)
7520 {
7521 errno = ENETDOWN;
7522 return NULL;
7523 }
7524
7525 check_errno ();
7526 serv = pfn_getservbyname (name, proto);
7527 if (!serv)
7528 set_errno ();
7529 return serv;
7530 }
7531
7532 int
7533 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
7534 {
7535 if (winsock_lib == NULL)
7536 {
7537 errno = ENETDOWN;
7538 return SOCKET_ERROR;
7539 }
7540
7541 check_errno ();
7542 if (fd_info[s].flags & FILE_SOCKET)
7543 {
7544 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
7545 if (rc == SOCKET_ERROR)
7546 set_errno ();
7547 return rc;
7548 }
7549 errno = ENOTSOCK;
7550 return SOCKET_ERROR;
7551 }
7552
7553 int
7554 sys_shutdown (int s, int how)
7555 {
7556 if (winsock_lib == NULL)
7557 {
7558 errno = ENETDOWN;
7559 return SOCKET_ERROR;
7560 }
7561
7562 check_errno ();
7563 if (fd_info[s].flags & FILE_SOCKET)
7564 {
7565 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
7566 if (rc == SOCKET_ERROR)
7567 set_errno ();
7568 return rc;
7569 }
7570 errno = ENOTSOCK;
7571 return SOCKET_ERROR;
7572 }
7573
7574 int
7575 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
7576 {
7577 if (winsock_lib == NULL)
7578 {
7579 errno = ENETDOWN;
7580 return SOCKET_ERROR;
7581 }
7582
7583 check_errno ();
7584 if (fd_info[s].flags & FILE_SOCKET)
7585 {
7586 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
7587 (const char *)optval, optlen);
7588 if (rc == SOCKET_ERROR)
7589 set_errno ();
7590 return rc;
7591 }
7592 errno = ENOTSOCK;
7593 return SOCKET_ERROR;
7594 }
7595
7596 int
7597 sys_listen (int s, int backlog)
7598 {
7599 if (winsock_lib == NULL)
7600 {
7601 errno = ENETDOWN;
7602 return SOCKET_ERROR;
7603 }
7604
7605 check_errno ();
7606 if (fd_info[s].flags & FILE_SOCKET)
7607 {
7608 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7609 if (rc == SOCKET_ERROR)
7610 set_errno ();
7611 else
7612 fd_info[s].flags |= FILE_LISTEN;
7613 return rc;
7614 }
7615 errno = ENOTSOCK;
7616 return SOCKET_ERROR;
7617 }
7618
7619 int
7620 sys_getsockname (int s, struct sockaddr * name, int * namelen)
7621 {
7622 if (winsock_lib == NULL)
7623 {
7624 errno = ENETDOWN;
7625 return SOCKET_ERROR;
7626 }
7627
7628 check_errno ();
7629 if (fd_info[s].flags & FILE_SOCKET)
7630 {
7631 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7632 if (rc == SOCKET_ERROR)
7633 set_errno ();
7634 return rc;
7635 }
7636 errno = ENOTSOCK;
7637 return SOCKET_ERROR;
7638 }
7639
7640 int
7641 sys_accept (int s, struct sockaddr * addr, int * addrlen)
7642 {
7643 if (winsock_lib == NULL)
7644 {
7645 errno = ENETDOWN;
7646 return -1;
7647 }
7648
7649 check_errno ();
7650 if (fd_info[s].flags & FILE_LISTEN)
7651 {
7652 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
7653 int fd = -1;
7654 if (t == INVALID_SOCKET)
7655 set_errno ();
7656 else
7657 fd = socket_to_fd (t);
7658
7659 if (fd >= 0)
7660 {
7661 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7662 ResetEvent (fd_info[s].cp->char_avail);
7663 }
7664 return fd;
7665 }
7666 errno = ENOTSOCK;
7667 return -1;
7668 }
7669
7670 int
7671 sys_recvfrom (int s, char * buf, int len, int flags,
7672 struct sockaddr * from, int * fromlen)
7673 {
7674 if (winsock_lib == NULL)
7675 {
7676 errno = ENETDOWN;
7677 return SOCKET_ERROR;
7678 }
7679
7680 check_errno ();
7681 if (fd_info[s].flags & FILE_SOCKET)
7682 {
7683 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7684 if (rc == SOCKET_ERROR)
7685 set_errno ();
7686 return rc;
7687 }
7688 errno = ENOTSOCK;
7689 return SOCKET_ERROR;
7690 }
7691
7692 int
7693 sys_sendto (int s, const char * buf, int len, int flags,
7694 const struct sockaddr * to, int tolen)
7695 {
7696 if (winsock_lib == NULL)
7697 {
7698 errno = ENETDOWN;
7699 return SOCKET_ERROR;
7700 }
7701
7702 check_errno ();
7703 if (fd_info[s].flags & FILE_SOCKET)
7704 {
7705 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
7706 if (rc == SOCKET_ERROR)
7707 set_errno ();
7708 return rc;
7709 }
7710 errno = ENOTSOCK;
7711 return SOCKET_ERROR;
7712 }
7713
7714 /* Windows does not have an fcntl function. Provide an implementation
7715 good enough for Emacs. */
7716 int
7717 fcntl (int s, int cmd, int options)
7718 {
7719 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7720 invoked in a context where fd1 is closed and all descriptors less
7721 than fd1 are open, so sys_dup is an adequate implementation. */
7722 if (cmd == F_DUPFD_CLOEXEC)
7723 return sys_dup (s);
7724
7725 check_errno ();
7726 if (fd_info[s].flags & FILE_SOCKET)
7727 {
7728 if (winsock_lib == NULL)
7729 {
7730 errno = ENETDOWN;
7731 return -1;
7732 }
7733
7734 if (cmd == F_SETFL && options == O_NONBLOCK)
7735 {
7736 unsigned long nblock = 1;
7737 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7738 if (rc == SOCKET_ERROR)
7739 set_errno ();
7740 /* Keep track of the fact that we set this to non-blocking. */
7741 fd_info[s].flags |= FILE_NDELAY;
7742 return rc;
7743 }
7744 else
7745 {
7746 errno = EINVAL;
7747 return SOCKET_ERROR;
7748 }
7749 }
7750 else if ((fd_info[s].flags & (FILE_PIPE | FILE_WRITE))
7751 == (FILE_PIPE | FILE_WRITE))
7752 {
7753 /* Force our writes to pipes be non-blocking. */
7754 if (cmd == F_SETFL && options == O_NONBLOCK)
7755 {
7756 HANDLE h = (HANDLE)_get_osfhandle (s);
7757 DWORD pipe_mode = PIPE_NOWAIT;
7758
7759 if (!SetNamedPipeHandleState (h, &pipe_mode, NULL, NULL))
7760 {
7761 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7762 return SOCKET_ERROR;
7763 }
7764 fd_info[s].flags |= FILE_NDELAY;
7765 return 0;
7766 }
7767 else
7768 {
7769 errno = EINVAL;
7770 return SOCKET_ERROR;
7771 }
7772 }
7773 errno = ENOTSOCK;
7774 return SOCKET_ERROR;
7775 }
7776
7777
7778 /* Shadow main io functions: we need to handle pipes and sockets more
7779 intelligently. */
7780
7781 int
7782 sys_close (int fd)
7783 {
7784 int rc;
7785
7786 if (fd < 0)
7787 {
7788 errno = EBADF;
7789 return -1;
7790 }
7791
7792 if (fd < MAXDESC && fd_info[fd].cp)
7793 {
7794 child_process * cp = fd_info[fd].cp;
7795
7796 fd_info[fd].cp = NULL;
7797
7798 if (CHILD_ACTIVE (cp))
7799 {
7800 /* if last descriptor to active child_process then cleanup */
7801 int i;
7802 for (i = 0; i < MAXDESC; i++)
7803 {
7804 if (i == fd)
7805 continue;
7806 if (fd_info[i].cp == cp)
7807 break;
7808 }
7809 if (i == MAXDESC)
7810 {
7811 if (fd_info[fd].flags & FILE_SOCKET)
7812 {
7813 if (winsock_lib == NULL) emacs_abort ();
7814
7815 pfn_shutdown (SOCK_HANDLE (fd), 2);
7816 rc = pfn_closesocket (SOCK_HANDLE (fd));
7817
7818 winsock_inuse--; /* count open sockets */
7819 }
7820 /* If the process handle is NULL, it's either a socket
7821 or serial connection, or a subprocess that was
7822 already reaped by reap_subprocess, but whose
7823 resources were not yet freed, because its output was
7824 not fully read yet by the time it was reaped. (This
7825 usually happens with async subprocesses whose output
7826 is being read by Emacs.) Otherwise, this process was
7827 not reaped yet, so we set its FD to a negative value
7828 to make sure sys_select will eventually get to
7829 calling the SIGCHLD handler for it, which will then
7830 invoke waitpid and reap_subprocess. */
7831 if (cp->procinfo.hProcess == NULL)
7832 delete_child (cp);
7833 else
7834 cp->fd = -1;
7835 }
7836 }
7837 }
7838
7839 if (fd >= 0 && fd < MAXDESC)
7840 fd_info[fd].flags = 0;
7841
7842 /* Note that sockets do not need special treatment here (at least on
7843 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7844 closesocket is equivalent to CloseHandle, which is to be expected
7845 because socket handles are fully fledged kernel handles. */
7846 rc = _close (fd);
7847
7848 return rc;
7849 }
7850
7851 int
7852 sys_dup (int fd)
7853 {
7854 int new_fd;
7855
7856 new_fd = _dup (fd);
7857 if (new_fd >= 0 && new_fd < MAXDESC)
7858 {
7859 /* duplicate our internal info as well */
7860 fd_info[new_fd] = fd_info[fd];
7861 }
7862 return new_fd;
7863 }
7864
7865 int
7866 sys_dup2 (int src, int dst)
7867 {
7868 int rc;
7869
7870 if (dst < 0 || dst >= MAXDESC)
7871 {
7872 errno = EBADF;
7873 return -1;
7874 }
7875
7876 /* make sure we close the destination first if it's a pipe or socket */
7877 if (src != dst && fd_info[dst].flags != 0)
7878 sys_close (dst);
7879
7880 rc = _dup2 (src, dst);
7881 if (rc == 0)
7882 {
7883 /* duplicate our internal info as well */
7884 fd_info[dst] = fd_info[src];
7885 }
7886 return rc;
7887 }
7888
7889 int
7890 pipe2 (int * phandles, int pipe2_flags)
7891 {
7892 int rc;
7893 unsigned flags;
7894
7895 eassert (pipe2_flags == (O_BINARY | O_CLOEXEC));
7896
7897 /* make pipe handles non-inheritable; when we spawn a child, we
7898 replace the relevant handle with an inheritable one. Also put
7899 pipes into binary mode; we will do text mode translation ourselves
7900 if required. */
7901 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
7902
7903 if (rc == 0)
7904 {
7905 /* Protect against overflow, since Windows can open more handles than
7906 our fd_info array has room for. */
7907 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
7908 {
7909 _close (phandles[0]);
7910 _close (phandles[1]);
7911 errno = EMFILE;
7912 rc = -1;
7913 }
7914 else
7915 {
7916 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
7917 fd_info[phandles[0]].flags = flags;
7918
7919 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
7920 fd_info[phandles[1]].flags = flags;
7921 }
7922 }
7923
7924 return rc;
7925 }
7926
7927 /* Function to do blocking read of one byte, needed to implement
7928 select. It is only allowed on communication ports, sockets, or
7929 pipes. */
7930 int
7931 _sys_read_ahead (int fd)
7932 {
7933 child_process * cp;
7934 int rc;
7935
7936 if (fd < 0 || fd >= MAXDESC)
7937 return STATUS_READ_ERROR;
7938
7939 cp = fd_info[fd].cp;
7940
7941 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7942 return STATUS_READ_ERROR;
7943
7944 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
7945 || (fd_info[fd].flags & FILE_READ) == 0)
7946 {
7947 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
7948 emacs_abort ();
7949 }
7950
7951 cp->status = STATUS_READ_IN_PROGRESS;
7952
7953 if (fd_info[fd].flags & FILE_PIPE)
7954 {
7955 rc = _read (fd, &cp->chr, sizeof (char));
7956
7957 /* Give subprocess time to buffer some more output for us before
7958 reporting that input is available; we need this because Windows 95
7959 connects DOS programs to pipes by making the pipe appear to be
7960 the normal console stdout - as a result most DOS programs will
7961 write to stdout without buffering, ie. one character at a
7962 time. Even some W32 programs do this - "dir" in a command
7963 shell on NT is very slow if we don't do this. */
7964 if (rc > 0)
7965 {
7966 int wait = w32_pipe_read_delay;
7967
7968 if (wait > 0)
7969 Sleep (wait);
7970 else if (wait < 0)
7971 while (++wait <= 0)
7972 /* Yield remainder of our time slice, effectively giving a
7973 temporary priority boost to the child process. */
7974 Sleep (0);
7975 }
7976 }
7977 else if (fd_info[fd].flags & FILE_SERIAL)
7978 {
7979 HANDLE hnd = fd_info[fd].hnd;
7980 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7981 COMMTIMEOUTS ct;
7982
7983 /* Configure timeouts for blocking read. */
7984 if (!GetCommTimeouts (hnd, &ct))
7985 {
7986 cp->status = STATUS_READ_ERROR;
7987 return STATUS_READ_ERROR;
7988 }
7989 ct.ReadIntervalTimeout = 0;
7990 ct.ReadTotalTimeoutMultiplier = 0;
7991 ct.ReadTotalTimeoutConstant = 0;
7992 if (!SetCommTimeouts (hnd, &ct))
7993 {
7994 cp->status = STATUS_READ_ERROR;
7995 return STATUS_READ_ERROR;
7996 }
7997
7998 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
7999 {
8000 if (GetLastError () != ERROR_IO_PENDING)
8001 {
8002 cp->status = STATUS_READ_ERROR;
8003 return STATUS_READ_ERROR;
8004 }
8005 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8006 {
8007 cp->status = STATUS_READ_ERROR;
8008 return STATUS_READ_ERROR;
8009 }
8010 }
8011 }
8012 else if (fd_info[fd].flags & FILE_SOCKET)
8013 {
8014 unsigned long nblock = 0;
8015 /* We always want this to block, so temporarily disable NDELAY. */
8016 if (fd_info[fd].flags & FILE_NDELAY)
8017 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8018
8019 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
8020
8021 if (fd_info[fd].flags & FILE_NDELAY)
8022 {
8023 nblock = 1;
8024 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8025 }
8026 }
8027
8028 if (rc == sizeof (char))
8029 cp->status = STATUS_READ_SUCCEEDED;
8030 else
8031 cp->status = STATUS_READ_FAILED;
8032
8033 return cp->status;
8034 }
8035
8036 int
8037 _sys_wait_accept (int fd)
8038 {
8039 HANDLE hEv;
8040 child_process * cp;
8041 int rc;
8042
8043 if (fd < 0 || fd >= MAXDESC)
8044 return STATUS_READ_ERROR;
8045
8046 cp = fd_info[fd].cp;
8047
8048 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
8049 return STATUS_READ_ERROR;
8050
8051 cp->status = STATUS_READ_FAILED;
8052
8053 hEv = pfn_WSACreateEvent ();
8054 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
8055 if (rc != SOCKET_ERROR)
8056 {
8057 do {
8058 rc = WaitForSingleObject (hEv, 500);
8059 Sleep (5);
8060 } while (rc == WAIT_TIMEOUT
8061 && cp->status != STATUS_READ_ERROR
8062 && cp->char_avail);
8063 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
8064 if (rc == WAIT_OBJECT_0)
8065 cp->status = STATUS_READ_SUCCEEDED;
8066 }
8067 pfn_WSACloseEvent (hEv);
8068
8069 return cp->status;
8070 }
8071
8072 int
8073 sys_read (int fd, char * buffer, unsigned int count)
8074 {
8075 int nchars;
8076 int to_read;
8077 DWORD waiting;
8078 char * orig_buffer = buffer;
8079
8080 if (fd < 0)
8081 {
8082 errno = EBADF;
8083 return -1;
8084 }
8085
8086 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8087 {
8088 child_process *cp = fd_info[fd].cp;
8089
8090 if ((fd_info[fd].flags & FILE_READ) == 0)
8091 {
8092 errno = EBADF;
8093 return -1;
8094 }
8095
8096 nchars = 0;
8097
8098 /* re-read CR carried over from last read */
8099 if (fd_info[fd].flags & FILE_LAST_CR)
8100 {
8101 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
8102 *buffer++ = 0x0d;
8103 count--;
8104 nchars++;
8105 fd_info[fd].flags &= ~FILE_LAST_CR;
8106 }
8107
8108 /* presence of a child_process structure means we are operating in
8109 non-blocking mode - otherwise we just call _read directly.
8110 Note that the child_process structure might be missing because
8111 reap_subprocess has been called; in this case the pipe is
8112 already broken, so calling _read on it is okay. */
8113 if (cp)
8114 {
8115 int current_status = cp->status;
8116
8117 switch (current_status)
8118 {
8119 case STATUS_READ_FAILED:
8120 case STATUS_READ_ERROR:
8121 /* report normal EOF if nothing in buffer */
8122 if (nchars <= 0)
8123 fd_info[fd].flags |= FILE_AT_EOF;
8124 return nchars;
8125
8126 case STATUS_READ_READY:
8127 case STATUS_READ_IN_PROGRESS:
8128 DebPrint (("sys_read called when read is in progress\n"));
8129 errno = EWOULDBLOCK;
8130 return -1;
8131
8132 case STATUS_READ_SUCCEEDED:
8133 /* consume read-ahead char */
8134 *buffer++ = cp->chr;
8135 count--;
8136 nchars++;
8137 cp->status = STATUS_READ_ACKNOWLEDGED;
8138 ResetEvent (cp->char_avail);
8139
8140 case STATUS_READ_ACKNOWLEDGED:
8141 break;
8142
8143 default:
8144 DebPrint (("sys_read: bad status %d\n", current_status));
8145 errno = EBADF;
8146 return -1;
8147 }
8148
8149 if (fd_info[fd].flags & FILE_PIPE)
8150 {
8151 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
8152 to_read = min (waiting, (DWORD) count);
8153
8154 if (to_read > 0)
8155 nchars += _read (fd, buffer, to_read);
8156 }
8157 else if (fd_info[fd].flags & FILE_SERIAL)
8158 {
8159 HANDLE hnd = fd_info[fd].hnd;
8160 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
8161 int rc = 0;
8162 COMMTIMEOUTS ct;
8163
8164 if (count > 0)
8165 {
8166 /* Configure timeouts for non-blocking read. */
8167 if (!GetCommTimeouts (hnd, &ct))
8168 {
8169 errno = EIO;
8170 return -1;
8171 }
8172 ct.ReadIntervalTimeout = MAXDWORD;
8173 ct.ReadTotalTimeoutMultiplier = 0;
8174 ct.ReadTotalTimeoutConstant = 0;
8175 if (!SetCommTimeouts (hnd, &ct))
8176 {
8177 errno = EIO;
8178 return -1;
8179 }
8180
8181 if (!ResetEvent (ovl->hEvent))
8182 {
8183 errno = EIO;
8184 return -1;
8185 }
8186 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
8187 {
8188 if (GetLastError () != ERROR_IO_PENDING)
8189 {
8190 errno = EIO;
8191 return -1;
8192 }
8193 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
8194 {
8195 errno = EIO;
8196 return -1;
8197 }
8198 }
8199 nchars += rc;
8200 }
8201 }
8202 else /* FILE_SOCKET */
8203 {
8204 if (winsock_lib == NULL) emacs_abort ();
8205
8206 /* do the equivalent of a non-blocking read */
8207 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
8208 if (waiting == 0 && nchars == 0)
8209 {
8210 errno = EWOULDBLOCK;
8211 return -1;
8212 }
8213
8214 if (waiting)
8215 {
8216 /* always use binary mode for sockets */
8217 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
8218 if (res == SOCKET_ERROR)
8219 {
8220 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8221 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8222 set_errno ();
8223 return -1;
8224 }
8225 nchars += res;
8226 }
8227 }
8228 }
8229 else
8230 {
8231 int nread = _read (fd, buffer, count);
8232 if (nread >= 0)
8233 nchars += nread;
8234 else if (nchars == 0)
8235 nchars = nread;
8236 }
8237
8238 if (nchars <= 0)
8239 fd_info[fd].flags |= FILE_AT_EOF;
8240 /* Perform text mode translation if required. */
8241 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
8242 {
8243 nchars = crlf_to_lf (nchars, orig_buffer);
8244 /* If buffer contains only CR, return that. To be absolutely
8245 sure we should attempt to read the next char, but in
8246 practice a CR to be followed by LF would not appear by
8247 itself in the buffer. */
8248 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
8249 {
8250 fd_info[fd].flags |= FILE_LAST_CR;
8251 nchars--;
8252 }
8253 }
8254 }
8255 else
8256 nchars = _read (fd, buffer, count);
8257
8258 return nchars;
8259 }
8260
8261 /* From w32xfns.c */
8262 extern HANDLE interrupt_handle;
8263
8264 int
8265 sys_write (int fd, const void * buffer, unsigned int count)
8266 {
8267 int nchars;
8268 USE_SAFE_ALLOCA;
8269
8270 if (fd < 0)
8271 {
8272 errno = EBADF;
8273 return -1;
8274 }
8275
8276 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
8277 {
8278 if ((fd_info[fd].flags & FILE_WRITE) == 0)
8279 {
8280 errno = EBADF;
8281 return -1;
8282 }
8283
8284 /* Perform text mode translation if required. */
8285 if ((fd_info[fd].flags & FILE_BINARY) == 0)
8286 {
8287 char * tmpbuf;
8288 const unsigned char * src = buffer;
8289 unsigned char * dst;
8290 int nbytes = count;
8291
8292 SAFE_NALLOCA (tmpbuf, 2, count);
8293 dst = tmpbuf;
8294
8295 while (1)
8296 {
8297 unsigned char *next;
8298 /* Copy next line or remaining bytes. */
8299 next = _memccpy (dst, src, '\n', nbytes);
8300 if (next)
8301 {
8302 /* Copied one line ending with '\n'. */
8303 int copied = next - dst;
8304 nbytes -= copied;
8305 src += copied;
8306 /* Insert '\r' before '\n'. */
8307 next[-1] = '\r';
8308 next[0] = '\n';
8309 dst = next + 1;
8310 count++;
8311 }
8312 else
8313 /* Copied remaining partial line -> now finished. */
8314 break;
8315 }
8316 buffer = tmpbuf;
8317 }
8318 }
8319
8320 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
8321 {
8322 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
8323 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
8324 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
8325 DWORD active = 0;
8326
8327 /* This is async (a.k.a. "overlapped") I/O, so the return value
8328 of FALSE from WriteFile means either an error or the output
8329 will be completed asynchronously (ERROR_IO_PENDING). */
8330 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
8331 {
8332 if (GetLastError () != ERROR_IO_PENDING)
8333 {
8334 errno = EIO;
8335 nchars = -1;
8336 }
8337 else
8338 {
8339 /* Wait for the write to complete, and watch C-g while
8340 at that. */
8341 if (detect_input_pending ())
8342 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE,
8343 INFINITE, QS_ALLINPUT);
8344 else
8345 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
8346 switch (active)
8347 {
8348 case WAIT_OBJECT_0:
8349 /* User pressed C-g, cancel write, then leave.
8350 Don't bother cleaning up as we may only get stuck
8351 in buggy drivers. */
8352 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
8353 CancelIo (hnd);
8354 errno = EIO; /* Why not EINTR? */
8355 nchars = -1;
8356 break;
8357 case WAIT_OBJECT_0 + 1:
8358 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
8359 {
8360 errno = EIO;
8361 nchars = -1;
8362 }
8363 break;
8364 }
8365 }
8366 }
8367 }
8368 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
8369 {
8370 unsigned long nblock = 0;
8371 if (winsock_lib == NULL) emacs_abort ();
8372
8373 /* TODO: implement select() properly so non-blocking I/O works. */
8374 /* For now, make sure the write blocks. */
8375 if (fd_info[fd].flags & FILE_NDELAY)
8376 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8377
8378 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
8379
8380 /* Set the socket back to non-blocking if it was before,
8381 for other operations that support it. */
8382 if (fd_info[fd].flags & FILE_NDELAY)
8383 {
8384 nblock = 1;
8385 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
8386 }
8387
8388 if (nchars == SOCKET_ERROR)
8389 {
8390 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8391 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
8392 set_errno ();
8393 }
8394 }
8395 else
8396 {
8397 /* Some networked filesystems don't like too large writes, so
8398 break them into smaller chunks. See the Comments section of
8399 the MSDN documentation of WriteFile for details behind the
8400 choice of the value of CHUNK below. See also the thread
8401 http://thread.gmane.org/gmane.comp.version-control.git/145294
8402 in the git mailing list. */
8403 const unsigned char *p = buffer;
8404 const unsigned chunk = 30 * 1024 * 1024;
8405
8406 nchars = 0;
8407 while (count > 0)
8408 {
8409 unsigned this_chunk = count < chunk ? count : chunk;
8410 int n = _write (fd, p, this_chunk);
8411
8412 nchars += n;
8413 if (n < 0)
8414 {
8415 /* When there's no buffer space in a pipe that is in the
8416 non-blocking mode, _write returns ENOSPC. We return
8417 EAGAIN instead, which should trigger the logic in
8418 send_process that enters waiting loop and calls
8419 wait_reading_process_output to allow process input to
8420 be accepted during the wait. Those calls to
8421 wait_reading_process_output allow sys_select to
8422 notice when process input becomes available, thus
8423 avoiding deadlock whereby each side of the pipe is
8424 blocked on write, waiting for the other party to read
8425 its end of the pipe. */
8426 if (errno == ENOSPC
8427 && fd < MAXDESC
8428 && ((fd_info[fd].flags & (FILE_PIPE | FILE_NDELAY))
8429 == (FILE_PIPE | FILE_NDELAY)))
8430 errno = EAGAIN;
8431 nchars = n;
8432 break;
8433 }
8434 else if (n < this_chunk)
8435 break;
8436 count -= n;
8437 p += n;
8438 }
8439 }
8440
8441 SAFE_FREE ();
8442 return nchars;
8443 }
8444
8445 \f
8446 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8447
8448 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
8449
8450 /* Return information about network interface IFNAME, or about all
8451 interfaces (if IFNAME is nil). */
8452 static Lisp_Object
8453 network_interface_get_info (Lisp_Object ifname)
8454 {
8455 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
8456 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
8457 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
8458 Lisp_Object res = Qnil;
8459
8460 if (retval == ERROR_BUFFER_OVERFLOW)
8461 {
8462 ainfo = xrealloc (ainfo, ainfo_len);
8463 retval = get_adapters_info (ainfo, &ainfo_len);
8464 }
8465
8466 if (retval == ERROR_SUCCESS)
8467 {
8468 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
8469 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
8470 int if_num;
8471 struct sockaddr_in sa;
8472
8473 /* For the below, we need some winsock functions, so make sure
8474 the winsock DLL is loaded. If we cannot successfully load
8475 it, they will have no use of the information we provide,
8476 anyway, so punt. */
8477 if (!winsock_lib && !init_winsock (1))
8478 goto done;
8479
8480 for (adapter = ainfo; adapter; adapter = adapter->Next)
8481 {
8482 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
8483 u_long ip_addr;
8484 /* Present Unix-compatible interface names, instead of the
8485 Windows names, which are really GUIDs not readable by
8486 humans. */
8487 static const char *ifmt[] = {
8488 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8489 "lo", "ifx%d"
8490 };
8491 enum {
8492 NONE = -1,
8493 ETHERNET = 0,
8494 TOKENRING = 1,
8495 FDDI = 2,
8496 PPP = 3,
8497 SLIP = 4,
8498 WLAN = 5,
8499 LOOPBACK = 6,
8500 OTHER_IF = 7
8501 } ifmt_idx;
8502
8503 switch (adapter->Type)
8504 {
8505 case MIB_IF_TYPE_ETHERNET:
8506 /* Windows before Vista reports wireless adapters as
8507 Ethernet. Work around by looking at the Description
8508 string. */
8509 if (strstr (adapter->Description, "Wireless "))
8510 {
8511 ifmt_idx = WLAN;
8512 if_num = wlan_count++;
8513 }
8514 else
8515 {
8516 ifmt_idx = ETHERNET;
8517 if_num = eth_count++;
8518 }
8519 break;
8520 case MIB_IF_TYPE_TOKENRING:
8521 ifmt_idx = TOKENRING;
8522 if_num = tr_count++;
8523 break;
8524 case MIB_IF_TYPE_FDDI:
8525 ifmt_idx = FDDI;
8526 if_num = fddi_count++;
8527 break;
8528 case MIB_IF_TYPE_PPP:
8529 ifmt_idx = PPP;
8530 if_num = ppp_count++;
8531 break;
8532 case MIB_IF_TYPE_SLIP:
8533 ifmt_idx = SLIP;
8534 if_num = sl_count++;
8535 break;
8536 case IF_TYPE_IEEE80211:
8537 ifmt_idx = WLAN;
8538 if_num = wlan_count++;
8539 break;
8540 case MIB_IF_TYPE_LOOPBACK:
8541 if (lo_count < 0)
8542 {
8543 ifmt_idx = LOOPBACK;
8544 if_num = lo_count++;
8545 }
8546 else
8547 ifmt_idx = NONE;
8548 break;
8549 default:
8550 ifmt_idx = OTHER_IF;
8551 if_num = ifx_count++;
8552 break;
8553 }
8554 if (ifmt_idx == NONE)
8555 continue;
8556 sprintf (namebuf, ifmt[ifmt_idx], if_num);
8557
8558 sa.sin_family = AF_INET;
8559 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
8560 if (ip_addr == INADDR_NONE)
8561 {
8562 /* Bogus address, skip this interface. */
8563 continue;
8564 }
8565 sa.sin_addr.s_addr = ip_addr;
8566 sa.sin_port = 0;
8567 if (NILP (ifname))
8568 res = Fcons (Fcons (build_string (namebuf),
8569 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8570 sizeof (struct sockaddr))),
8571 res);
8572 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
8573 {
8574 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
8575 register struct Lisp_Vector *p = XVECTOR (hwaddr);
8576 Lisp_Object flags = Qnil;
8577 int n;
8578 u_long net_mask;
8579
8580 /* Flags. We guess most of them by type, since the
8581 Windows flags are different and hard to get by. */
8582 flags = Fcons (intern ("up"), flags);
8583 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
8584 {
8585 flags = Fcons (intern ("broadcast"), flags);
8586 flags = Fcons (intern ("multicast"), flags);
8587 }
8588 flags = Fcons (intern ("running"), flags);
8589 if (ifmt_idx == PPP)
8590 {
8591 flags = Fcons (intern ("pointopoint"), flags);
8592 flags = Fcons (intern ("noarp"), flags);
8593 }
8594 if (adapter->HaveWins)
8595 flags = Fcons (intern ("WINS"), flags);
8596 if (adapter->DhcpEnabled)
8597 flags = Fcons (intern ("dynamic"), flags);
8598
8599 res = Fcons (flags, res);
8600
8601 /* Hardware address and its family. */
8602 for (n = 0; n < adapter->AddressLength; n++)
8603 p->contents[n] = make_number ((int) adapter->Address[n]);
8604 /* Windows does not support AF_LINK or AF_PACKET family
8605 of addresses. Use an arbitrary family number that is
8606 identical to what GNU/Linux returns. */
8607 res = Fcons (Fcons (make_number (1), hwaddr), res);
8608
8609 /* Network mask. */
8610 sa.sin_family = AF_INET;
8611 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
8612 if (net_mask != INADDR_NONE)
8613 {
8614 sa.sin_addr.s_addr = net_mask;
8615 sa.sin_port = 0;
8616 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8617 sizeof (struct sockaddr)),
8618 res);
8619 }
8620 else
8621 res = Fcons (Qnil, res);
8622
8623 sa.sin_family = AF_INET;
8624 if (ip_addr != INADDR_NONE)
8625 {
8626 /* Broadcast address is only reported by
8627 GetAdaptersAddresses, which is of limited
8628 availability. Generate it on our own. */
8629 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8630
8631 sa.sin_addr.s_addr = bcast_addr;
8632 sa.sin_port = 0;
8633 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8634 sizeof (struct sockaddr)),
8635 res);
8636
8637 /* IP address. */
8638 sa.sin_addr.s_addr = ip_addr;
8639 sa.sin_port = 0;
8640 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8641 sizeof (struct sockaddr)),
8642 res);
8643 }
8644 else
8645 res = Fcons (Qnil, Fcons (Qnil, res));
8646 }
8647 }
8648 /* GetAdaptersInfo is documented to not report loopback
8649 interfaces, so we generate one out of thin air. */
8650 if (!lo_count)
8651 {
8652 sa.sin_family = AF_INET;
8653 sa.sin_port = 0;
8654 if (NILP (ifname))
8655 {
8656 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8657 res = Fcons (Fcons (build_string ("lo"),
8658 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8659 sizeof (struct sockaddr))),
8660 res);
8661 }
8662 else if (strcmp (SSDATA (ifname), "lo") == 0)
8663 {
8664 res = Fcons (Fcons (intern ("running"),
8665 Fcons (intern ("loopback"),
8666 Fcons (intern ("up"), Qnil))), Qnil);
8667 /* 772 is what 3 different GNU/Linux systems report for
8668 the loopback interface. */
8669 res = Fcons (Fcons (make_number (772),
8670 Fmake_vector (make_number (6),
8671 make_number (0))),
8672 res);
8673 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8674 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8675 sizeof (struct sockaddr)),
8676 res);
8677 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8678 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8679 sizeof (struct sockaddr)),
8680 res);
8681 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8682 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8683 sizeof (struct sockaddr)),
8684 res);
8685 }
8686
8687 }
8688 }
8689
8690 done:
8691 xfree (ainfo);
8692 return res;
8693 }
8694
8695 Lisp_Object
8696 network_interface_list (void)
8697 {
8698 return network_interface_get_info (Qnil);
8699 }
8700
8701 Lisp_Object
8702 network_interface_info (Lisp_Object ifname)
8703 {
8704 CHECK_STRING (ifname);
8705 return network_interface_get_info (ifname);
8706 }
8707
8708 \f
8709 /* The Windows CRT functions are "optimized for speed", so they don't
8710 check for timezone and DST changes if they were last called less
8711 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8712 all Emacs features that repeatedly call time functions (e.g.,
8713 display-time) are in real danger of missing timezone and DST
8714 changes. Calling tzset before each localtime call fixes that. */
8715 struct tm *
8716 sys_localtime (const time_t *t)
8717 {
8718 tzset ();
8719 return localtime (t);
8720 }
8721
8722
8723 \f
8724 /* Try loading LIBRARY_ID from the file(s) specified in
8725 Vdynamic_library_alist. If the library is loaded successfully,
8726 return the handle of the DLL, and record the filename in the
8727 property :loaded-from of LIBRARY_ID. If the library could not be
8728 found, or when it was already loaded (because the handle is not
8729 recorded anywhere, and so is lost after use), return NULL.
8730
8731 We could also save the handle in :loaded-from, but currently
8732 there's no use case for it. */
8733 HMODULE
8734 w32_delayed_load (Lisp_Object library_id)
8735 {
8736 HMODULE dll_handle = NULL;
8737
8738 CHECK_SYMBOL (library_id);
8739
8740 if (CONSP (Vdynamic_library_alist)
8741 && NILP (Fassq (library_id, Vlibrary_cache)))
8742 {
8743 Lisp_Object found = Qnil;
8744 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
8745
8746 if (CONSP (dlls))
8747 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
8748 {
8749 Lisp_Object dll = XCAR (dlls);
8750 char name[MAX_UTF8_PATH];
8751 DWORD res = -1;
8752
8753 CHECK_STRING (dll);
8754 dll = ENCODE_FILE (dll);
8755 if (w32_unicode_filenames)
8756 {
8757 wchar_t name_w[MAX_PATH];
8758
8759 filename_to_utf16 (SSDATA (dll), name_w);
8760 dll_handle = LoadLibraryW (name_w);
8761 if (dll_handle)
8762 {
8763 res = GetModuleFileNameW (dll_handle, name_w,
8764 sizeof (name_w));
8765 if (res > 0)
8766 filename_from_utf16 (name_w, name);
8767 }
8768 }
8769 else
8770 {
8771 char name_a[MAX_PATH];
8772
8773 filename_to_ansi (SSDATA (dll), name_a);
8774 dll_handle = LoadLibraryA (name_a);
8775 if (dll_handle)
8776 {
8777 res = GetModuleFileNameA (dll_handle, name_a,
8778 sizeof (name_a));
8779 if (res > 0)
8780 filename_from_ansi (name_a, name);
8781 }
8782 }
8783 if (dll_handle)
8784 {
8785 ptrdiff_t len = strlen (name);
8786 found = Fcons (dll,
8787 (res > 0)
8788 /* Possibly truncated */
8789 ? make_specified_string (name, -1, len, 1)
8790 : Qnil);
8791 /* This prevents thread start and end notifications
8792 from being sent to the DLL, for every thread we
8793 start. We don't need those notifications because
8794 threads we create never use any of these DLLs, only
8795 the main thread uses them. This is supposed to
8796 speed up thread creation. */
8797 DisableThreadLibraryCalls (dll_handle);
8798 break;
8799 }
8800 }
8801
8802 Fput (library_id, QCloaded_from, found);
8803 }
8804
8805 return dll_handle;
8806 }
8807
8808 \f
8809 void
8810 check_windows_init_file (void)
8811 {
8812 /* A common indication that Emacs is not installed properly is when
8813 it cannot find the Windows installation file. If this file does
8814 not exist in the expected place, tell the user. */
8815
8816 if (!noninteractive && !inhibit_window_system
8817 /* Vload_path is not yet initialized when we are loading
8818 loadup.el. */
8819 && NILP (Vpurify_flag))
8820 {
8821 Lisp_Object init_file;
8822 int fd;
8823
8824 /* Implementation note: this function runs early during Emacs
8825 startup, before startup.el is run. So Vload_path is still in
8826 its initial unibyte form, but it holds UTF-8 encoded file
8827 names, since init_callproc was already called. So we do not
8828 need to ENCODE_FILE here, but we do need to convert the file
8829 names from UTF-8 to ANSI. */
8830 init_file = build_string ("term/w32-win");
8831 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil, 0);
8832 if (fd < 0)
8833 {
8834 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
8835 char *init_file_name = SDATA (init_file);
8836 char *load_path = SDATA (load_path_print);
8837 char *buffer = alloca (1024
8838 + strlen (init_file_name)
8839 + strlen (load_path));
8840 char *msg = buffer;
8841 int needed;
8842
8843 sprintf (buffer,
8844 "The Emacs Windows initialization file \"%s.el\" "
8845 "could not be found in your Emacs installation. "
8846 "Emacs checked the following directories for this file:\n"
8847 "\n%s\n\n"
8848 "When Emacs cannot find this file, it usually means that it "
8849 "was not installed properly, or its distribution file was "
8850 "not unpacked properly.\nSee the README.W32 file in the "
8851 "top-level Emacs directory for more information.",
8852 init_file_name, load_path);
8853 needed = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer,
8854 -1, NULL, 0);
8855 if (needed > 0)
8856 {
8857 wchar_t *msg_w = alloca ((needed + 1) * sizeof (wchar_t));
8858
8859 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, buffer, -1,
8860 msg_w, needed);
8861 needed = pWideCharToMultiByte (CP_ACP, 0, msg_w, -1,
8862 NULL, 0, NULL, NULL);
8863 if (needed > 0)
8864 {
8865 char *msg_a = alloca (needed + 1);
8866
8867 pWideCharToMultiByte (CP_ACP, 0, msg_w, -1, msg_a, needed,
8868 NULL, NULL);
8869 msg = msg_a;
8870 }
8871 }
8872 MessageBox (NULL,
8873 msg,
8874 "Emacs Abort Dialog",
8875 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
8876 /* Use the low-level system abort. */
8877 abort ();
8878 }
8879 else
8880 {
8881 _close (fd);
8882 }
8883 }
8884 }
8885
8886 void
8887 term_ntproc (int ignored)
8888 {
8889 (void)ignored;
8890
8891 term_timers ();
8892
8893 /* shutdown the socket interface if necessary */
8894 term_winsock ();
8895
8896 term_w32select ();
8897 }
8898
8899 void
8900 init_ntproc (int dumping)
8901 {
8902 sigset_t initial_mask = 0;
8903
8904 /* Initialize the socket interface now if available and requested by
8905 the user by defining PRELOAD_WINSOCK; otherwise loading will be
8906 delayed until open-network-stream is called (w32-has-winsock can
8907 also be used to dynamically load or reload winsock).
8908
8909 Conveniently, init_environment is called before us, so
8910 PRELOAD_WINSOCK can be set in the registry. */
8911
8912 /* Always initialize this correctly. */
8913 winsock_lib = NULL;
8914
8915 if (getenv ("PRELOAD_WINSOCK") != NULL)
8916 init_winsock (TRUE);
8917
8918 /* Initial preparation for subprocess support: replace our standard
8919 handles with non-inheritable versions. */
8920 {
8921 HANDLE parent;
8922 HANDLE stdin_save = INVALID_HANDLE_VALUE;
8923 HANDLE stdout_save = INVALID_HANDLE_VALUE;
8924 HANDLE stderr_save = INVALID_HANDLE_VALUE;
8925
8926 parent = GetCurrentProcess ();
8927
8928 /* ignore errors when duplicating and closing; typically the
8929 handles will be invalid when running as a gui program. */
8930 DuplicateHandle (parent,
8931 GetStdHandle (STD_INPUT_HANDLE),
8932 parent,
8933 &stdin_save,
8934 0,
8935 FALSE,
8936 DUPLICATE_SAME_ACCESS);
8937
8938 DuplicateHandle (parent,
8939 GetStdHandle (STD_OUTPUT_HANDLE),
8940 parent,
8941 &stdout_save,
8942 0,
8943 FALSE,
8944 DUPLICATE_SAME_ACCESS);
8945
8946 DuplicateHandle (parent,
8947 GetStdHandle (STD_ERROR_HANDLE),
8948 parent,
8949 &stderr_save,
8950 0,
8951 FALSE,
8952 DUPLICATE_SAME_ACCESS);
8953
8954 fclose (stdin);
8955 fclose (stdout);
8956 fclose (stderr);
8957
8958 if (stdin_save != INVALID_HANDLE_VALUE)
8959 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
8960 else
8961 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
8962 _fdopen (0, "r");
8963
8964 if (stdout_save != INVALID_HANDLE_VALUE)
8965 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
8966 else
8967 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8968 _fdopen (1, "w");
8969
8970 if (stderr_save != INVALID_HANDLE_VALUE)
8971 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
8972 else
8973 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8974 _fdopen (2, "w");
8975 }
8976
8977 /* unfortunately, atexit depends on implementation of malloc */
8978 /* atexit (term_ntproc); */
8979 if (!dumping)
8980 {
8981 /* Make sure we start with all signals unblocked. */
8982 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
8983 signal (SIGABRT, term_ntproc);
8984 }
8985 init_timers ();
8986
8987 /* determine which drives are fixed, for GetCachedVolumeInformation */
8988 {
8989 /* GetDriveType must have trailing backslash. */
8990 char drive[] = "A:\\";
8991
8992 /* Loop over all possible drive letters */
8993 while (*drive <= 'Z')
8994 {
8995 /* Record if this drive letter refers to a fixed drive. */
8996 fixed_drives[DRIVE_INDEX (*drive)] =
8997 (GetDriveType (drive) == DRIVE_FIXED);
8998
8999 (*drive)++;
9000 }
9001
9002 /* Reset the volume info cache. */
9003 volume_cache = NULL;
9004 }
9005 }
9006
9007 /*
9008 shutdown_handler ensures that buffers' autosave files are
9009 up to date when the user logs off, or the system shuts down.
9010 */
9011 static BOOL WINAPI
9012 shutdown_handler (DWORD type)
9013 {
9014 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9015 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
9016 || type == CTRL_LOGOFF_EVENT /* User logs off. */
9017 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
9018 {
9019 /* Shut down cleanly, making sure autosave files are up to date. */
9020 shut_down_emacs (0, Qnil);
9021 }
9022
9023 /* Allow other handlers to handle this signal. */
9024 return FALSE;
9025 }
9026
9027 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9028 NT, return a handle to GDI32.DLL. */
9029 HANDLE
9030 maybe_load_unicows_dll (void)
9031 {
9032 if (os_subtype == OS_9X)
9033 {
9034 HANDLE ret = LoadLibrary ("Unicows.dll");
9035 if (ret)
9036 {
9037 /* These two functions are present on Windows 9X as stubs
9038 that always fail. We need the real implementations from
9039 UNICOWS.DLL, so we must call these functions through
9040 pointers, and assign the correct addresses to these
9041 pointers at program startup (see emacs.c, which calls
9042 this function early on). */
9043 pMultiByteToWideChar = GetProcAddress (ret, "MultiByteToWideChar");
9044 pWideCharToMultiByte = GetProcAddress (ret, "WideCharToMultiByte");
9045 return ret;
9046 }
9047 else
9048 {
9049 int button;
9050
9051 button = MessageBox (NULL,
9052 "Emacs cannot load the UNICOWS.DLL library.\n"
9053 "This library is essential for using Emacs\n"
9054 "on this system. You need to install it.\n\n"
9055 "Emacs will exit when you click OK.",
9056 "Emacs cannot load UNICOWS.DLL",
9057 MB_ICONERROR | MB_TASKMODAL
9058 | MB_SETFOREGROUND | MB_OK);
9059 switch (button)
9060 {
9061 case IDOK:
9062 default:
9063 exit (1);
9064 }
9065 }
9066 }
9067 else
9068 {
9069 /* On NT family of Windows, these two functions are always
9070 linked in, so we just assign their addresses to the 2
9071 pointers; no need for the LoadLibrary dance. */
9072 pMultiByteToWideChar = MultiByteToWideChar;
9073 pWideCharToMultiByte = WideCharToMultiByte;
9074 return LoadLibrary ("Gdi32.dll");
9075 }
9076 }
9077
9078 /*
9079 globals_of_w32 is used to initialize those global variables that
9080 must always be initialized on startup even when the global variable
9081 initialized is non zero (see the function main in emacs.c).
9082 */
9083 void
9084 globals_of_w32 (void)
9085 {
9086 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
9087
9088 get_process_times_fn = (GetProcessTimes_Proc)
9089 GetProcAddress (kernel32, "GetProcessTimes");
9090
9091 DEFSYM (QCloaded_from, ":loaded-from");
9092
9093 g_b_init_is_windows_9x = 0;
9094 g_b_init_open_process_token = 0;
9095 g_b_init_get_token_information = 0;
9096 g_b_init_lookup_account_sid = 0;
9097 g_b_init_get_sid_sub_authority = 0;
9098 g_b_init_get_sid_sub_authority_count = 0;
9099 g_b_init_get_security_info = 0;
9100 g_b_init_get_file_security_w = 0;
9101 g_b_init_get_file_security_a = 0;
9102 g_b_init_get_security_descriptor_owner = 0;
9103 g_b_init_get_security_descriptor_group = 0;
9104 g_b_init_is_valid_sid = 0;
9105 g_b_init_create_toolhelp32_snapshot = 0;
9106 g_b_init_process32_first = 0;
9107 g_b_init_process32_next = 0;
9108 g_b_init_open_thread_token = 0;
9109 g_b_init_impersonate_self = 0;
9110 g_b_init_revert_to_self = 0;
9111 g_b_init_get_process_memory_info = 0;
9112 g_b_init_get_process_working_set_size = 0;
9113 g_b_init_global_memory_status = 0;
9114 g_b_init_global_memory_status_ex = 0;
9115 g_b_init_equal_sid = 0;
9116 g_b_init_copy_sid = 0;
9117 g_b_init_get_length_sid = 0;
9118 g_b_init_get_native_system_info = 0;
9119 g_b_init_get_system_times = 0;
9120 g_b_init_create_symbolic_link_w = 0;
9121 g_b_init_create_symbolic_link_a = 0;
9122 g_b_init_get_security_descriptor_dacl = 0;
9123 g_b_init_convert_sd_to_sddl = 0;
9124 g_b_init_convert_sddl_to_sd = 0;
9125 g_b_init_is_valid_security_descriptor = 0;
9126 g_b_init_set_file_security_w = 0;
9127 g_b_init_set_file_security_a = 0;
9128 g_b_init_set_named_security_info_w = 0;
9129 g_b_init_set_named_security_info_a = 0;
9130 g_b_init_get_adapters_info = 0;
9131 g_b_init_compare_string_w = 0;
9132 num_of_processors = 0;
9133 /* The following sets a handler for shutdown notifications for
9134 console apps. This actually applies to Emacs in both console and
9135 GUI modes, since we had to fool windows into thinking emacs is a
9136 console application to get console mode to work. */
9137 SetConsoleCtrlHandler (shutdown_handler, TRUE);
9138
9139 /* "None" is the default group name on standalone workstations. */
9140 strcpy (dflt_group_name, "None");
9141
9142 /* Reset, in case it has some value inherited from dump time. */
9143 w32_stat_get_owner_group = 0;
9144
9145 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9146 (a.k.a. "wide") APIs to invoke functions that accept file
9147 names. */
9148 if (is_windows_9x ())
9149 w32_unicode_filenames = 0;
9150 else
9151 w32_unicode_filenames = 1;
9152 }
9153
9154 /* For make-serial-process */
9155 int
9156 serial_open (Lisp_Object port_obj)
9157 {
9158 char *port = SSDATA (port_obj);
9159 HANDLE hnd;
9160 child_process *cp;
9161 int fd = -1;
9162
9163 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
9164 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
9165 if (hnd == INVALID_HANDLE_VALUE)
9166 error ("Could not open %s", port);
9167 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
9168 if (fd == -1)
9169 error ("Could not open %s", port);
9170
9171 cp = new_child ();
9172 if (!cp)
9173 error ("Could not create child process");
9174 cp->fd = fd;
9175 cp->status = STATUS_READ_ACKNOWLEDGED;
9176 fd_info[ fd ].hnd = hnd;
9177 fd_info[ fd ].flags |=
9178 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
9179 if (fd_info[ fd ].cp != NULL)
9180 {
9181 error ("fd_info[fd = %d] is already in use", fd);
9182 }
9183 fd_info[ fd ].cp = cp;
9184 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9185 if (cp->ovl_read.hEvent == NULL)
9186 error ("Could not create read event");
9187 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
9188 if (cp->ovl_write.hEvent == NULL)
9189 error ("Could not create write event");
9190
9191 return fd;
9192 }
9193
9194 /* For serial-process-configure */
9195 void
9196 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
9197 {
9198 Lisp_Object childp2 = Qnil;
9199 Lisp_Object tem = Qnil;
9200 HANDLE hnd;
9201 DCB dcb;
9202 COMMTIMEOUTS ct;
9203 char summary[4] = "???"; /* This usually becomes "8N1". */
9204
9205 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
9206 error ("Not a serial process");
9207 hnd = fd_info[ p->outfd ].hnd;
9208
9209 childp2 = Fcopy_sequence (p->childp);
9210
9211 /* Initialize timeouts for blocking read and blocking write. */
9212 if (!GetCommTimeouts (hnd, &ct))
9213 error ("GetCommTimeouts() failed");
9214 ct.ReadIntervalTimeout = 0;
9215 ct.ReadTotalTimeoutMultiplier = 0;
9216 ct.ReadTotalTimeoutConstant = 0;
9217 ct.WriteTotalTimeoutMultiplier = 0;
9218 ct.WriteTotalTimeoutConstant = 0;
9219 if (!SetCommTimeouts (hnd, &ct))
9220 error ("SetCommTimeouts() failed");
9221 /* Read port attributes and prepare default configuration. */
9222 memset (&dcb, 0, sizeof (dcb));
9223 dcb.DCBlength = sizeof (DCB);
9224 if (!GetCommState (hnd, &dcb))
9225 error ("GetCommState() failed");
9226 dcb.fBinary = TRUE;
9227 dcb.fNull = FALSE;
9228 dcb.fAbortOnError = FALSE;
9229 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9230 dcb.ErrorChar = 0;
9231 dcb.EofChar = 0;
9232 dcb.EvtChar = 0;
9233
9234 /* Configure speed. */
9235 if (!NILP (Fplist_member (contact, QCspeed)))
9236 tem = Fplist_get (contact, QCspeed);
9237 else
9238 tem = Fplist_get (p->childp, QCspeed);
9239 CHECK_NUMBER (tem);
9240 dcb.BaudRate = XINT (tem);
9241 childp2 = Fplist_put (childp2, QCspeed, tem);
9242
9243 /* Configure bytesize. */
9244 if (!NILP (Fplist_member (contact, QCbytesize)))
9245 tem = Fplist_get (contact, QCbytesize);
9246 else
9247 tem = Fplist_get (p->childp, QCbytesize);
9248 if (NILP (tem))
9249 tem = make_number (8);
9250 CHECK_NUMBER (tem);
9251 if (XINT (tem) != 7 && XINT (tem) != 8)
9252 error (":bytesize must be nil (8), 7, or 8");
9253 dcb.ByteSize = XINT (tem);
9254 summary[0] = XINT (tem) + '0';
9255 childp2 = Fplist_put (childp2, QCbytesize, tem);
9256
9257 /* Configure parity. */
9258 if (!NILP (Fplist_member (contact, QCparity)))
9259 tem = Fplist_get (contact, QCparity);
9260 else
9261 tem = Fplist_get (p->childp, QCparity);
9262 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
9263 error (":parity must be nil (no parity), `even', or `odd'");
9264 dcb.fParity = FALSE;
9265 dcb.Parity = NOPARITY;
9266 dcb.fErrorChar = FALSE;
9267 if (NILP (tem))
9268 {
9269 summary[1] = 'N';
9270 }
9271 else if (EQ (tem, Qeven))
9272 {
9273 summary[1] = 'E';
9274 dcb.fParity = TRUE;
9275 dcb.Parity = EVENPARITY;
9276 dcb.fErrorChar = TRUE;
9277 }
9278 else if (EQ (tem, Qodd))
9279 {
9280 summary[1] = 'O';
9281 dcb.fParity = TRUE;
9282 dcb.Parity = ODDPARITY;
9283 dcb.fErrorChar = TRUE;
9284 }
9285 childp2 = Fplist_put (childp2, QCparity, tem);
9286
9287 /* Configure stopbits. */
9288 if (!NILP (Fplist_member (contact, QCstopbits)))
9289 tem = Fplist_get (contact, QCstopbits);
9290 else
9291 tem = Fplist_get (p->childp, QCstopbits);
9292 if (NILP (tem))
9293 tem = make_number (1);
9294 CHECK_NUMBER (tem);
9295 if (XINT (tem) != 1 && XINT (tem) != 2)
9296 error (":stopbits must be nil (1 stopbit), 1, or 2");
9297 summary[2] = XINT (tem) + '0';
9298 if (XINT (tem) == 1)
9299 dcb.StopBits = ONESTOPBIT;
9300 else if (XINT (tem) == 2)
9301 dcb.StopBits = TWOSTOPBITS;
9302 childp2 = Fplist_put (childp2, QCstopbits, tem);
9303
9304 /* Configure flowcontrol. */
9305 if (!NILP (Fplist_member (contact, QCflowcontrol)))
9306 tem = Fplist_get (contact, QCflowcontrol);
9307 else
9308 tem = Fplist_get (p->childp, QCflowcontrol);
9309 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
9310 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9311 dcb.fOutxCtsFlow = FALSE;
9312 dcb.fOutxDsrFlow = FALSE;
9313 dcb.fDtrControl = DTR_CONTROL_DISABLE;
9314 dcb.fDsrSensitivity = FALSE;
9315 dcb.fTXContinueOnXoff = FALSE;
9316 dcb.fOutX = FALSE;
9317 dcb.fInX = FALSE;
9318 dcb.fRtsControl = RTS_CONTROL_DISABLE;
9319 dcb.XonChar = 17; /* Control-Q */
9320 dcb.XoffChar = 19; /* Control-S */
9321 if (NILP (tem))
9322 {
9323 /* Already configured. */
9324 }
9325 else if (EQ (tem, Qhw))
9326 {
9327 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
9328 dcb.fOutxCtsFlow = TRUE;
9329 }
9330 else if (EQ (tem, Qsw))
9331 {
9332 dcb.fOutX = TRUE;
9333 dcb.fInX = TRUE;
9334 }
9335 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
9336
9337 /* Activate configuration. */
9338 if (!SetCommState (hnd, &dcb))
9339 error ("SetCommState() failed");
9340
9341 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
9342 pset_childp (p, childp2);
9343 }
9344
9345 #ifdef HAVE_GNUTLS
9346
9347 ssize_t
9348 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
9349 {
9350 int n, err;
9351 struct Lisp_Process *process = (struct Lisp_Process *)p;
9352 int fd = process->infd;
9353
9354 n = sys_read (fd, (char*)buf, sz);
9355
9356 if (n >= 0)
9357 return n;
9358
9359 err = errno;
9360
9361 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9362 if (err == EWOULDBLOCK)
9363 err = EAGAIN;
9364
9365 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
9366
9367 return -1;
9368 }
9369
9370 ssize_t
9371 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
9372 {
9373 struct Lisp_Process *process = (struct Lisp_Process *)p;
9374 int fd = process->outfd;
9375 ssize_t n = sys_write (fd, buf, sz);
9376
9377 /* 0 or more bytes written means everything went fine. */
9378 if (n >= 0)
9379 return n;
9380
9381 /* Negative bytes written means we got an error in errno.
9382 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9383 emacs_gnutls_transport_set_errno (process->gnutls_state,
9384 errno == EWOULDBLOCK ? EAGAIN : errno);
9385
9386 return -1;
9387 }
9388 #endif /* HAVE_GNUTLS */
9389
9390 /* end of w32.c */