Merge from emacs-24; up to 2012-11-17T22:12:47Z!eggert@cs.ucla.edu
[bpt/emacs.git] / src / w32.c
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2012 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19 /*
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
21 */
22 #include <stddef.h> /* for offsetof */
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <float.h> /* for DBL_EPSILON */
26 #include <io.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <sys/file.h>
32 #include <sys/time.h>
33 #include <sys/utime.h>
34 #include <math.h>
35 #include <time.h>
36
37 /* must include CRT headers *before* config.h */
38
39 #include <config.h>
40 #include <mbstring.h> /* for _mbspbrk */
41
42 #undef access
43 #undef chdir
44 #undef chmod
45 #undef creat
46 #undef ctime
47 #undef fopen
48 #undef link
49 #undef mkdir
50 #undef mktemp
51 #undef open
52 #undef rename
53 #undef rmdir
54 #undef unlink
55
56 #undef close
57 #undef dup
58 #undef dup2
59 #undef pipe
60 #undef read
61 #undef write
62
63 #undef strerror
64
65 #undef localtime
66
67 #include "lisp.h"
68
69 #include <pwd.h>
70 #include <grp.h>
71
72 #ifdef __GNUC__
73 #define _ANONYMOUS_UNION
74 #define _ANONYMOUS_STRUCT
75 #endif
76 #include <windows.h>
77 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
78 use a different name to avoid compilation problems. */
79 typedef struct _MEMORY_STATUS_EX {
80 DWORD dwLength;
81 DWORD dwMemoryLoad;
82 DWORDLONG ullTotalPhys;
83 DWORDLONG ullAvailPhys;
84 DWORDLONG ullTotalPageFile;
85 DWORDLONG ullAvailPageFile;
86 DWORDLONG ullTotalVirtual;
87 DWORDLONG ullAvailVirtual;
88 DWORDLONG ullAvailExtendedVirtual;
89 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
90
91 #include <lmcons.h>
92 #include <shlobj.h>
93
94 #include <tlhelp32.h>
95 #include <psapi.h>
96 #ifndef _MSC_VER
97 #include <w32api.h>
98 #endif
99 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100 /* This either is not in psapi.h or guarded by higher value of
101 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
102 defines it in psapi.h */
103 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
104 DWORD cb;
105 DWORD PageFaultCount;
106 DWORD PeakWorkingSetSize;
107 DWORD WorkingSetSize;
108 DWORD QuotaPeakPagedPoolUsage;
109 DWORD QuotaPagedPoolUsage;
110 DWORD QuotaPeakNonPagedPoolUsage;
111 DWORD QuotaNonPagedPoolUsage;
112 DWORD PagefileUsage;
113 DWORD PeakPagefileUsage;
114 DWORD PrivateUsage;
115 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
116 #endif
117
118 #include <winioctl.h>
119 #include <aclapi.h>
120
121 #ifdef _MSC_VER
122 /* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
123 associated macros, except on ntifs.h, which cannot be included
124 because it triggers conflicts with other Windows API headers. So
125 we define it here by hand. */
126
127 typedef struct _REPARSE_DATA_BUFFER {
128 ULONG ReparseTag;
129 USHORT ReparseDataLength;
130 USHORT Reserved;
131 union {
132 struct {
133 USHORT SubstituteNameOffset;
134 USHORT SubstituteNameLength;
135 USHORT PrintNameOffset;
136 USHORT PrintNameLength;
137 ULONG Flags;
138 WCHAR PathBuffer[1];
139 } SymbolicLinkReparseBuffer;
140 struct {
141 USHORT SubstituteNameOffset;
142 USHORT SubstituteNameLength;
143 USHORT PrintNameOffset;
144 USHORT PrintNameLength;
145 WCHAR PathBuffer[1];
146 } MountPointReparseBuffer;
147 struct {
148 UCHAR DataBuffer[1];
149 } GenericReparseBuffer;
150 } DUMMYUNIONNAME;
151 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
152
153 #define FILE_DEVICE_FILE_SYSTEM 9
154 #define METHOD_BUFFERED 0
155 #define FILE_ANY_ACCESS 0x00000000
156 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
157 #define FSCTL_GET_REPARSE_POINT \
158 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
159 #endif
160
161 /* TCP connection support. */
162 #include <sys/socket.h>
163 #undef socket
164 #undef bind
165 #undef connect
166 #undef htons
167 #undef ntohs
168 #undef inet_addr
169 #undef gethostname
170 #undef gethostbyname
171 #undef getservbyname
172 #undef getpeername
173 #undef shutdown
174 #undef setsockopt
175 #undef listen
176 #undef getsockname
177 #undef accept
178 #undef recvfrom
179 #undef sendto
180
181 #include "w32.h"
182 #include "ndir.h"
183 #include "w32common.h"
184 #include "w32heap.h"
185 #include "w32select.h"
186 #include "systime.h"
187 #include "dispextern.h" /* for xstrcasecmp */
188 #include "coding.h" /* for Vlocale_coding_system */
189
190 #include "careadlinkat.h"
191 #include "allocator.h"
192
193 /* For serial_configure and serial_open. */
194 #include "process.h"
195
196 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
197 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
198
199 Lisp_Object QCloaded_from;
200
201 void globals_of_w32 (void);
202 static DWORD get_rid (PSID);
203 static int is_symlink (const char *);
204 static char * chase_symlinks (const char *);
205 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
206 static int restore_privilege (TOKEN_PRIVILEGES *);
207 static BOOL WINAPI revert_to_self (void);
208
209 extern int sys_access (const char *, int);
210 extern void *e_malloc (size_t);
211 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
212 EMACS_TIME *, void *);
213
214
215 \f
216 /* Initialization states.
217
218 WARNING: If you add any more such variables for additional APIs,
219 you MUST add initialization for them to globals_of_w32
220 below. This is because these variables might get set
221 to non-NULL values during dumping, but the dumped Emacs
222 cannot reuse those values, because it could be run on a
223 different version of the OS, where API addresses are
224 different. */
225 static BOOL g_b_init_is_windows_9x;
226 static BOOL g_b_init_open_process_token;
227 static BOOL g_b_init_get_token_information;
228 static BOOL g_b_init_lookup_account_sid;
229 static BOOL g_b_init_get_sid_sub_authority;
230 static BOOL g_b_init_get_sid_sub_authority_count;
231 static BOOL g_b_init_get_security_info;
232 static BOOL g_b_init_get_file_security;
233 static BOOL g_b_init_get_security_descriptor_owner;
234 static BOOL g_b_init_get_security_descriptor_group;
235 static BOOL g_b_init_is_valid_sid;
236 static BOOL g_b_init_create_toolhelp32_snapshot;
237 static BOOL g_b_init_process32_first;
238 static BOOL g_b_init_process32_next;
239 static BOOL g_b_init_open_thread_token;
240 static BOOL g_b_init_impersonate_self;
241 static BOOL g_b_init_revert_to_self;
242 static BOOL g_b_init_get_process_memory_info;
243 static BOOL g_b_init_get_process_working_set_size;
244 static BOOL g_b_init_global_memory_status;
245 static BOOL g_b_init_global_memory_status_ex;
246 static BOOL g_b_init_get_length_sid;
247 static BOOL g_b_init_equal_sid;
248 static BOOL g_b_init_copy_sid;
249 static BOOL g_b_init_get_native_system_info;
250 static BOOL g_b_init_get_system_times;
251 static BOOL g_b_init_create_symbolic_link;
252
253 /*
254 BEGIN: Wrapper functions around OpenProcessToken
255 and other functions in advapi32.dll that are only
256 supported in Windows NT / 2k / XP
257 */
258 /* ** Function pointer typedefs ** */
259 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
260 HANDLE ProcessHandle,
261 DWORD DesiredAccess,
262 PHANDLE TokenHandle);
263 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
264 HANDLE TokenHandle,
265 TOKEN_INFORMATION_CLASS TokenInformationClass,
266 LPVOID TokenInformation,
267 DWORD TokenInformationLength,
268 PDWORD ReturnLength);
269 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
270 HANDLE process_handle,
271 LPFILETIME creation_time,
272 LPFILETIME exit_time,
273 LPFILETIME kernel_time,
274 LPFILETIME user_time);
275
276 GetProcessTimes_Proc get_process_times_fn = NULL;
277
278 #ifdef _UNICODE
279 const char * const LookupAccountSid_Name = "LookupAccountSidW";
280 const char * const GetFileSecurity_Name = "GetFileSecurityW";
281 #else
282 const char * const LookupAccountSid_Name = "LookupAccountSidA";
283 const char * const GetFileSecurity_Name = "GetFileSecurityA";
284 #endif
285 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
286 LPCTSTR lpSystemName,
287 PSID Sid,
288 LPTSTR Name,
289 LPDWORD cbName,
290 LPTSTR DomainName,
291 LPDWORD cbDomainName,
292 PSID_NAME_USE peUse);
293 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
294 PSID pSid,
295 DWORD n);
296 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
297 PSID pSid);
298 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
299 HANDLE handle,
300 SE_OBJECT_TYPE ObjectType,
301 SECURITY_INFORMATION SecurityInfo,
302 PSID *ppsidOwner,
303 PSID *ppsidGroup,
304 PACL *ppDacl,
305 PACL *ppSacl,
306 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
307 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
308 LPCTSTR lpFileName,
309 SECURITY_INFORMATION RequestedInformation,
310 PSECURITY_DESCRIPTOR pSecurityDescriptor,
311 DWORD nLength,
312 LPDWORD lpnLengthNeeded);
313 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
314 PSECURITY_DESCRIPTOR pSecurityDescriptor,
315 PSID *pOwner,
316 LPBOOL lpbOwnerDefaulted);
317 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
318 PSECURITY_DESCRIPTOR pSecurityDescriptor,
319 PSID *pGroup,
320 LPBOOL lpbGroupDefaulted);
321 typedef BOOL (WINAPI * IsValidSid_Proc) (
322 PSID sid);
323 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
324 DWORD dwFlags,
325 DWORD th32ProcessID);
326 typedef BOOL (WINAPI * Process32First_Proc) (
327 HANDLE hSnapshot,
328 LPPROCESSENTRY32 lppe);
329 typedef BOOL (WINAPI * Process32Next_Proc) (
330 HANDLE hSnapshot,
331 LPPROCESSENTRY32 lppe);
332 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
333 HANDLE ThreadHandle,
334 DWORD DesiredAccess,
335 BOOL OpenAsSelf,
336 PHANDLE TokenHandle);
337 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
338 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
339 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
340 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
341 HANDLE Process,
342 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
343 DWORD cb);
344 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
345 HANDLE hProcess,
346 DWORD * lpMinimumWorkingSetSize,
347 DWORD * lpMaximumWorkingSetSize);
348 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
349 LPMEMORYSTATUS lpBuffer);
350 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
351 LPMEMORY_STATUS_EX lpBuffer);
352 typedef BOOL (WINAPI * CopySid_Proc) (
353 DWORD nDestinationSidLength,
354 PSID pDestinationSid,
355 PSID pSourceSid);
356 typedef BOOL (WINAPI * EqualSid_Proc) (
357 PSID pSid1,
358 PSID pSid2);
359 typedef DWORD (WINAPI * GetLengthSid_Proc) (
360 PSID pSid);
361 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
362 LPSYSTEM_INFO lpSystemInfo);
363 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
364 LPFILETIME lpIdleTime,
365 LPFILETIME lpKernelTime,
366 LPFILETIME lpUserTime);
367 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
368 LPTSTR lpSymlinkFileName,
369 LPTSTR lpTargetFileName,
370 DWORD dwFlags);
371
372 /* ** A utility function ** */
373 static BOOL
374 is_windows_9x (void)
375 {
376 static BOOL s_b_ret = 0;
377 OSVERSIONINFO os_ver;
378 if (g_b_init_is_windows_9x == 0)
379 {
380 g_b_init_is_windows_9x = 1;
381 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
382 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
383 if (GetVersionEx (&os_ver))
384 {
385 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
386 }
387 }
388 return s_b_ret;
389 }
390
391 static Lisp_Object ltime (ULONGLONG);
392
393 /* Get total user and system times for get-internal-run-time.
394 Returns a list of integers if the times are provided by the OS
395 (NT derivatives), otherwise it returns the result of current-time. */
396 Lisp_Object
397 w32_get_internal_run_time (void)
398 {
399 if (get_process_times_fn)
400 {
401 FILETIME create, exit, kernel, user;
402 HANDLE proc = GetCurrentProcess ();
403 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
404 {
405 LARGE_INTEGER user_int, kernel_int, total;
406 user_int.LowPart = user.dwLowDateTime;
407 user_int.HighPart = user.dwHighDateTime;
408 kernel_int.LowPart = kernel.dwLowDateTime;
409 kernel_int.HighPart = kernel.dwHighDateTime;
410 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
411 return ltime (total.QuadPart);
412 }
413 }
414
415 return Fcurrent_time ();
416 }
417
418 /* ** The wrapper functions ** */
419
420 static BOOL WINAPI
421 open_process_token (HANDLE ProcessHandle,
422 DWORD DesiredAccess,
423 PHANDLE TokenHandle)
424 {
425 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
426 HMODULE hm_advapi32 = NULL;
427 if (is_windows_9x () == TRUE)
428 {
429 return FALSE;
430 }
431 if (g_b_init_open_process_token == 0)
432 {
433 g_b_init_open_process_token = 1;
434 hm_advapi32 = LoadLibrary ("Advapi32.dll");
435 s_pfn_Open_Process_Token =
436 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
437 }
438 if (s_pfn_Open_Process_Token == NULL)
439 {
440 return FALSE;
441 }
442 return (
443 s_pfn_Open_Process_Token (
444 ProcessHandle,
445 DesiredAccess,
446 TokenHandle)
447 );
448 }
449
450 static BOOL WINAPI
451 get_token_information (HANDLE TokenHandle,
452 TOKEN_INFORMATION_CLASS TokenInformationClass,
453 LPVOID TokenInformation,
454 DWORD TokenInformationLength,
455 PDWORD ReturnLength)
456 {
457 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
458 HMODULE hm_advapi32 = NULL;
459 if (is_windows_9x () == TRUE)
460 {
461 return FALSE;
462 }
463 if (g_b_init_get_token_information == 0)
464 {
465 g_b_init_get_token_information = 1;
466 hm_advapi32 = LoadLibrary ("Advapi32.dll");
467 s_pfn_Get_Token_Information =
468 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
469 }
470 if (s_pfn_Get_Token_Information == NULL)
471 {
472 return FALSE;
473 }
474 return (
475 s_pfn_Get_Token_Information (
476 TokenHandle,
477 TokenInformationClass,
478 TokenInformation,
479 TokenInformationLength,
480 ReturnLength)
481 );
482 }
483
484 static BOOL WINAPI
485 lookup_account_sid (LPCTSTR lpSystemName,
486 PSID Sid,
487 LPTSTR Name,
488 LPDWORD cbName,
489 LPTSTR DomainName,
490 LPDWORD cbDomainName,
491 PSID_NAME_USE peUse)
492 {
493 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
494 HMODULE hm_advapi32 = NULL;
495 if (is_windows_9x () == TRUE)
496 {
497 return FALSE;
498 }
499 if (g_b_init_lookup_account_sid == 0)
500 {
501 g_b_init_lookup_account_sid = 1;
502 hm_advapi32 = LoadLibrary ("Advapi32.dll");
503 s_pfn_Lookup_Account_Sid =
504 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
505 }
506 if (s_pfn_Lookup_Account_Sid == NULL)
507 {
508 return FALSE;
509 }
510 return (
511 s_pfn_Lookup_Account_Sid (
512 lpSystemName,
513 Sid,
514 Name,
515 cbName,
516 DomainName,
517 cbDomainName,
518 peUse)
519 );
520 }
521
522 static PDWORD WINAPI
523 get_sid_sub_authority (PSID pSid, DWORD n)
524 {
525 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
526 static DWORD zero = 0U;
527 HMODULE hm_advapi32 = NULL;
528 if (is_windows_9x () == TRUE)
529 {
530 return &zero;
531 }
532 if (g_b_init_get_sid_sub_authority == 0)
533 {
534 g_b_init_get_sid_sub_authority = 1;
535 hm_advapi32 = LoadLibrary ("Advapi32.dll");
536 s_pfn_Get_Sid_Sub_Authority =
537 (GetSidSubAuthority_Proc) GetProcAddress (
538 hm_advapi32, "GetSidSubAuthority");
539 }
540 if (s_pfn_Get_Sid_Sub_Authority == NULL)
541 {
542 return &zero;
543 }
544 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
545 }
546
547 static PUCHAR WINAPI
548 get_sid_sub_authority_count (PSID pSid)
549 {
550 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
551 static UCHAR zero = 0U;
552 HMODULE hm_advapi32 = NULL;
553 if (is_windows_9x () == TRUE)
554 {
555 return &zero;
556 }
557 if (g_b_init_get_sid_sub_authority_count == 0)
558 {
559 g_b_init_get_sid_sub_authority_count = 1;
560 hm_advapi32 = LoadLibrary ("Advapi32.dll");
561 s_pfn_Get_Sid_Sub_Authority_Count =
562 (GetSidSubAuthorityCount_Proc) GetProcAddress (
563 hm_advapi32, "GetSidSubAuthorityCount");
564 }
565 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
566 {
567 return &zero;
568 }
569 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
570 }
571
572 static DWORD WINAPI
573 get_security_info (HANDLE handle,
574 SE_OBJECT_TYPE ObjectType,
575 SECURITY_INFORMATION SecurityInfo,
576 PSID *ppsidOwner,
577 PSID *ppsidGroup,
578 PACL *ppDacl,
579 PACL *ppSacl,
580 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
581 {
582 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
583 HMODULE hm_advapi32 = NULL;
584 if (is_windows_9x () == TRUE)
585 {
586 return FALSE;
587 }
588 if (g_b_init_get_security_info == 0)
589 {
590 g_b_init_get_security_info = 1;
591 hm_advapi32 = LoadLibrary ("Advapi32.dll");
592 s_pfn_Get_Security_Info =
593 (GetSecurityInfo_Proc) GetProcAddress (
594 hm_advapi32, "GetSecurityInfo");
595 }
596 if (s_pfn_Get_Security_Info == NULL)
597 {
598 return FALSE;
599 }
600 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
601 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
602 ppSecurityDescriptor));
603 }
604
605 static BOOL WINAPI
606 get_file_security (LPCTSTR lpFileName,
607 SECURITY_INFORMATION RequestedInformation,
608 PSECURITY_DESCRIPTOR pSecurityDescriptor,
609 DWORD nLength,
610 LPDWORD lpnLengthNeeded)
611 {
612 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
613 HMODULE hm_advapi32 = NULL;
614 if (is_windows_9x () == TRUE)
615 {
616 return FALSE;
617 }
618 if (g_b_init_get_file_security == 0)
619 {
620 g_b_init_get_file_security = 1;
621 hm_advapi32 = LoadLibrary ("Advapi32.dll");
622 s_pfn_Get_File_Security =
623 (GetFileSecurity_Proc) GetProcAddress (
624 hm_advapi32, GetFileSecurity_Name);
625 }
626 if (s_pfn_Get_File_Security == NULL)
627 {
628 return FALSE;
629 }
630 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
631 pSecurityDescriptor, nLength,
632 lpnLengthNeeded));
633 }
634
635 static BOOL WINAPI
636 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
637 PSID *pOwner,
638 LPBOOL lpbOwnerDefaulted)
639 {
640 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
641 HMODULE hm_advapi32 = NULL;
642 if (is_windows_9x () == TRUE)
643 {
644 return FALSE;
645 }
646 if (g_b_init_get_security_descriptor_owner == 0)
647 {
648 g_b_init_get_security_descriptor_owner = 1;
649 hm_advapi32 = LoadLibrary ("Advapi32.dll");
650 s_pfn_Get_Security_Descriptor_Owner =
651 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
652 hm_advapi32, "GetSecurityDescriptorOwner");
653 }
654 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
655 {
656 return FALSE;
657 }
658 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
659 lpbOwnerDefaulted));
660 }
661
662 static BOOL WINAPI
663 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
664 PSID *pGroup,
665 LPBOOL lpbGroupDefaulted)
666 {
667 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
668 HMODULE hm_advapi32 = NULL;
669 if (is_windows_9x () == TRUE)
670 {
671 return FALSE;
672 }
673 if (g_b_init_get_security_descriptor_group == 0)
674 {
675 g_b_init_get_security_descriptor_group = 1;
676 hm_advapi32 = LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_Security_Descriptor_Group =
678 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
679 hm_advapi32, "GetSecurityDescriptorGroup");
680 }
681 if (s_pfn_Get_Security_Descriptor_Group == NULL)
682 {
683 return FALSE;
684 }
685 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
686 lpbGroupDefaulted));
687 }
688
689 static BOOL WINAPI
690 is_valid_sid (PSID sid)
691 {
692 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
693 HMODULE hm_advapi32 = NULL;
694 if (is_windows_9x () == TRUE)
695 {
696 return FALSE;
697 }
698 if (g_b_init_is_valid_sid == 0)
699 {
700 g_b_init_is_valid_sid = 1;
701 hm_advapi32 = LoadLibrary ("Advapi32.dll");
702 s_pfn_Is_Valid_Sid =
703 (IsValidSid_Proc) GetProcAddress (
704 hm_advapi32, "IsValidSid");
705 }
706 if (s_pfn_Is_Valid_Sid == NULL)
707 {
708 return FALSE;
709 }
710 return (s_pfn_Is_Valid_Sid (sid));
711 }
712
713 static BOOL WINAPI
714 equal_sid (PSID sid1, PSID sid2)
715 {
716 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
717 HMODULE hm_advapi32 = NULL;
718 if (is_windows_9x () == TRUE)
719 {
720 return FALSE;
721 }
722 if (g_b_init_equal_sid == 0)
723 {
724 g_b_init_equal_sid = 1;
725 hm_advapi32 = LoadLibrary ("Advapi32.dll");
726 s_pfn_Equal_Sid =
727 (EqualSid_Proc) GetProcAddress (
728 hm_advapi32, "EqualSid");
729 }
730 if (s_pfn_Equal_Sid == NULL)
731 {
732 return FALSE;
733 }
734 return (s_pfn_Equal_Sid (sid1, sid2));
735 }
736
737 static DWORD WINAPI
738 get_length_sid (PSID sid)
739 {
740 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
741 HMODULE hm_advapi32 = NULL;
742 if (is_windows_9x () == TRUE)
743 {
744 return 0;
745 }
746 if (g_b_init_get_length_sid == 0)
747 {
748 g_b_init_get_length_sid = 1;
749 hm_advapi32 = LoadLibrary ("Advapi32.dll");
750 s_pfn_Get_Length_Sid =
751 (GetLengthSid_Proc) GetProcAddress (
752 hm_advapi32, "GetLengthSid");
753 }
754 if (s_pfn_Get_Length_Sid == NULL)
755 {
756 return 0;
757 }
758 return (s_pfn_Get_Length_Sid (sid));
759 }
760
761 static BOOL WINAPI
762 copy_sid (DWORD destlen, PSID dest, PSID src)
763 {
764 static CopySid_Proc s_pfn_Copy_Sid = NULL;
765 HMODULE hm_advapi32 = NULL;
766 if (is_windows_9x () == TRUE)
767 {
768 return FALSE;
769 }
770 if (g_b_init_copy_sid == 0)
771 {
772 g_b_init_copy_sid = 1;
773 hm_advapi32 = LoadLibrary ("Advapi32.dll");
774 s_pfn_Copy_Sid =
775 (CopySid_Proc) GetProcAddress (
776 hm_advapi32, "CopySid");
777 }
778 if (s_pfn_Copy_Sid == NULL)
779 {
780 return FALSE;
781 }
782 return (s_pfn_Copy_Sid (destlen, dest, src));
783 }
784
785 /*
786 END: Wrapper functions around OpenProcessToken
787 and other functions in advapi32.dll that are only
788 supported in Windows NT / 2k / XP
789 */
790
791 static void WINAPI
792 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
793 {
794 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
795 if (is_windows_9x () != TRUE)
796 {
797 if (g_b_init_get_native_system_info == 0)
798 {
799 g_b_init_get_native_system_info = 1;
800 s_pfn_Get_Native_System_Info =
801 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
802 "GetNativeSystemInfo");
803 }
804 if (s_pfn_Get_Native_System_Info != NULL)
805 s_pfn_Get_Native_System_Info (lpSystemInfo);
806 }
807 else
808 lpSystemInfo->dwNumberOfProcessors = -1;
809 }
810
811 static BOOL WINAPI
812 get_system_times (LPFILETIME lpIdleTime,
813 LPFILETIME lpKernelTime,
814 LPFILETIME lpUserTime)
815 {
816 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
817 if (is_windows_9x () == TRUE)
818 {
819 return FALSE;
820 }
821 if (g_b_init_get_system_times == 0)
822 {
823 g_b_init_get_system_times = 1;
824 s_pfn_Get_System_times =
825 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
826 "GetSystemTimes");
827 }
828 if (s_pfn_Get_System_times == NULL)
829 return FALSE;
830 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
831 }
832
833 static BOOLEAN WINAPI
834 create_symbolic_link (LPTSTR lpSymlinkFilename,
835 LPTSTR lpTargetFileName,
836 DWORD dwFlags)
837 {
838 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
839 BOOLEAN retval;
840
841 if (is_windows_9x () == TRUE)
842 {
843 errno = ENOSYS;
844 return 0;
845 }
846 if (g_b_init_create_symbolic_link == 0)
847 {
848 g_b_init_create_symbolic_link = 1;
849 #ifdef _UNICODE
850 s_pfn_Create_Symbolic_Link =
851 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
852 "CreateSymbolicLinkW");
853 #else
854 s_pfn_Create_Symbolic_Link =
855 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
856 "CreateSymbolicLinkA");
857 #endif
858 }
859 if (s_pfn_Create_Symbolic_Link == NULL)
860 {
861 errno = ENOSYS;
862 return 0;
863 }
864
865 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
866 dwFlags);
867 /* If we were denied creation of the symlink, try again after
868 enabling the SeCreateSymbolicLinkPrivilege for our process. */
869 if (!retval)
870 {
871 TOKEN_PRIVILEGES priv_current;
872
873 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
874 {
875 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
876 dwFlags);
877 restore_privilege (&priv_current);
878 revert_to_self ();
879 }
880 }
881 return retval;
882 }
883 \f
884
885 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
886 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
887
888 This is called from alloc.c:valid_pointer_p. */
889 int
890 w32_valid_pointer_p (void *p, int size)
891 {
892 SIZE_T done;
893 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
894
895 if (h)
896 {
897 unsigned char *buf = alloca (size);
898 int retval = ReadProcessMemory (h, p, buf, size, &done);
899
900 CloseHandle (h);
901 return retval;
902 }
903 else
904 return -1;
905 }
906
907 static char startup_dir[MAXPATHLEN];
908
909 /* Get the current working directory. */
910 char *
911 getwd (char *dir)
912 {
913 #if 0
914 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
915 return dir;
916 return NULL;
917 #else
918 /* Emacs doesn't actually change directory itself, it stays in the
919 same directory where it was started. */
920 strcpy (dir, startup_dir);
921 return dir;
922 #endif
923 }
924
925 /* Emulate getloadavg. */
926
927 struct load_sample {
928 time_t sample_time;
929 ULONGLONG idle;
930 ULONGLONG kernel;
931 ULONGLONG user;
932 };
933
934 /* Number of processors on this machine. */
935 static unsigned num_of_processors;
936
937 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
938 static struct load_sample samples[16*60];
939 static int first_idx = -1, last_idx = -1;
940 static int max_idx = sizeof (samples) / sizeof (samples[0]);
941
942 static int
943 buf_next (int from)
944 {
945 int next_idx = from + 1;
946
947 if (next_idx >= max_idx)
948 next_idx = 0;
949
950 return next_idx;
951 }
952
953 static int
954 buf_prev (int from)
955 {
956 int prev_idx = from - 1;
957
958 if (prev_idx < 0)
959 prev_idx = max_idx - 1;
960
961 return prev_idx;
962 }
963
964 static void
965 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
966 {
967 SYSTEM_INFO sysinfo;
968 FILETIME ft_idle, ft_user, ft_kernel;
969
970 /* Initialize the number of processors on this machine. */
971 if (num_of_processors <= 0)
972 {
973 get_native_system_info (&sysinfo);
974 num_of_processors = sysinfo.dwNumberOfProcessors;
975 if (num_of_processors <= 0)
976 {
977 GetSystemInfo (&sysinfo);
978 num_of_processors = sysinfo.dwNumberOfProcessors;
979 }
980 if (num_of_processors <= 0)
981 num_of_processors = 1;
982 }
983
984 /* TODO: Take into account threads that are ready to run, by
985 sampling the "\System\Processor Queue Length" performance
986 counter. The code below accounts only for threads that are
987 actually running. */
988
989 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
990 {
991 ULARGE_INTEGER uidle, ukernel, uuser;
992
993 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
994 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
995 memcpy (&uuser, &ft_user, sizeof (ft_user));
996 *idle = uidle.QuadPart;
997 *kernel = ukernel.QuadPart;
998 *user = uuser.QuadPart;
999 }
1000 else
1001 {
1002 *idle = 0;
1003 *kernel = 0;
1004 *user = 0;
1005 }
1006 }
1007
1008 /* Produce the load average for a given time interval, using the
1009 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1010 1-minute, 5-minute, or 15-minute average, respectively. */
1011 static double
1012 getavg (int which)
1013 {
1014 double retval = -1.0;
1015 double tdiff;
1016 int idx;
1017 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1018 time_t now = samples[last_idx].sample_time;
1019
1020 if (first_idx != last_idx)
1021 {
1022 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1023 {
1024 tdiff = difftime (now, samples[idx].sample_time);
1025 if (tdiff >= span - 2*DBL_EPSILON*now)
1026 {
1027 long double sys =
1028 samples[last_idx].kernel + samples[last_idx].user
1029 - (samples[idx].kernel + samples[idx].user);
1030 long double idl = samples[last_idx].idle - samples[idx].idle;
1031
1032 retval = (1.0 - idl / sys) * num_of_processors;
1033 break;
1034 }
1035 if (idx == first_idx)
1036 break;
1037 }
1038 }
1039
1040 return retval;
1041 }
1042
1043 int
1044 getloadavg (double loadavg[], int nelem)
1045 {
1046 int elem;
1047 ULONGLONG idle, kernel, user;
1048 time_t now = time (NULL);
1049
1050 /* Store another sample. We ignore samples that are less than 1 sec
1051 apart. */
1052 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1053 {
1054 sample_system_load (&idle, &kernel, &user);
1055 last_idx = buf_next (last_idx);
1056 samples[last_idx].sample_time = now;
1057 samples[last_idx].idle = idle;
1058 samples[last_idx].kernel = kernel;
1059 samples[last_idx].user = user;
1060 /* If the buffer has more that 15 min worth of samples, discard
1061 the old ones. */
1062 if (first_idx == -1)
1063 first_idx = last_idx;
1064 while (first_idx != last_idx
1065 && (difftime (now, samples[first_idx].sample_time)
1066 >= 15.0*60 + 2*DBL_EPSILON*now))
1067 first_idx = buf_next (first_idx);
1068 }
1069
1070 for (elem = 0; elem < nelem; elem++)
1071 {
1072 double avg = getavg (elem);
1073
1074 if (avg < 0)
1075 break;
1076 loadavg[elem] = avg;
1077 }
1078
1079 return elem;
1080 }
1081
1082 /* Emulate getpwuid, getpwnam and others. */
1083
1084 #define PASSWD_FIELD_SIZE 256
1085
1086 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1087 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1088 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1089 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1090 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1091
1092 static struct passwd dflt_passwd =
1093 {
1094 dflt_passwd_name,
1095 dflt_passwd_passwd,
1096 0,
1097 0,
1098 0,
1099 dflt_passwd_gecos,
1100 dflt_passwd_dir,
1101 dflt_passwd_shell,
1102 };
1103
1104 static char dflt_group_name[GNLEN+1];
1105
1106 static struct group dflt_group =
1107 {
1108 /* When group information is not available, we return this as the
1109 group for all files. */
1110 dflt_group_name,
1111 0,
1112 };
1113
1114 unsigned
1115 getuid (void)
1116 {
1117 return dflt_passwd.pw_uid;
1118 }
1119
1120 unsigned
1121 geteuid (void)
1122 {
1123 /* I could imagine arguing for checking to see whether the user is
1124 in the Administrators group and returning a UID of 0 for that
1125 case, but I don't know how wise that would be in the long run. */
1126 return getuid ();
1127 }
1128
1129 unsigned
1130 getgid (void)
1131 {
1132 return dflt_passwd.pw_gid;
1133 }
1134
1135 unsigned
1136 getegid (void)
1137 {
1138 return getgid ();
1139 }
1140
1141 struct passwd *
1142 getpwuid (unsigned uid)
1143 {
1144 if (uid == dflt_passwd.pw_uid)
1145 return &dflt_passwd;
1146 return NULL;
1147 }
1148
1149 struct group *
1150 getgrgid (gid_t gid)
1151 {
1152 return &dflt_group;
1153 }
1154
1155 struct passwd *
1156 getpwnam (char *name)
1157 {
1158 struct passwd *pw;
1159
1160 pw = getpwuid (getuid ());
1161 if (!pw)
1162 return pw;
1163
1164 if (xstrcasecmp (name, pw->pw_name))
1165 return NULL;
1166
1167 return pw;
1168 }
1169
1170 static void
1171 init_user_info (void)
1172 {
1173 /* Find the user's real name by opening the process token and
1174 looking up the name associated with the user-sid in that token.
1175
1176 Use the relative portion of the identifier authority value from
1177 the user-sid as the user id value (same for group id using the
1178 primary group sid from the process token). */
1179
1180 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1181 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1182 DWORD glength = sizeof (gname);
1183 HANDLE token = NULL;
1184 SID_NAME_USE user_type;
1185 unsigned char *buf = NULL;
1186 DWORD blen = 0;
1187 TOKEN_USER user_token;
1188 TOKEN_PRIMARY_GROUP group_token;
1189 BOOL result;
1190
1191 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1192 if (result)
1193 {
1194 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1195 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1196 {
1197 buf = xmalloc (blen);
1198 result = get_token_information (token, TokenUser,
1199 (LPVOID)buf, blen, &needed);
1200 if (result)
1201 {
1202 memcpy (&user_token, buf, sizeof (user_token));
1203 result = lookup_account_sid (NULL, user_token.User.Sid,
1204 uname, &ulength,
1205 domain, &dlength, &user_type);
1206 }
1207 }
1208 else
1209 result = FALSE;
1210 }
1211 if (result)
1212 {
1213 strcpy (dflt_passwd.pw_name, uname);
1214 /* Determine a reasonable uid value. */
1215 if (xstrcasecmp ("administrator", uname) == 0)
1216 {
1217 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1218 dflt_passwd.pw_gid = 513; /* well-known None gid */
1219 }
1220 else
1221 {
1222 /* Use the last sub-authority value of the RID, the relative
1223 portion of the SID, as user/group ID. */
1224 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1225
1226 /* Get group id and name. */
1227 result = get_token_information (token, TokenPrimaryGroup,
1228 (LPVOID)buf, blen, &needed);
1229 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1230 {
1231 buf = xrealloc (buf, blen = needed);
1232 result = get_token_information (token, TokenPrimaryGroup,
1233 (LPVOID)buf, blen, &needed);
1234 }
1235 if (result)
1236 {
1237 memcpy (&group_token, buf, sizeof (group_token));
1238 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1239 dlength = sizeof (domain);
1240 /* If we can get at the real Primary Group name, use that.
1241 Otherwise, the default group name was already set to
1242 "None" in globals_of_w32. */
1243 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1244 gname, &glength, NULL, &dlength,
1245 &user_type))
1246 strcpy (dflt_group_name, gname);
1247 }
1248 else
1249 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1250 }
1251 }
1252 /* If security calls are not supported (presumably because we
1253 are running under Windows 9X), fallback to this: */
1254 else if (GetUserName (uname, &ulength))
1255 {
1256 strcpy (dflt_passwd.pw_name, uname);
1257 if (xstrcasecmp ("administrator", uname) == 0)
1258 dflt_passwd.pw_uid = 0;
1259 else
1260 dflt_passwd.pw_uid = 123;
1261 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1262 }
1263 else
1264 {
1265 strcpy (dflt_passwd.pw_name, "unknown");
1266 dflt_passwd.pw_uid = 123;
1267 dflt_passwd.pw_gid = 123;
1268 }
1269 dflt_group.gr_gid = dflt_passwd.pw_gid;
1270
1271 /* Ensure HOME and SHELL are defined. */
1272 if (getenv ("HOME") == NULL)
1273 emacs_abort ();
1274 if (getenv ("SHELL") == NULL)
1275 emacs_abort ();
1276
1277 /* Set dir and shell from environment variables. */
1278 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1279 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1280
1281 xfree (buf);
1282 if (token)
1283 CloseHandle (token);
1284 }
1285
1286 int
1287 random (void)
1288 {
1289 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1290 return ((rand () << 15) | rand ());
1291 }
1292
1293 void
1294 srandom (int seed)
1295 {
1296 srand (seed);
1297 }
1298
1299
1300 /* Normalize filename by converting all path separators to
1301 the specified separator. Also conditionally convert upper
1302 case path name components to lower case. */
1303
1304 static void
1305 normalize_filename (register char *fp, char path_sep)
1306 {
1307 char sep;
1308 char *elem;
1309
1310 /* Always lower-case drive letters a-z, even if the filesystem
1311 preserves case in filenames.
1312 This is so filenames can be compared by string comparison
1313 functions that are case-sensitive. Even case-preserving filesystems
1314 do not distinguish case in drive letters. */
1315 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
1316 {
1317 *fp += 'a' - 'A';
1318 fp += 2;
1319 }
1320
1321 if (NILP (Vw32_downcase_file_names))
1322 {
1323 while (*fp)
1324 {
1325 if (*fp == '/' || *fp == '\\')
1326 *fp = path_sep;
1327 fp++;
1328 }
1329 return;
1330 }
1331
1332 sep = path_sep; /* convert to this path separator */
1333 elem = fp; /* start of current path element */
1334
1335 do {
1336 if (*fp >= 'a' && *fp <= 'z')
1337 elem = 0; /* don't convert this element */
1338
1339 if (*fp == 0 || *fp == ':')
1340 {
1341 sep = *fp; /* restore current separator (or 0) */
1342 *fp = '/'; /* after conversion of this element */
1343 }
1344
1345 if (*fp == '/' || *fp == '\\')
1346 {
1347 if (elem && elem != fp)
1348 {
1349 *fp = 0; /* temporary end of string */
1350 _strlwr (elem); /* while we convert to lower case */
1351 }
1352 *fp = sep; /* convert (or restore) path separator */
1353 elem = fp + 1; /* next element starts after separator */
1354 sep = path_sep;
1355 }
1356 } while (*fp++);
1357 }
1358
1359 /* Destructively turn backslashes into slashes. */
1360 void
1361 dostounix_filename (register char *p)
1362 {
1363 normalize_filename (p, '/');
1364 }
1365
1366 /* Destructively turn slashes into backslashes. */
1367 void
1368 unixtodos_filename (register char *p)
1369 {
1370 normalize_filename (p, '\\');
1371 }
1372
1373 /* Remove all CR's that are followed by a LF.
1374 (From msdos.c...probably should figure out a way to share it,
1375 although this code isn't going to ever change.) */
1376 static int
1377 crlf_to_lf (register int n, register unsigned char *buf)
1378 {
1379 unsigned char *np = buf;
1380 unsigned char *startp = buf;
1381 unsigned char *endp = buf + n;
1382
1383 if (n == 0)
1384 return n;
1385 while (buf < endp - 1)
1386 {
1387 if (*buf == 0x0d)
1388 {
1389 if (*(++buf) != 0x0a)
1390 *np++ = 0x0d;
1391 }
1392 else
1393 *np++ = *buf++;
1394 }
1395 if (buf < endp)
1396 *np++ = *buf++;
1397 return np - startp;
1398 }
1399
1400 /* Parse the root part of file name, if present. Return length and
1401 optionally store pointer to char after root. */
1402 static int
1403 parse_root (char * name, char ** pPath)
1404 {
1405 char * start = name;
1406
1407 if (name == NULL)
1408 return 0;
1409
1410 /* find the root name of the volume if given */
1411 if (isalpha (name[0]) && name[1] == ':')
1412 {
1413 /* skip past drive specifier */
1414 name += 2;
1415 if (IS_DIRECTORY_SEP (name[0]))
1416 name++;
1417 }
1418 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1419 {
1420 int slashes = 2;
1421 name += 2;
1422 do
1423 {
1424 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1425 break;
1426 name++;
1427 }
1428 while ( *name );
1429 if (IS_DIRECTORY_SEP (name[0]))
1430 name++;
1431 }
1432
1433 if (pPath)
1434 *pPath = name;
1435
1436 return name - start;
1437 }
1438
1439 /* Get long base name for name; name is assumed to be absolute. */
1440 static int
1441 get_long_basename (char * name, char * buf, int size)
1442 {
1443 WIN32_FIND_DATA find_data;
1444 HANDLE dir_handle;
1445 int len = 0;
1446
1447 /* must be valid filename, no wild cards or other invalid characters */
1448 if (_mbspbrk (name, "*?|<>\""))
1449 return 0;
1450
1451 dir_handle = FindFirstFile (name, &find_data);
1452 if (dir_handle != INVALID_HANDLE_VALUE)
1453 {
1454 if ((len = strlen (find_data.cFileName)) < size)
1455 memcpy (buf, find_data.cFileName, len + 1);
1456 else
1457 len = 0;
1458 FindClose (dir_handle);
1459 }
1460 return len;
1461 }
1462
1463 /* Get long name for file, if possible (assumed to be absolute). */
1464 BOOL
1465 w32_get_long_filename (char * name, char * buf, int size)
1466 {
1467 char * o = buf;
1468 char * p;
1469 char * q;
1470 char full[ MAX_PATH ];
1471 int len;
1472
1473 len = strlen (name);
1474 if (len >= MAX_PATH)
1475 return FALSE;
1476
1477 /* Use local copy for destructive modification. */
1478 memcpy (full, name, len+1);
1479 unixtodos_filename (full);
1480
1481 /* Copy root part verbatim. */
1482 len = parse_root (full, &p);
1483 memcpy (o, full, len);
1484 o += len;
1485 *o = '\0';
1486 size -= len;
1487
1488 while (p != NULL && *p)
1489 {
1490 q = p;
1491 p = strchr (q, '\\');
1492 if (p) *p = '\0';
1493 len = get_long_basename (full, o, size);
1494 if (len > 0)
1495 {
1496 o += len;
1497 size -= len;
1498 if (p != NULL)
1499 {
1500 *p++ = '\\';
1501 if (size < 2)
1502 return FALSE;
1503 *o++ = '\\';
1504 size--;
1505 *o = '\0';
1506 }
1507 }
1508 else
1509 return FALSE;
1510 }
1511
1512 return TRUE;
1513 }
1514
1515 static int
1516 is_unc_volume (const char *filename)
1517 {
1518 const char *ptr = filename;
1519
1520 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1521 return 0;
1522
1523 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1524 return 0;
1525
1526 return 1;
1527 }
1528
1529 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1530
1531 LPBYTE
1532 w32_get_resource (char *key, LPDWORD lpdwtype)
1533 {
1534 LPBYTE lpvalue;
1535 HKEY hrootkey = NULL;
1536 DWORD cbData;
1537
1538 /* Check both the current user and the local machine to see if
1539 we have any resources. */
1540
1541 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1542 {
1543 lpvalue = NULL;
1544
1545 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1546 && (lpvalue = xmalloc (cbData)) != NULL
1547 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1548 {
1549 RegCloseKey (hrootkey);
1550 return (lpvalue);
1551 }
1552
1553 xfree (lpvalue);
1554
1555 RegCloseKey (hrootkey);
1556 }
1557
1558 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1559 {
1560 lpvalue = NULL;
1561
1562 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1563 && (lpvalue = xmalloc (cbData)) != NULL
1564 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1565 {
1566 RegCloseKey (hrootkey);
1567 return (lpvalue);
1568 }
1569
1570 xfree (lpvalue);
1571
1572 RegCloseKey (hrootkey);
1573 }
1574
1575 return (NULL);
1576 }
1577
1578 char *get_emacs_configuration (void);
1579
1580 void
1581 init_environment (char ** argv)
1582 {
1583 static const char * const tempdirs[] = {
1584 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1585 };
1586
1587 int i;
1588
1589 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1590
1591 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1592 temporary files and assume "/tmp" if $TMPDIR is unset, which
1593 will break on DOS/Windows. Refuse to work if we cannot find
1594 a directory, not even "c:/", usable for that purpose. */
1595 for (i = 0; i < imax ; i++)
1596 {
1597 const char *tmp = tempdirs[i];
1598
1599 if (*tmp == '$')
1600 tmp = getenv (tmp + 1);
1601 /* Note that `access' can lie to us if the directory resides on a
1602 read-only filesystem, like CD-ROM or a write-protected floppy.
1603 The only way to be really sure is to actually create a file and
1604 see if it succeeds. But I think that's too much to ask. */
1605
1606 /* MSVCRT's _access crashes with D_OK. */
1607 if (tmp && faccessat (AT_FDCWD, tmp, D_OK, AT_EACCESS) == 0)
1608 {
1609 char * var = alloca (strlen (tmp) + 8);
1610 sprintf (var, "TMPDIR=%s", tmp);
1611 _putenv (strdup (var));
1612 break;
1613 }
1614 }
1615 if (i >= imax)
1616 cmd_error_internal
1617 (Fcons (Qerror,
1618 Fcons (build_string ("no usable temporary directories found!!"),
1619 Qnil)),
1620 "While setting TMPDIR: ");
1621
1622 /* Check for environment variables and use registry settings if they
1623 don't exist. Fallback on default values where applicable. */
1624 {
1625 int i;
1626 LPBYTE lpval;
1627 DWORD dwType;
1628 char locale_name[32];
1629 char default_home[MAX_PATH];
1630 int appdata = 0;
1631
1632 static const struct env_entry
1633 {
1634 char * name;
1635 char * def_value;
1636 } dflt_envvars[] =
1637 {
1638 /* If the default value is NULL, we will use the value from the
1639 outside environment or the Registry, but will not push the
1640 variable into the Emacs environment if it is defined neither
1641 in the Registry nor in the outside environment. */
1642 {"HOME", "C:/"},
1643 {"PRELOAD_WINSOCK", NULL},
1644 {"emacs_dir", "C:/emacs"},
1645 {"EMACSLOADPATH", NULL},
1646 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1647 {"EMACSDATA", NULL},
1648 {"EMACSPATH", NULL},
1649 {"INFOPATH", NULL},
1650 {"EMACSDOC", NULL},
1651 {"TERM", "cmd"},
1652 {"LANG", NULL},
1653 };
1654
1655 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1656
1657 /* We need to copy dflt_envvars[] and work on the copy because we
1658 don't want the dumped Emacs to inherit the values of
1659 environment variables we saw during dumping (which could be on
1660 a different system). The defaults above must be left intact. */
1661 struct env_entry env_vars[N_ENV_VARS];
1662
1663 for (i = 0; i < N_ENV_VARS; i++)
1664 env_vars[i] = dflt_envvars[i];
1665
1666 /* For backwards compatibility, check if a .emacs file exists in C:/
1667 If not, then we can try to default to the appdata directory under the
1668 user's profile, which is more likely to be writable. */
1669 if (!check_existing ("C:/.emacs"))
1670 {
1671 HRESULT profile_result;
1672 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1673 of Windows 95 and NT4 that have not been updated to include
1674 MSIE 5. */
1675 ShGetFolderPath_fn get_folder_path;
1676 get_folder_path = (ShGetFolderPath_fn)
1677 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1678
1679 if (get_folder_path != NULL)
1680 {
1681 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
1682 0, default_home);
1683
1684 /* If we can't get the appdata dir, revert to old behavior. */
1685 if (profile_result == S_OK)
1686 {
1687 env_vars[0].def_value = default_home;
1688 appdata = 1;
1689 }
1690 }
1691 }
1692
1693 /* Get default locale info and use it for LANG. */
1694 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
1695 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1696 locale_name, sizeof (locale_name)))
1697 {
1698 for (i = 0; i < N_ENV_VARS; i++)
1699 {
1700 if (strcmp (env_vars[i].name, "LANG") == 0)
1701 {
1702 env_vars[i].def_value = locale_name;
1703 break;
1704 }
1705 }
1706 }
1707
1708 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1709
1710 /* Treat emacs_dir specially: set it unconditionally based on our
1711 location. */
1712 {
1713 char *p;
1714 char modname[MAX_PATH];
1715
1716 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1717 emacs_abort ();
1718 if ((p = strrchr (modname, '\\')) == NULL)
1719 emacs_abort ();
1720 *p = 0;
1721
1722 if ((p = strrchr (modname, '\\')) && xstrcasecmp (p, "\\bin") == 0)
1723 {
1724 char buf[SET_ENV_BUF_SIZE];
1725
1726 *p = 0;
1727 for (p = modname; *p; p++)
1728 if (*p == '\\') *p = '/';
1729
1730 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1731 _putenv (strdup (buf));
1732 }
1733 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1734
1735 /* FIXME: should use substring of get_emacs_configuration ().
1736 But I don't think the Windows build supports alpha, mips etc
1737 anymore, so have taken the easy option for now. */
1738 else if (p && (xstrcasecmp (p, "\\i386") == 0
1739 || xstrcasecmp (p, "\\AMD64") == 0))
1740 {
1741 *p = 0;
1742 p = strrchr (modname, '\\');
1743 if (p != NULL)
1744 {
1745 *p = 0;
1746 p = strrchr (modname, '\\');
1747 if (p && xstrcasecmp (p, "\\src") == 0)
1748 {
1749 char buf[SET_ENV_BUF_SIZE];
1750
1751 *p = 0;
1752 for (p = modname; *p; p++)
1753 if (*p == '\\') *p = '/';
1754
1755 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1756 _putenv (strdup (buf));
1757 }
1758 }
1759 }
1760 }
1761
1762 for (i = 0; i < N_ENV_VARS; i++)
1763 {
1764 if (!getenv (env_vars[i].name))
1765 {
1766 int dont_free = 0;
1767
1768 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
1769 /* Also ignore empty environment variables. */
1770 || *lpval == 0)
1771 {
1772 xfree (lpval);
1773 lpval = env_vars[i].def_value;
1774 dwType = REG_EXPAND_SZ;
1775 dont_free = 1;
1776 if (!strcmp (env_vars[i].name, "HOME") && !appdata)
1777 Vdelayed_warnings_list
1778 = Fcons (listn (CONSTYPE_HEAP, 2,
1779 intern ("initialization"),
1780 build_string ("Setting HOME to C:\\ by default is deprecated")),
1781 Vdelayed_warnings_list);
1782 }
1783
1784 if (lpval)
1785 {
1786 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
1787
1788 if (dwType == REG_EXPAND_SZ)
1789 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
1790 else if (dwType == REG_SZ)
1791 strcpy (buf1, lpval);
1792 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
1793 {
1794 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
1795 buf1);
1796 _putenv (strdup (buf2));
1797 }
1798
1799 if (!dont_free)
1800 xfree (lpval);
1801 }
1802 }
1803 }
1804 }
1805
1806 /* Rebuild system configuration to reflect invoking system. */
1807 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
1808
1809 /* Another special case: on NT, the PATH variable is actually named
1810 "Path" although cmd.exe (perhaps NT itself) arranges for
1811 environment variable lookup and setting to be case insensitive.
1812 However, Emacs assumes a fully case sensitive environment, so we
1813 need to change "Path" to "PATH" to match the expectations of
1814 various elisp packages. We do this by the sneaky method of
1815 modifying the string in the C runtime environ entry.
1816
1817 The same applies to COMSPEC. */
1818 {
1819 char ** envp;
1820
1821 for (envp = environ; *envp; envp++)
1822 if (_strnicmp (*envp, "PATH=", 5) == 0)
1823 memcpy (*envp, "PATH=", 5);
1824 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
1825 memcpy (*envp, "COMSPEC=", 8);
1826 }
1827
1828 /* Remember the initial working directory for getwd. */
1829 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
1830 Does it matter anywhere in Emacs? */
1831 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
1832 emacs_abort ();
1833
1834 {
1835 static char modname[MAX_PATH];
1836
1837 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1838 emacs_abort ();
1839 argv[0] = modname;
1840 }
1841
1842 /* Determine if there is a middle mouse button, to allow parse_button
1843 to decide whether right mouse events should be mouse-2 or
1844 mouse-3. */
1845 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
1846
1847 init_user_info ();
1848 }
1849
1850 /* Called from expand-file-name when default-directory is not a string. */
1851
1852 char *
1853 emacs_root_dir (void)
1854 {
1855 static char root_dir[FILENAME_MAX];
1856 const char *p;
1857
1858 p = getenv ("emacs_dir");
1859 if (p == NULL)
1860 emacs_abort ();
1861 strcpy (root_dir, p);
1862 root_dir[parse_root (root_dir, NULL)] = '\0';
1863 dostounix_filename (root_dir);
1864 return root_dir;
1865 }
1866
1867 /* We don't have scripts to automatically determine the system configuration
1868 for Emacs before it's compiled, and we don't want to have to make the
1869 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1870 routine. */
1871
1872 char *
1873 get_emacs_configuration (void)
1874 {
1875 char *arch, *oem, *os;
1876 int build_num;
1877 static char configuration_buffer[32];
1878
1879 /* Determine the processor type. */
1880 switch (get_processor_type ())
1881 {
1882
1883 #ifdef PROCESSOR_INTEL_386
1884 case PROCESSOR_INTEL_386:
1885 case PROCESSOR_INTEL_486:
1886 case PROCESSOR_INTEL_PENTIUM:
1887 #ifdef _WIN64
1888 arch = "amd64";
1889 #else
1890 arch = "i386";
1891 #endif
1892 break;
1893 #endif
1894 #ifdef PROCESSOR_AMD_X8664
1895 case PROCESSOR_AMD_X8664:
1896 arch = "amd64";
1897 break;
1898 #endif
1899
1900 #ifdef PROCESSOR_MIPS_R2000
1901 case PROCESSOR_MIPS_R2000:
1902 case PROCESSOR_MIPS_R3000:
1903 case PROCESSOR_MIPS_R4000:
1904 arch = "mips";
1905 break;
1906 #endif
1907
1908 #ifdef PROCESSOR_ALPHA_21064
1909 case PROCESSOR_ALPHA_21064:
1910 arch = "alpha";
1911 break;
1912 #endif
1913
1914 default:
1915 arch = "unknown";
1916 break;
1917 }
1918
1919 /* Use the OEM field to reflect the compiler/library combination. */
1920 #ifdef _MSC_VER
1921 #define COMPILER_NAME "msvc"
1922 #else
1923 #ifdef __GNUC__
1924 #define COMPILER_NAME "mingw"
1925 #else
1926 #define COMPILER_NAME "unknown"
1927 #endif
1928 #endif
1929 oem = COMPILER_NAME;
1930
1931 switch (osinfo_cache.dwPlatformId) {
1932 case VER_PLATFORM_WIN32_NT:
1933 os = "nt";
1934 build_num = osinfo_cache.dwBuildNumber;
1935 break;
1936 case VER_PLATFORM_WIN32_WINDOWS:
1937 if (osinfo_cache.dwMinorVersion == 0) {
1938 os = "windows95";
1939 } else {
1940 os = "windows98";
1941 }
1942 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1943 break;
1944 case VER_PLATFORM_WIN32s:
1945 /* Not supported, should not happen. */
1946 os = "windows32s";
1947 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1948 break;
1949 default:
1950 os = "unknown";
1951 build_num = 0;
1952 break;
1953 }
1954
1955 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1956 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
1957 get_w32_major_version (), get_w32_minor_version (), build_num);
1958 } else {
1959 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
1960 }
1961
1962 return configuration_buffer;
1963 }
1964
1965 char *
1966 get_emacs_configuration_options (void)
1967 {
1968 static char *options_buffer;
1969 char cv[32]; /* Enough for COMPILER_VERSION. */
1970 char *options[] = {
1971 cv, /* To be filled later. */
1972 #ifdef EMACSDEBUG
1973 " --no-opt",
1974 #endif
1975 #ifdef ENABLE_CHECKING
1976 " --enable-checking",
1977 #endif
1978 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1979 with a starting space to save work here. */
1980 #ifdef USER_CFLAGS
1981 " --cflags", USER_CFLAGS,
1982 #endif
1983 #ifdef USER_LDFLAGS
1984 " --ldflags", USER_LDFLAGS,
1985 #endif
1986 NULL
1987 };
1988 size_t size = 0;
1989 int i;
1990
1991 /* Work out the effective configure options for this build. */
1992 #ifdef _MSC_VER
1993 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1994 #else
1995 #ifdef __GNUC__
1996 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1997 #else
1998 #define COMPILER_VERSION ""
1999 #endif
2000 #endif
2001
2002 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2003 return "Error: not enough space for compiler version";
2004 cv[sizeof (cv) - 1] = '\0';
2005
2006 for (i = 0; options[i]; i++)
2007 size += strlen (options[i]);
2008
2009 options_buffer = xmalloc (size + 1);
2010 options_buffer[0] = '\0';
2011
2012 for (i = 0; options[i]; i++)
2013 strcat (options_buffer, options[i]);
2014
2015 return options_buffer;
2016 }
2017
2018
2019 #include <sys/timeb.h>
2020
2021 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2022 void
2023 gettimeofday (struct timeval *tv, struct timezone *tz)
2024 {
2025 struct _timeb tb;
2026 _ftime (&tb);
2027
2028 tv->tv_sec = tb.time;
2029 tv->tv_usec = tb.millitm * 1000L;
2030 /* Implementation note: _ftime sometimes doesn't update the dstflag
2031 according to the new timezone when the system timezone is
2032 changed. We could fix that by using GetSystemTime and
2033 GetTimeZoneInformation, but that doesn't seem necessary, since
2034 Emacs always calls gettimeofday with the 2nd argument NULL (see
2035 current_emacs_time). */
2036 if (tz)
2037 {
2038 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2039 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2040 }
2041 }
2042
2043 /* Emulate fdutimens. */
2044
2045 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2046 TIMESPEC[0] and TIMESPEC[1], respectively.
2047 FD must be either negative -- in which case it is ignored --
2048 or a file descriptor that is open on FILE.
2049 If FD is nonnegative, then FILE can be NULL, which means
2050 use just futimes instead of utimes.
2051 If TIMESPEC is null, FAIL.
2052 Return 0 on success, -1 (setting errno) on failure. */
2053
2054 int
2055 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2056 {
2057 struct _utimbuf ut;
2058
2059 if (!timespec)
2060 {
2061 errno = ENOSYS;
2062 return -1;
2063 }
2064 if (fd < 0 && !file)
2065 {
2066 errno = EBADF;
2067 return -1;
2068 }
2069 ut.actime = timespec[0].tv_sec;
2070 ut.modtime = timespec[1].tv_sec;
2071 if (fd >= 0)
2072 return _futime (fd, &ut);
2073 else
2074 return _utime (file, &ut);
2075 }
2076
2077
2078 /* ------------------------------------------------------------------------- */
2079 /* IO support and wrapper functions for the Windows API. */
2080 /* ------------------------------------------------------------------------- */
2081
2082 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2083 on network directories, so we handle that case here.
2084 (Ulrich Leodolter, 1/11/95). */
2085 char *
2086 sys_ctime (const time_t *t)
2087 {
2088 char *str = (char *) ctime (t);
2089 return (str ? str : "Sun Jan 01 00:00:00 1970");
2090 }
2091
2092 /* Emulate sleep...we could have done this with a define, but that
2093 would necessitate including windows.h in the files that used it.
2094 This is much easier. */
2095 void
2096 sys_sleep (int seconds)
2097 {
2098 Sleep (seconds * 1000);
2099 }
2100
2101 /* Internal MSVC functions for low-level descriptor munging */
2102 extern int __cdecl _set_osfhnd (int fd, long h);
2103 extern int __cdecl _free_osfhnd (int fd);
2104
2105 /* parallel array of private info on file handles */
2106 filedesc fd_info [ MAXDESC ];
2107
2108 typedef struct volume_info_data {
2109 struct volume_info_data * next;
2110
2111 /* time when info was obtained */
2112 DWORD timestamp;
2113
2114 /* actual volume info */
2115 char * root_dir;
2116 DWORD serialnum;
2117 DWORD maxcomp;
2118 DWORD flags;
2119 char * name;
2120 char * type;
2121 } volume_info_data;
2122
2123 /* Global referenced by various functions. */
2124 static volume_info_data volume_info;
2125
2126 /* Vector to indicate which drives are local and fixed (for which cached
2127 data never expires). */
2128 static BOOL fixed_drives[26];
2129
2130 /* Consider cached volume information to be stale if older than 10s,
2131 at least for non-local drives. Info for fixed drives is never stale. */
2132 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2133 #define VOLINFO_STILL_VALID( root_dir, info ) \
2134 ( ( isalpha (root_dir[0]) && \
2135 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2136 || GetTickCount () - info->timestamp < 10000 )
2137
2138 /* Cache support functions. */
2139
2140 /* Simple linked list with linear search is sufficient. */
2141 static volume_info_data *volume_cache = NULL;
2142
2143 static volume_info_data *
2144 lookup_volume_info (char * root_dir)
2145 {
2146 volume_info_data * info;
2147
2148 for (info = volume_cache; info; info = info->next)
2149 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2150 break;
2151 return info;
2152 }
2153
2154 static void
2155 add_volume_info (char * root_dir, volume_info_data * info)
2156 {
2157 info->root_dir = xstrdup (root_dir);
2158 info->next = volume_cache;
2159 volume_cache = info;
2160 }
2161
2162
2163 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2164 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2165 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2166 static volume_info_data *
2167 GetCachedVolumeInformation (char * root_dir)
2168 {
2169 volume_info_data * info;
2170 char default_root[ MAX_PATH ];
2171
2172 /* NULL for root_dir means use root from current directory. */
2173 if (root_dir == NULL)
2174 {
2175 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2176 return NULL;
2177 parse_root (default_root, &root_dir);
2178 *root_dir = 0;
2179 root_dir = default_root;
2180 }
2181
2182 /* Local fixed drives can be cached permanently. Removable drives
2183 cannot be cached permanently, since the volume name and serial
2184 number (if nothing else) can change. Remote drives should be
2185 treated as if they are removable, since there is no sure way to
2186 tell whether they are or not. Also, the UNC association of drive
2187 letters mapped to remote volumes can be changed at any time (even
2188 by other processes) without notice.
2189
2190 As a compromise, so we can benefit from caching info for remote
2191 volumes, we use a simple expiry mechanism to invalidate cache
2192 entries that are more than ten seconds old. */
2193
2194 #if 0
2195 /* No point doing this, because WNetGetConnection is even slower than
2196 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2197 GetDriveType is about the only call of this type which does not
2198 involve network access, and so is extremely quick). */
2199
2200 /* Map drive letter to UNC if remote. */
2201 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2202 {
2203 char remote_name[ 256 ];
2204 char drive[3] = { root_dir[0], ':' };
2205
2206 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2207 == NO_ERROR)
2208 /* do something */ ;
2209 }
2210 #endif
2211
2212 info = lookup_volume_info (root_dir);
2213
2214 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2215 {
2216 char name[ 256 ];
2217 DWORD serialnum;
2218 DWORD maxcomp;
2219 DWORD flags;
2220 char type[ 256 ];
2221
2222 /* Info is not cached, or is stale. */
2223 if (!GetVolumeInformation (root_dir,
2224 name, sizeof (name),
2225 &serialnum,
2226 &maxcomp,
2227 &flags,
2228 type, sizeof (type)))
2229 return NULL;
2230
2231 /* Cache the volume information for future use, overwriting existing
2232 entry if present. */
2233 if (info == NULL)
2234 {
2235 info = xmalloc (sizeof (volume_info_data));
2236 add_volume_info (root_dir, info);
2237 }
2238 else
2239 {
2240 xfree (info->name);
2241 xfree (info->type);
2242 }
2243
2244 info->name = xstrdup (name);
2245 info->serialnum = serialnum;
2246 info->maxcomp = maxcomp;
2247 info->flags = flags;
2248 info->type = xstrdup (type);
2249 info->timestamp = GetTickCount ();
2250 }
2251
2252 return info;
2253 }
2254
2255 /* Get information on the volume where NAME is held; set path pointer to
2256 start of pathname in NAME (past UNC header\volume header if present),
2257 if pPath is non-NULL.
2258
2259 Note: if NAME includes symlinks, the information is for the volume
2260 of the symlink, not of its target. That's because, even though
2261 GetVolumeInformation returns information about the symlink target
2262 of its argument, we only pass the root directory to
2263 GetVolumeInformation, not the full NAME. */
2264 static int
2265 get_volume_info (const char * name, const char ** pPath)
2266 {
2267 char temp[MAX_PATH];
2268 char *rootname = NULL; /* default to current volume */
2269 volume_info_data * info;
2270
2271 if (name == NULL)
2272 return FALSE;
2273
2274 /* Find the root name of the volume if given. */
2275 if (isalpha (name[0]) && name[1] == ':')
2276 {
2277 rootname = temp;
2278 temp[0] = *name++;
2279 temp[1] = *name++;
2280 temp[2] = '\\';
2281 temp[3] = 0;
2282 }
2283 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2284 {
2285 char *str = temp;
2286 int slashes = 4;
2287 rootname = temp;
2288 do
2289 {
2290 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2291 break;
2292 *str++ = *name++;
2293 }
2294 while ( *name );
2295
2296 *str++ = '\\';
2297 *str = 0;
2298 }
2299
2300 if (pPath)
2301 *pPath = name;
2302
2303 info = GetCachedVolumeInformation (rootname);
2304 if (info != NULL)
2305 {
2306 /* Set global referenced by other functions. */
2307 volume_info = *info;
2308 return TRUE;
2309 }
2310 return FALSE;
2311 }
2312
2313 /* Determine if volume is FAT format (ie. only supports short 8.3
2314 names); also set path pointer to start of pathname in name, if
2315 pPath is non-NULL. */
2316 static int
2317 is_fat_volume (const char * name, const char ** pPath)
2318 {
2319 if (get_volume_info (name, pPath))
2320 return (volume_info.maxcomp == 12);
2321 return FALSE;
2322 }
2323
2324 /* Map filename to a valid 8.3 name if necessary.
2325 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2326 const char *
2327 map_w32_filename (const char * name, const char ** pPath)
2328 {
2329 static char shortname[MAX_PATH];
2330 char * str = shortname;
2331 char c;
2332 char * path;
2333 const char * save_name = name;
2334
2335 if (strlen (name) >= MAX_PATH)
2336 {
2337 /* Return a filename which will cause callers to fail. */
2338 strcpy (shortname, "?");
2339 return shortname;
2340 }
2341
2342 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2343 {
2344 register int left = 8; /* maximum number of chars in part */
2345 register int extn = 0; /* extension added? */
2346 register int dots = 2; /* maximum number of dots allowed */
2347
2348 while (name < path)
2349 *str++ = *name++; /* skip past UNC header */
2350
2351 while ((c = *name++))
2352 {
2353 switch ( c )
2354 {
2355 case ':':
2356 case '\\':
2357 case '/':
2358 *str++ = (c == ':' ? ':' : '\\');
2359 extn = 0; /* reset extension flags */
2360 dots = 2; /* max 2 dots */
2361 left = 8; /* max length 8 for main part */
2362 break;
2363 case '.':
2364 if ( dots )
2365 {
2366 /* Convert path components of the form .xxx to _xxx,
2367 but leave . and .. as they are. This allows .emacs
2368 to be read as _emacs, for example. */
2369
2370 if (! *name ||
2371 *name == '.' ||
2372 IS_DIRECTORY_SEP (*name))
2373 {
2374 *str++ = '.';
2375 dots--;
2376 }
2377 else
2378 {
2379 *str++ = '_';
2380 left--;
2381 dots = 0;
2382 }
2383 }
2384 else if ( !extn )
2385 {
2386 *str++ = '.';
2387 extn = 1; /* we've got an extension */
2388 left = 3; /* 3 chars in extension */
2389 }
2390 else
2391 {
2392 /* any embedded dots after the first are converted to _ */
2393 *str++ = '_';
2394 }
2395 break;
2396 case '~':
2397 case '#': /* don't lose these, they're important */
2398 if ( ! left )
2399 str[-1] = c; /* replace last character of part */
2400 /* FALLTHRU */
2401 default:
2402 if ( left )
2403 {
2404 *str++ = tolower (c); /* map to lower case (looks nicer) */
2405 left--;
2406 dots = 0; /* started a path component */
2407 }
2408 break;
2409 }
2410 }
2411 *str = '\0';
2412 }
2413 else
2414 {
2415 strcpy (shortname, name);
2416 unixtodos_filename (shortname);
2417 }
2418
2419 if (pPath)
2420 *pPath = shortname + (path - save_name);
2421
2422 return shortname;
2423 }
2424
2425 static int
2426 is_exec (const char * name)
2427 {
2428 char * p = strrchr (name, '.');
2429 return
2430 (p != NULL
2431 && (xstrcasecmp (p, ".exe") == 0 ||
2432 xstrcasecmp (p, ".com") == 0 ||
2433 xstrcasecmp (p, ".bat") == 0 ||
2434 xstrcasecmp (p, ".cmd") == 0));
2435 }
2436
2437 /* Emulate the Unix directory procedures opendir, closedir,
2438 and readdir. We can't use the procedures supplied in sysdep.c,
2439 so we provide them here. */
2440
2441 struct direct dir_static; /* simulated directory contents */
2442 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2443 static int dir_is_fat;
2444 static char dir_pathname[MAXPATHLEN+1];
2445 static WIN32_FIND_DATA dir_find_data;
2446
2447 /* Support shares on a network resource as subdirectories of a read-only
2448 root directory. */
2449 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2450 static HANDLE open_unc_volume (const char *);
2451 static char *read_unc_volume (HANDLE, char *, int);
2452 static void close_unc_volume (HANDLE);
2453
2454 DIR *
2455 opendir (char *filename)
2456 {
2457 DIR *dirp;
2458
2459 /* Opening is done by FindFirstFile. However, a read is inherent to
2460 this operation, so we defer the open until read time. */
2461
2462 if (dir_find_handle != INVALID_HANDLE_VALUE)
2463 return NULL;
2464 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2465 return NULL;
2466
2467 /* Note: We don't support traversal of UNC volumes via symlinks.
2468 Doing so would mean punishing 99.99% of use cases by resolving
2469 all the possible symlinks in FILENAME, recursively. */
2470 if (is_unc_volume (filename))
2471 {
2472 wnet_enum_handle = open_unc_volume (filename);
2473 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2474 return NULL;
2475 }
2476
2477 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2478 return NULL;
2479
2480 dirp->dd_fd = 0;
2481 dirp->dd_loc = 0;
2482 dirp->dd_size = 0;
2483
2484 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2485 dir_pathname[MAXPATHLEN] = '\0';
2486 /* Note: We don't support symlinks to file names on FAT volumes.
2487 Doing so would mean punishing 99.99% of use cases by resolving
2488 all the possible symlinks in FILENAME, recursively. */
2489 dir_is_fat = is_fat_volume (filename, NULL);
2490
2491 return dirp;
2492 }
2493
2494 void
2495 closedir (DIR *dirp)
2496 {
2497 /* If we have a find-handle open, close it. */
2498 if (dir_find_handle != INVALID_HANDLE_VALUE)
2499 {
2500 FindClose (dir_find_handle);
2501 dir_find_handle = INVALID_HANDLE_VALUE;
2502 }
2503 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2504 {
2505 close_unc_volume (wnet_enum_handle);
2506 wnet_enum_handle = INVALID_HANDLE_VALUE;
2507 }
2508 xfree ((char *) dirp);
2509 }
2510
2511 struct direct *
2512 readdir (DIR *dirp)
2513 {
2514 int downcase = !NILP (Vw32_downcase_file_names);
2515
2516 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2517 {
2518 if (!read_unc_volume (wnet_enum_handle,
2519 dir_find_data.cFileName,
2520 MAX_PATH))
2521 return NULL;
2522 }
2523 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2524 else if (dir_find_handle == INVALID_HANDLE_VALUE)
2525 {
2526 char filename[MAXNAMLEN + 3];
2527 int ln;
2528
2529 strcpy (filename, dir_pathname);
2530 ln = strlen (filename) - 1;
2531 if (!IS_DIRECTORY_SEP (filename[ln]))
2532 strcat (filename, "\\");
2533 strcat (filename, "*");
2534
2535 /* Note: No need to resolve symlinks in FILENAME, because
2536 FindFirst opens the directory that is the target of a
2537 symlink. */
2538 dir_find_handle = FindFirstFile (filename, &dir_find_data);
2539
2540 if (dir_find_handle == INVALID_HANDLE_VALUE)
2541 return NULL;
2542 }
2543 else
2544 {
2545 if (!FindNextFile (dir_find_handle, &dir_find_data))
2546 return NULL;
2547 }
2548
2549 /* Emacs never uses this value, so don't bother making it match
2550 value returned by stat(). */
2551 dir_static.d_ino = 1;
2552
2553 strcpy (dir_static.d_name, dir_find_data.cFileName);
2554
2555 /* If the file name in cFileName[] includes `?' characters, it means
2556 the original file name used characters that cannot be represented
2557 by the current ANSI codepage. To avoid total lossage, retrieve
2558 the short 8+3 alias of the long file name. */
2559 if (_mbspbrk (dir_static.d_name, "?"))
2560 {
2561 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2562 downcase = 1; /* 8+3 aliases are returned in all caps */
2563 }
2564 dir_static.d_namlen = strlen (dir_static.d_name);
2565 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
2566 dir_static.d_namlen - dir_static.d_namlen % 4;
2567
2568 /* If the file name in cFileName[] includes `?' characters, it means
2569 the original file name used characters that cannot be represented
2570 by the current ANSI codepage. To avoid total lossage, retrieve
2571 the short 8+3 alias of the long file name. */
2572 if (_mbspbrk (dir_find_data.cFileName, "?"))
2573 {
2574 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2575 /* 8+3 aliases are returned in all caps, which could break
2576 various alists that look at filenames' extensions. */
2577 downcase = 1;
2578 }
2579 else
2580 strcpy (dir_static.d_name, dir_find_data.cFileName);
2581 dir_static.d_namlen = strlen (dir_static.d_name);
2582 if (dir_is_fat)
2583 _strlwr (dir_static.d_name);
2584 else if (downcase)
2585 {
2586 register char *p;
2587 for (p = dir_static.d_name; *p; p++)
2588 if (*p >= 'a' && *p <= 'z')
2589 break;
2590 if (!*p)
2591 _strlwr (dir_static.d_name);
2592 }
2593
2594 return &dir_static;
2595 }
2596
2597 static HANDLE
2598 open_unc_volume (const char *path)
2599 {
2600 NETRESOURCE nr;
2601 HANDLE henum;
2602 int result;
2603
2604 nr.dwScope = RESOURCE_GLOBALNET;
2605 nr.dwType = RESOURCETYPE_DISK;
2606 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
2607 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
2608 nr.lpLocalName = NULL;
2609 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
2610 nr.lpComment = NULL;
2611 nr.lpProvider = NULL;
2612
2613 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
2614 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
2615
2616 if (result == NO_ERROR)
2617 return henum;
2618 else
2619 return INVALID_HANDLE_VALUE;
2620 }
2621
2622 static char *
2623 read_unc_volume (HANDLE henum, char *readbuf, int size)
2624 {
2625 DWORD count;
2626 int result;
2627 DWORD bufsize = 512;
2628 char *buffer;
2629 char *ptr;
2630
2631 count = 1;
2632 buffer = alloca (bufsize);
2633 result = WNetEnumResource (henum, &count, buffer, &bufsize);
2634 if (result != NO_ERROR)
2635 return NULL;
2636
2637 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2638 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
2639 ptr += 2;
2640 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
2641 ptr++;
2642
2643 strncpy (readbuf, ptr, size);
2644 return readbuf;
2645 }
2646
2647 static void
2648 close_unc_volume (HANDLE henum)
2649 {
2650 if (henum != INVALID_HANDLE_VALUE)
2651 WNetCloseEnum (henum);
2652 }
2653
2654 static DWORD
2655 unc_volume_file_attributes (const char *path)
2656 {
2657 HANDLE henum;
2658 DWORD attrs;
2659
2660 henum = open_unc_volume (path);
2661 if (henum == INVALID_HANDLE_VALUE)
2662 return -1;
2663
2664 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
2665
2666 close_unc_volume (henum);
2667
2668 return attrs;
2669 }
2670
2671 /* Ensure a network connection is authenticated. */
2672 static void
2673 logon_network_drive (const char *path)
2674 {
2675 NETRESOURCE resource;
2676 char share[MAX_PATH];
2677 int i, n_slashes;
2678 char drive[4];
2679 UINT drvtype;
2680
2681 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
2682 drvtype = DRIVE_REMOTE;
2683 else if (path[0] == '\0' || path[1] != ':')
2684 drvtype = GetDriveType (NULL);
2685 else
2686 {
2687 drive[0] = path[0];
2688 drive[1] = ':';
2689 drive[2] = '\\';
2690 drive[3] = '\0';
2691 drvtype = GetDriveType (drive);
2692 }
2693
2694 /* Only logon to networked drives. */
2695 if (drvtype != DRIVE_REMOTE)
2696 return;
2697
2698 n_slashes = 2;
2699 strncpy (share, path, MAX_PATH);
2700 /* Truncate to just server and share name. */
2701 for (i = 2; i < MAX_PATH; i++)
2702 {
2703 if (IS_DIRECTORY_SEP (share[i]) && ++n_slashes > 3)
2704 {
2705 share[i] = '\0';
2706 break;
2707 }
2708 }
2709
2710 resource.dwType = RESOURCETYPE_DISK;
2711 resource.lpLocalName = NULL;
2712 resource.lpRemoteName = share;
2713 resource.lpProvider = NULL;
2714
2715 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
2716 }
2717
2718 /* Emulate faccessat(2). */
2719 int
2720 faccessat (int dirfd, const char * path, int mode, int flags)
2721 {
2722 DWORD attributes;
2723
2724 if (dirfd != AT_FDCWD
2725 && !(IS_DIRECTORY_SEP (path[0])
2726 || IS_DEVICE_SEP (path[1])))
2727 {
2728 errno = EBADF;
2729 return -1;
2730 }
2731
2732 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
2733 newer versions blow up when passed D_OK. */
2734 path = map_w32_filename (path, NULL);
2735 /* If the last element of PATH is a symlink, we need to resolve it
2736 to get the attributes of its target file. Note: any symlinks in
2737 PATH elements other than the last one are transparently resolved
2738 by GetFileAttributes below. */
2739 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
2740 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
2741 path = chase_symlinks (path);
2742
2743 if ((attributes = GetFileAttributes (path)) == -1)
2744 {
2745 DWORD w32err = GetLastError ();
2746
2747 switch (w32err)
2748 {
2749 case ERROR_INVALID_NAME:
2750 case ERROR_BAD_PATHNAME:
2751 if (is_unc_volume (path))
2752 {
2753 attributes = unc_volume_file_attributes (path);
2754 if (attributes == -1)
2755 {
2756 errno = EACCES;
2757 return -1;
2758 }
2759 break;
2760 }
2761 /* FALLTHROUGH */
2762 case ERROR_FILE_NOT_FOUND:
2763 case ERROR_BAD_NETPATH:
2764 errno = ENOENT;
2765 break;
2766 default:
2767 errno = EACCES;
2768 break;
2769 }
2770 return -1;
2771 }
2772 if ((mode & X_OK) != 0
2773 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
2774 {
2775 errno = EACCES;
2776 return -1;
2777 }
2778 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
2779 {
2780 errno = EACCES;
2781 return -1;
2782 }
2783 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
2784 {
2785 errno = EACCES;
2786 return -1;
2787 }
2788 return 0;
2789 }
2790
2791 /* Shadow some MSVC runtime functions to map requests for long filenames
2792 to reasonable short names if necessary. This was originally added to
2793 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2794 long file names. */
2795
2796 int
2797 sys_chdir (const char * path)
2798 {
2799 return _chdir (map_w32_filename (path, NULL));
2800 }
2801
2802 int
2803 sys_chmod (const char * path, int mode)
2804 {
2805 path = chase_symlinks (map_w32_filename (path, NULL));
2806 return _chmod (path, mode);
2807 }
2808
2809 int
2810 sys_chown (const char *path, uid_t owner, gid_t group)
2811 {
2812 if (sys_chmod (path, S_IREAD) == -1) /* check if file exists */
2813 return -1;
2814 return 0;
2815 }
2816
2817 int
2818 sys_creat (const char * path, int mode)
2819 {
2820 return _creat (map_w32_filename (path, NULL), mode);
2821 }
2822
2823 FILE *
2824 sys_fopen (const char * path, const char * mode)
2825 {
2826 int fd;
2827 int oflag;
2828 const char * mode_save = mode;
2829
2830 /* Force all file handles to be non-inheritable. This is necessary to
2831 ensure child processes don't unwittingly inherit handles that might
2832 prevent future file access. */
2833
2834 if (mode[0] == 'r')
2835 oflag = O_RDONLY;
2836 else if (mode[0] == 'w' || mode[0] == 'a')
2837 oflag = O_WRONLY | O_CREAT | O_TRUNC;
2838 else
2839 return NULL;
2840
2841 /* Only do simplistic option parsing. */
2842 while (*++mode)
2843 if (mode[0] == '+')
2844 {
2845 oflag &= ~(O_RDONLY | O_WRONLY);
2846 oflag |= O_RDWR;
2847 }
2848 else if (mode[0] == 'b')
2849 {
2850 oflag &= ~O_TEXT;
2851 oflag |= O_BINARY;
2852 }
2853 else if (mode[0] == 't')
2854 {
2855 oflag &= ~O_BINARY;
2856 oflag |= O_TEXT;
2857 }
2858 else break;
2859
2860 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
2861 if (fd < 0)
2862 return NULL;
2863
2864 return _fdopen (fd, mode_save);
2865 }
2866
2867 /* This only works on NTFS volumes, but is useful to have. */
2868 int
2869 sys_link (const char * old, const char * new)
2870 {
2871 HANDLE fileh;
2872 int result = -1;
2873 char oldname[MAX_PATH], newname[MAX_PATH];
2874
2875 if (old == NULL || new == NULL)
2876 {
2877 errno = ENOENT;
2878 return -1;
2879 }
2880
2881 strcpy (oldname, map_w32_filename (old, NULL));
2882 strcpy (newname, map_w32_filename (new, NULL));
2883
2884 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
2885 FILE_FLAG_BACKUP_SEMANTICS, NULL);
2886 if (fileh != INVALID_HANDLE_VALUE)
2887 {
2888 int wlen;
2889
2890 /* Confusingly, the "alternate" stream name field does not apply
2891 when restoring a hard link, and instead contains the actual
2892 stream data for the link (ie. the name of the link to create).
2893 The WIN32_STREAM_ID structure before the cStreamName field is
2894 the stream header, which is then immediately followed by the
2895 stream data. */
2896
2897 struct {
2898 WIN32_STREAM_ID wid;
2899 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
2900 } data;
2901
2902 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
2903 data.wid.cStreamName, MAX_PATH);
2904 if (wlen > 0)
2905 {
2906 LPVOID context = NULL;
2907 DWORD wbytes = 0;
2908
2909 data.wid.dwStreamId = BACKUP_LINK;
2910 data.wid.dwStreamAttributes = 0;
2911 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
2912 data.wid.Size.HighPart = 0;
2913 data.wid.dwStreamNameSize = 0;
2914
2915 if (BackupWrite (fileh, (LPBYTE)&data,
2916 offsetof (WIN32_STREAM_ID, cStreamName)
2917 + data.wid.Size.LowPart,
2918 &wbytes, FALSE, FALSE, &context)
2919 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
2920 {
2921 /* succeeded */
2922 result = 0;
2923 }
2924 else
2925 {
2926 /* Should try mapping GetLastError to errno; for now just
2927 indicate a general error (eg. links not supported). */
2928 errno = EINVAL; // perhaps EMLINK?
2929 }
2930 }
2931
2932 CloseHandle (fileh);
2933 }
2934 else
2935 errno = ENOENT;
2936
2937 return result;
2938 }
2939
2940 int
2941 sys_mkdir (const char * path)
2942 {
2943 return _mkdir (map_w32_filename (path, NULL));
2944 }
2945
2946 /* Because of long name mapping issues, we need to implement this
2947 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2948 a unique name, instead of setting the input template to an empty
2949 string.
2950
2951 Standard algorithm seems to be use pid or tid with a letter on the
2952 front (in place of the 6 X's) and cycle through the letters to find a
2953 unique name. We extend that to allow any reasonable character as the
2954 first of the 6 X's. */
2955 char *
2956 sys_mktemp (char * template)
2957 {
2958 char * p;
2959 int i;
2960 unsigned uid = GetCurrentThreadId ();
2961 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2962
2963 if (template == NULL)
2964 return NULL;
2965 p = template + strlen (template);
2966 i = 5;
2967 /* replace up to the last 5 X's with uid in decimal */
2968 while (--p >= template && p[0] == 'X' && --i >= 0)
2969 {
2970 p[0] = '0' + uid % 10;
2971 uid /= 10;
2972 }
2973
2974 if (i < 0 && p[0] == 'X')
2975 {
2976 i = 0;
2977 do
2978 {
2979 int save_errno = errno;
2980 p[0] = first_char[i];
2981 if (faccessat (AT_FDCWD, template, F_OK, AT_EACCESS) < 0)
2982 {
2983 errno = save_errno;
2984 return template;
2985 }
2986 }
2987 while (++i < sizeof (first_char));
2988 }
2989
2990 /* Template is badly formed or else we can't generate a unique name,
2991 so return empty string */
2992 template[0] = 0;
2993 return template;
2994 }
2995
2996 int
2997 sys_open (const char * path, int oflag, int mode)
2998 {
2999 const char* mpath = map_w32_filename (path, NULL);
3000 /* Try to open file without _O_CREAT, to be able to write to hidden
3001 and system files. Force all file handles to be
3002 non-inheritable. */
3003 int res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3004 if (res >= 0)
3005 return res;
3006 return _open (mpath, oflag | _O_NOINHERIT, mode);
3007 }
3008
3009 int
3010 sys_rename (const char * oldname, const char * newname)
3011 {
3012 BOOL result;
3013 char temp[MAX_PATH];
3014 int newname_dev;
3015 int oldname_dev;
3016
3017 /* MoveFile on Windows 95 doesn't correctly change the short file name
3018 alias in a number of circumstances (it is not easy to predict when
3019 just by looking at oldname and newname, unfortunately). In these
3020 cases, renaming through a temporary name avoids the problem.
3021
3022 A second problem on Windows 95 is that renaming through a temp name when
3023 newname is uppercase fails (the final long name ends up in
3024 lowercase, although the short alias might be uppercase) UNLESS the
3025 long temp name is not 8.3.
3026
3027 So, on Windows 95 we always rename through a temp name, and we make sure
3028 the temp name has a long extension to ensure correct renaming. */
3029
3030 strcpy (temp, map_w32_filename (oldname, NULL));
3031
3032 /* volume_info is set indirectly by map_w32_filename. */
3033 oldname_dev = volume_info.serialnum;
3034
3035 if (os_subtype == OS_9X)
3036 {
3037 char * o;
3038 char * p;
3039 int i = 0;
3040
3041 oldname = map_w32_filename (oldname, NULL);
3042 if ((o = strrchr (oldname, '\\')))
3043 o++;
3044 else
3045 o = (char *) oldname;
3046
3047 if ((p = strrchr (temp, '\\')))
3048 p++;
3049 else
3050 p = temp;
3051
3052 do
3053 {
3054 /* Force temp name to require a manufactured 8.3 alias - this
3055 seems to make the second rename work properly. */
3056 sprintf (p, "_.%s.%u", o, i);
3057 i++;
3058 result = rename (oldname, temp);
3059 }
3060 /* This loop must surely terminate! */
3061 while (result < 0 && errno == EEXIST);
3062 if (result < 0)
3063 return -1;
3064 }
3065
3066 /* Emulate Unix behavior - newname is deleted if it already exists
3067 (at least if it is a file; don't do this for directories).
3068
3069 Since we mustn't do this if we are just changing the case of the
3070 file name (we would end up deleting the file we are trying to
3071 rename!), we let rename detect if the destination file already
3072 exists - that way we avoid the possible pitfalls of trying to
3073 determine ourselves whether two names really refer to the same
3074 file, which is not always possible in the general case. (Consider
3075 all the permutations of shared or subst'd drives, etc.) */
3076
3077 newname = map_w32_filename (newname, NULL);
3078
3079 /* volume_info is set indirectly by map_w32_filename. */
3080 newname_dev = volume_info.serialnum;
3081
3082 result = rename (temp, newname);
3083
3084 if (result < 0)
3085 {
3086 DWORD w32err = GetLastError ();
3087
3088 if (errno == EACCES
3089 && newname_dev != oldname_dev)
3090 {
3091 /* The implementation of `rename' on Windows does not return
3092 errno = EXDEV when you are moving a directory to a
3093 different storage device (ex. logical disk). It returns
3094 EACCES instead. So here we handle such situations and
3095 return EXDEV. */
3096 DWORD attributes;
3097
3098 if ((attributes = GetFileAttributes (temp)) != -1
3099 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3100 errno = EXDEV;
3101 }
3102 else if (errno == EEXIST)
3103 {
3104 if (_chmod (newname, 0666) != 0)
3105 return result;
3106 if (_unlink (newname) != 0)
3107 return result;
3108 result = rename (temp, newname);
3109 }
3110 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3111 && is_symlink (temp))
3112 {
3113 /* This is Windows prohibiting the user from creating a
3114 symlink in another place, since that requires
3115 privileges. */
3116 errno = EPERM;
3117 }
3118 }
3119
3120 return result;
3121 }
3122
3123 int
3124 sys_rmdir (const char * path)
3125 {
3126 return _rmdir (map_w32_filename (path, NULL));
3127 }
3128
3129 int
3130 sys_unlink (const char * path)
3131 {
3132 path = map_w32_filename (path, NULL);
3133
3134 /* On Unix, unlink works without write permission. */
3135 _chmod (path, 0666);
3136 return _unlink (path);
3137 }
3138
3139 static FILETIME utc_base_ft;
3140 static ULONGLONG utc_base; /* In 100ns units */
3141 static int init = 0;
3142
3143 #define FILETIME_TO_U64(result, ft) \
3144 do { \
3145 ULARGE_INTEGER uiTemp; \
3146 uiTemp.LowPart = (ft).dwLowDateTime; \
3147 uiTemp.HighPart = (ft).dwHighDateTime; \
3148 result = uiTemp.QuadPart; \
3149 } while (0)
3150
3151 static void
3152 initialize_utc_base (void)
3153 {
3154 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3155 SYSTEMTIME st;
3156
3157 st.wYear = 1970;
3158 st.wMonth = 1;
3159 st.wDay = 1;
3160 st.wHour = 0;
3161 st.wMinute = 0;
3162 st.wSecond = 0;
3163 st.wMilliseconds = 0;
3164
3165 SystemTimeToFileTime (&st, &utc_base_ft);
3166 FILETIME_TO_U64 (utc_base, utc_base_ft);
3167 }
3168
3169 static time_t
3170 convert_time (FILETIME ft)
3171 {
3172 ULONGLONG tmp;
3173
3174 if (!init)
3175 {
3176 initialize_utc_base ();
3177 init = 1;
3178 }
3179
3180 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3181 return 0;
3182
3183 FILETIME_TO_U64 (tmp, ft);
3184 return (time_t) ((tmp - utc_base) / 10000000L);
3185 }
3186
3187 static void
3188 convert_from_time_t (time_t time, FILETIME * pft)
3189 {
3190 ULARGE_INTEGER tmp;
3191
3192 if (!init)
3193 {
3194 initialize_utc_base ();
3195 init = 1;
3196 }
3197
3198 /* time in 100ns units since 1-Jan-1601 */
3199 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3200 pft->dwHighDateTime = tmp.HighPart;
3201 pft->dwLowDateTime = tmp.LowPart;
3202 }
3203
3204 #if 0
3205 /* No reason to keep this; faking inode values either by hashing or even
3206 using the file index from GetInformationByHandle, is not perfect and
3207 so by default Emacs doesn't use the inode values on Windows.
3208 Instead, we now determine file-truename correctly (except for
3209 possible drive aliasing etc). */
3210
3211 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3212 static unsigned
3213 hashval (const unsigned char * str)
3214 {
3215 unsigned h = 0;
3216 while (*str)
3217 {
3218 h = (h << 4) + *str++;
3219 h ^= (h >> 28);
3220 }
3221 return h;
3222 }
3223
3224 /* Return the hash value of the canonical pathname, excluding the
3225 drive/UNC header, to get a hopefully unique inode number. */
3226 static DWORD
3227 generate_inode_val (const char * name)
3228 {
3229 char fullname[ MAX_PATH ];
3230 char * p;
3231 unsigned hash;
3232
3233 /* Get the truly canonical filename, if it exists. (Note: this
3234 doesn't resolve aliasing due to subst commands, or recognize hard
3235 links. */
3236 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3237 emacs_abort ();
3238
3239 parse_root (fullname, &p);
3240 /* Normal W32 filesystems are still case insensitive. */
3241 _strlwr (p);
3242 return hashval (p);
3243 }
3244
3245 #endif
3246
3247 static PSECURITY_DESCRIPTOR
3248 get_file_security_desc_by_handle (HANDLE h)
3249 {
3250 PSECURITY_DESCRIPTOR psd = NULL;
3251 DWORD err;
3252 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3253 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3254
3255 err = get_security_info (h, SE_FILE_OBJECT, si,
3256 NULL, NULL, NULL, NULL, &psd);
3257 if (err != ERROR_SUCCESS)
3258 return NULL;
3259
3260 return psd;
3261 }
3262
3263 static PSECURITY_DESCRIPTOR
3264 get_file_security_desc_by_name (const char *fname)
3265 {
3266 PSECURITY_DESCRIPTOR psd = NULL;
3267 DWORD sd_len, err;
3268 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3269 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3270
3271 if (!get_file_security (fname, si, psd, 0, &sd_len))
3272 {
3273 err = GetLastError ();
3274 if (err != ERROR_INSUFFICIENT_BUFFER)
3275 return NULL;
3276 }
3277
3278 psd = xmalloc (sd_len);
3279 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3280 {
3281 xfree (psd);
3282 return NULL;
3283 }
3284
3285 return psd;
3286 }
3287
3288 static DWORD
3289 get_rid (PSID sid)
3290 {
3291 unsigned n_subauthorities;
3292
3293 /* Use the last sub-authority value of the RID, the relative
3294 portion of the SID, as user/group ID. */
3295 n_subauthorities = *get_sid_sub_authority_count (sid);
3296 if (n_subauthorities < 1)
3297 return 0; /* the "World" RID */
3298 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3299 }
3300
3301 /* Caching SID and account values for faster lokup. */
3302
3303 #ifdef __GNUC__
3304 # define FLEXIBLE_ARRAY_MEMBER
3305 #else
3306 # define FLEXIBLE_ARRAY_MEMBER 1
3307 #endif
3308
3309 struct w32_id {
3310 unsigned rid;
3311 struct w32_id *next;
3312 char name[GNLEN+1];
3313 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3314 };
3315
3316 static struct w32_id *w32_idlist;
3317
3318 static int
3319 w32_cached_id (PSID sid, unsigned *id, char *name)
3320 {
3321 struct w32_id *tail, *found;
3322
3323 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3324 {
3325 if (equal_sid ((PSID)tail->sid, sid))
3326 {
3327 found = tail;
3328 break;
3329 }
3330 }
3331 if (found)
3332 {
3333 *id = found->rid;
3334 strcpy (name, found->name);
3335 return 1;
3336 }
3337 else
3338 return 0;
3339 }
3340
3341 static void
3342 w32_add_to_cache (PSID sid, unsigned id, char *name)
3343 {
3344 DWORD sid_len;
3345 struct w32_id *new_entry;
3346
3347 /* We don't want to leave behind stale cache from when Emacs was
3348 dumped. */
3349 if (initialized)
3350 {
3351 sid_len = get_length_sid (sid);
3352 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3353 if (new_entry)
3354 {
3355 new_entry->rid = id;
3356 strcpy (new_entry->name, name);
3357 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3358 new_entry->next = w32_idlist;
3359 w32_idlist = new_entry;
3360 }
3361 }
3362 }
3363
3364 #define UID 1
3365 #define GID 2
3366
3367 static int
3368 get_name_and_id (PSECURITY_DESCRIPTOR psd, const char *fname,
3369 unsigned *id, char *nm, int what)
3370 {
3371 PSID sid = NULL;
3372 char machine[MAX_COMPUTERNAME_LENGTH+1];
3373 BOOL dflt;
3374 SID_NAME_USE ignore;
3375 char name[UNLEN+1];
3376 DWORD name_len = sizeof (name);
3377 char domain[1024];
3378 DWORD domain_len = sizeof (domain);
3379 char *mp = NULL;
3380 int use_dflt = 0;
3381 int result;
3382
3383 if (what == UID)
3384 result = get_security_descriptor_owner (psd, &sid, &dflt);
3385 else if (what == GID)
3386 result = get_security_descriptor_group (psd, &sid, &dflt);
3387 else
3388 result = 0;
3389
3390 if (!result || !is_valid_sid (sid))
3391 use_dflt = 1;
3392 else if (!w32_cached_id (sid, id, nm))
3393 {
3394 /* If FNAME is a UNC, we need to lookup account on the
3395 specified machine. */
3396 if (IS_DIRECTORY_SEP (fname[0]) && IS_DIRECTORY_SEP (fname[1])
3397 && fname[2] != '\0')
3398 {
3399 const char *s;
3400 char *p;
3401
3402 for (s = fname + 2, p = machine;
3403 *s && !IS_DIRECTORY_SEP (*s); s++, p++)
3404 *p = *s;
3405 *p = '\0';
3406 mp = machine;
3407 }
3408
3409 if (!lookup_account_sid (mp, sid, name, &name_len,
3410 domain, &domain_len, &ignore)
3411 || name_len > UNLEN+1)
3412 use_dflt = 1;
3413 else
3414 {
3415 *id = get_rid (sid);
3416 strcpy (nm, name);
3417 w32_add_to_cache (sid, *id, name);
3418 }
3419 }
3420 return use_dflt;
3421 }
3422
3423 static void
3424 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd,
3425 const char *fname,
3426 struct stat *st)
3427 {
3428 int dflt_usr = 0, dflt_grp = 0;
3429
3430 if (!psd)
3431 {
3432 dflt_usr = 1;
3433 dflt_grp = 1;
3434 }
3435 else
3436 {
3437 if (get_name_and_id (psd, fname, &st->st_uid, st->st_uname, UID))
3438 dflt_usr = 1;
3439 if (get_name_and_id (psd, fname, &st->st_gid, st->st_gname, GID))
3440 dflt_grp = 1;
3441 }
3442 /* Consider files to belong to current user/group, if we cannot get
3443 more accurate information. */
3444 if (dflt_usr)
3445 {
3446 st->st_uid = dflt_passwd.pw_uid;
3447 strcpy (st->st_uname, dflt_passwd.pw_name);
3448 }
3449 if (dflt_grp)
3450 {
3451 st->st_gid = dflt_passwd.pw_gid;
3452 strcpy (st->st_gname, dflt_group.gr_name);
3453 }
3454 }
3455
3456 /* Return non-zero if NAME is a potentially slow filesystem. */
3457 int
3458 is_slow_fs (const char *name)
3459 {
3460 char drive_root[4];
3461 UINT devtype;
3462
3463 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3464 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3465 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3466 devtype = GetDriveType (NULL); /* use root of current drive */
3467 else
3468 {
3469 /* GetDriveType needs the root directory of the drive. */
3470 strncpy (drive_root, name, 2);
3471 drive_root[2] = '\\';
3472 drive_root[3] = '\0';
3473 devtype = GetDriveType (drive_root);
3474 }
3475 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3476 }
3477
3478 /* MSVC stat function can't cope with UNC names and has other bugs, so
3479 replace it with our own. This also allows us to calculate consistent
3480 inode values and owner/group without hacks in the main Emacs code. */
3481
3482 static int
3483 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
3484 {
3485 char *name, *save_name, *r;
3486 WIN32_FIND_DATA wfd;
3487 HANDLE fh;
3488 unsigned __int64 fake_inode = 0;
3489 int permission;
3490 int len;
3491 int rootdir = FALSE;
3492 PSECURITY_DESCRIPTOR psd = NULL;
3493 int is_a_symlink = 0;
3494 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
3495 DWORD access_rights = 0;
3496 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
3497 FILETIME ctime, atime, wtime;
3498
3499 if (path == NULL || buf == NULL)
3500 {
3501 errno = EFAULT;
3502 return -1;
3503 }
3504
3505 save_name = name = (char *) map_w32_filename (path, &path);
3506 /* Must be valid filename, no wild cards or other invalid
3507 characters. We use _mbspbrk to support multibyte strings that
3508 might look to strpbrk as if they included literal *, ?, and other
3509 characters mentioned below that are disallowed by Windows
3510 filesystems. */
3511 if (_mbspbrk (name, "*?|<>\""))
3512 {
3513 errno = ENOENT;
3514 return -1;
3515 }
3516
3517 /* Remove trailing directory separator, unless name is the root
3518 directory of a drive or UNC volume in which case ensure there
3519 is a trailing separator. */
3520 len = strlen (name);
3521 name = strcpy (alloca (len + 2), name);
3522
3523 /* Avoid a somewhat costly call to is_symlink if the filesystem
3524 doesn't support symlinks. */
3525 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
3526 is_a_symlink = is_symlink (name);
3527
3528 /* Plan A: Open the file and get all the necessary information via
3529 the resulting handle. This solves several issues in one blow:
3530
3531 . retrieves attributes for the target of a symlink, if needed
3532 . gets attributes of root directories and symlinks pointing to
3533 root directories, thus avoiding the need for special-casing
3534 these and detecting them by examining the file-name format
3535 . retrieves more accurate attributes (e.g., non-zero size for
3536 some directories, esp. directories that are junction points)
3537 . correctly resolves "c:/..", "/.." and similar file names
3538 . avoids run-time penalties for 99% of use cases
3539
3540 Plan A is always tried first, unless the user asked not to (but
3541 if the file is a symlink and we need to follow links, we try Plan
3542 A even if the user asked not to).
3543
3544 If Plan A fails, we go to Plan B (below), where various
3545 potentially expensive techniques must be used to handle "special"
3546 files such as UNC volumes etc. */
3547 if (!(NILP (Vw32_get_true_file_attributes)
3548 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
3549 /* Following symlinks requires getting the info by handle. */
3550 || (is_a_symlink && follow_symlinks))
3551 {
3552 BY_HANDLE_FILE_INFORMATION info;
3553
3554 if (is_a_symlink && !follow_symlinks)
3555 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
3556 /* READ_CONTROL access rights are required to get security info
3557 by handle. But if the OS doesn't support security in the
3558 first place, we don't need to try. */
3559 if (is_windows_9x () != TRUE)
3560 access_rights |= READ_CONTROL;
3561
3562 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
3563 file_flags, NULL);
3564 /* If CreateFile fails with READ_CONTROL, try again with zero as
3565 access rights. */
3566 if (fh == INVALID_HANDLE_VALUE && access_rights)
3567 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
3568 file_flags, NULL);
3569 if (fh == INVALID_HANDLE_VALUE)
3570 goto no_true_file_attributes;
3571
3572 /* This is more accurate in terms of getting the correct number
3573 of links, but is quite slow (it is noticeable when Emacs is
3574 making a list of file name completions). */
3575 if (GetFileInformationByHandle (fh, &info))
3576 {
3577 nlinks = info.nNumberOfLinks;
3578 /* Might as well use file index to fake inode values, but this
3579 is not guaranteed to be unique unless we keep a handle open
3580 all the time (even then there are situations where it is
3581 not unique). Reputedly, there are at most 48 bits of info
3582 (on NTFS, presumably less on FAT). */
3583 fake_inode = info.nFileIndexHigh;
3584 fake_inode <<= 32;
3585 fake_inode += info.nFileIndexLow;
3586 serialnum = info.dwVolumeSerialNumber;
3587 fs_high = info.nFileSizeHigh;
3588 fs_low = info.nFileSizeLow;
3589 ctime = info.ftCreationTime;
3590 atime = info.ftLastAccessTime;
3591 wtime = info.ftLastWriteTime;
3592 fattrs = info.dwFileAttributes;
3593 }
3594 else
3595 {
3596 /* We don't go to Plan B here, because it's not clear that
3597 it's a good idea. The only known use case where
3598 CreateFile succeeds, but GetFileInformationByHandle fails
3599 (with ERROR_INVALID_FUNCTION) is for character devices
3600 such as NUL, PRN, etc. For these, switching to Plan B is
3601 a net loss, because we lose the character device
3602 attribute returned by GetFileType below (FindFirstFile
3603 doesn't set that bit in the attributes), and the other
3604 fields don't make sense for character devices anyway.
3605 Emacs doesn't really care for non-file entities in the
3606 context of l?stat, so neither do we. */
3607
3608 /* w32err is assigned so one could put a breakpoint here and
3609 examine its value, when GetFileInformationByHandle
3610 fails. */
3611 DWORD w32err = GetLastError ();
3612
3613 switch (w32err)
3614 {
3615 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
3616 errno = ENOENT;
3617 return -1;
3618 }
3619 }
3620
3621 /* Test for a symlink before testing for a directory, since
3622 symlinks to directories have the directory bit set, but we
3623 don't want them to appear as directories. */
3624 if (is_a_symlink && !follow_symlinks)
3625 buf->st_mode = S_IFLNK;
3626 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3627 buf->st_mode = S_IFDIR;
3628 else
3629 {
3630 DWORD ftype = GetFileType (fh);
3631
3632 switch (ftype)
3633 {
3634 case FILE_TYPE_DISK:
3635 buf->st_mode = S_IFREG;
3636 break;
3637 case FILE_TYPE_PIPE:
3638 buf->st_mode = S_IFIFO;
3639 break;
3640 case FILE_TYPE_CHAR:
3641 case FILE_TYPE_UNKNOWN:
3642 default:
3643 buf->st_mode = S_IFCHR;
3644 }
3645 }
3646 /* We produce the fallback owner and group data, based on the
3647 current user that runs Emacs, in the following cases:
3648
3649 . this is Windows 9X
3650 . getting security by handle failed, and we need to produce
3651 information for the target of a symlink (this is better
3652 than producing a potentially misleading info about the
3653 symlink itself)
3654
3655 If getting security by handle fails, and we don't need to
3656 resolve symlinks, we try getting security by name. */
3657 if (is_windows_9x () != TRUE)
3658 psd = get_file_security_desc_by_handle (fh);
3659 if (psd)
3660 {
3661 get_file_owner_and_group (psd, name, buf);
3662 LocalFree (psd);
3663 }
3664 else if (is_windows_9x () == TRUE)
3665 get_file_owner_and_group (NULL, name, buf);
3666 else if (!(is_a_symlink && follow_symlinks))
3667 {
3668 psd = get_file_security_desc_by_name (name);
3669 get_file_owner_and_group (psd, name, buf);
3670 xfree (psd);
3671 }
3672 else
3673 get_file_owner_and_group (NULL, name, buf);
3674 CloseHandle (fh);
3675 }
3676 else
3677 {
3678 no_true_file_attributes:
3679 /* Plan B: Either getting a handle on the file failed, or the
3680 caller explicitly asked us to not bother making this
3681 information more accurate.
3682
3683 Implementation note: In Plan B, we never bother to resolve
3684 symlinks, even if we got here because we tried Plan A and
3685 failed. That's because, even if the caller asked for extra
3686 precision by setting Vw32_get_true_file_attributes to t,
3687 resolving symlinks requires acquiring a file handle to the
3688 symlink, which we already know will fail. And if the user
3689 did not ask for extra precision, resolving symlinks will fly
3690 in the face of that request, since the user then wants the
3691 lightweight version of the code. */
3692 rootdir = (path >= save_name + len - 1
3693 && (IS_DIRECTORY_SEP (*path) || *path == 0));
3694
3695 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3696 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
3697 if (IS_DIRECTORY_SEP (r[0])
3698 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
3699 r[1] = r[2] = '\0';
3700
3701 /* Note: If NAME is a symlink to the root of a UNC volume
3702 (i.e. "\\SERVER"), we will not detect that here, and we will
3703 return data about the symlink as result of FindFirst below.
3704 This is unfortunate, but that marginal use case does not
3705 justify a call to chase_symlinks which would impose a penalty
3706 on all the other use cases. (We get here for symlinks to
3707 roots of UNC volumes because CreateFile above fails for them,
3708 unlike with symlinks to root directories X:\ of drives.) */
3709 if (is_unc_volume (name))
3710 {
3711 fattrs = unc_volume_file_attributes (name);
3712 if (fattrs == -1)
3713 return -1;
3714
3715 ctime = atime = wtime = utc_base_ft;
3716 }
3717 else if (rootdir)
3718 {
3719 if (!IS_DIRECTORY_SEP (name[len-1]))
3720 strcat (name, "\\");
3721 if (GetDriveType (name) < 2)
3722 {
3723 errno = ENOENT;
3724 return -1;
3725 }
3726
3727 fattrs = FILE_ATTRIBUTE_DIRECTORY;
3728 ctime = atime = wtime = utc_base_ft;
3729 }
3730 else
3731 {
3732 if (IS_DIRECTORY_SEP (name[len-1]))
3733 name[len - 1] = 0;
3734
3735 /* (This is hacky, but helps when doing file completions on
3736 network drives.) Optimize by using information available from
3737 active readdir if possible. */
3738 len = strlen (dir_pathname);
3739 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
3740 len--;
3741 if (dir_find_handle != INVALID_HANDLE_VALUE
3742 && !(is_a_symlink && follow_symlinks)
3743 && strnicmp (save_name, dir_pathname, len) == 0
3744 && IS_DIRECTORY_SEP (name[len])
3745 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
3746 {
3747 /* This was the last entry returned by readdir. */
3748 wfd = dir_find_data;
3749 }
3750 else
3751 {
3752 logon_network_drive (name);
3753
3754 fh = FindFirstFile (name, &wfd);
3755 if (fh == INVALID_HANDLE_VALUE)
3756 {
3757 errno = ENOENT;
3758 return -1;
3759 }
3760 FindClose (fh);
3761 }
3762 /* Note: if NAME is a symlink, the information we get from
3763 FindFirstFile is for the symlink, not its target. */
3764 fattrs = wfd.dwFileAttributes;
3765 ctime = wfd.ftCreationTime;
3766 atime = wfd.ftLastAccessTime;
3767 wtime = wfd.ftLastWriteTime;
3768 fs_high = wfd.nFileSizeHigh;
3769 fs_low = wfd.nFileSizeLow;
3770 fake_inode = 0;
3771 nlinks = 1;
3772 serialnum = volume_info.serialnum;
3773 }
3774 if (is_a_symlink && !follow_symlinks)
3775 buf->st_mode = S_IFLNK;
3776 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3777 buf->st_mode = S_IFDIR;
3778 else
3779 buf->st_mode = S_IFREG;
3780
3781 get_file_owner_and_group (NULL, name, buf);
3782 }
3783
3784 #if 0
3785 /* Not sure if there is any point in this. */
3786 if (!NILP (Vw32_generate_fake_inodes))
3787 fake_inode = generate_inode_val (name);
3788 else if (fake_inode == 0)
3789 {
3790 /* For want of something better, try to make everything unique. */
3791 static DWORD gen_num = 0;
3792 fake_inode = ++gen_num;
3793 }
3794 #endif
3795
3796 buf->st_ino = fake_inode;
3797
3798 buf->st_dev = serialnum;
3799 buf->st_rdev = serialnum;
3800
3801 buf->st_size = fs_high;
3802 buf->st_size <<= 32;
3803 buf->st_size += fs_low;
3804 buf->st_nlink = nlinks;
3805
3806 /* Convert timestamps to Unix format. */
3807 buf->st_mtime = convert_time (wtime);
3808 buf->st_atime = convert_time (atime);
3809 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3810 buf->st_ctime = convert_time (ctime);
3811 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3812
3813 /* determine rwx permissions */
3814 if (is_a_symlink && !follow_symlinks)
3815 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
3816 else
3817 {
3818 if (fattrs & FILE_ATTRIBUTE_READONLY)
3819 permission = S_IREAD;
3820 else
3821 permission = S_IREAD | S_IWRITE;
3822
3823 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3824 permission |= S_IEXEC;
3825 else if (is_exec (name))
3826 permission |= S_IEXEC;
3827 }
3828
3829 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3830
3831 return 0;
3832 }
3833
3834 int
3835 stat (const char * path, struct stat * buf)
3836 {
3837 return stat_worker (path, buf, 1);
3838 }
3839
3840 int
3841 lstat (const char * path, struct stat * buf)
3842 {
3843 return stat_worker (path, buf, 0);
3844 }
3845
3846 /* Provide fstat and utime as well as stat for consistent handling of
3847 file timestamps. */
3848 int
3849 fstat (int desc, struct stat * buf)
3850 {
3851 HANDLE fh = (HANDLE) _get_osfhandle (desc);
3852 BY_HANDLE_FILE_INFORMATION info;
3853 unsigned __int64 fake_inode;
3854 int permission;
3855
3856 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
3857 {
3858 case FILE_TYPE_DISK:
3859 buf->st_mode = S_IFREG;
3860 if (!GetFileInformationByHandle (fh, &info))
3861 {
3862 errno = EACCES;
3863 return -1;
3864 }
3865 break;
3866 case FILE_TYPE_PIPE:
3867 buf->st_mode = S_IFIFO;
3868 goto non_disk;
3869 case FILE_TYPE_CHAR:
3870 case FILE_TYPE_UNKNOWN:
3871 default:
3872 buf->st_mode = S_IFCHR;
3873 non_disk:
3874 memset (&info, 0, sizeof (info));
3875 info.dwFileAttributes = 0;
3876 info.ftCreationTime = utc_base_ft;
3877 info.ftLastAccessTime = utc_base_ft;
3878 info.ftLastWriteTime = utc_base_ft;
3879 }
3880
3881 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3882 buf->st_mode = S_IFDIR;
3883
3884 buf->st_nlink = info.nNumberOfLinks;
3885 /* Might as well use file index to fake inode values, but this
3886 is not guaranteed to be unique unless we keep a handle open
3887 all the time (even then there are situations where it is
3888 not unique). Reputedly, there are at most 48 bits of info
3889 (on NTFS, presumably less on FAT). */
3890 fake_inode = info.nFileIndexHigh;
3891 fake_inode <<= 32;
3892 fake_inode += info.nFileIndexLow;
3893
3894 /* MSVC defines _ino_t to be short; other libc's might not. */
3895 if (sizeof (buf->st_ino) == 2)
3896 buf->st_ino = fake_inode ^ (fake_inode >> 16);
3897 else
3898 buf->st_ino = fake_inode;
3899
3900 /* Consider files to belong to current user.
3901 FIXME: this should use GetSecurityInfo API, but it is only
3902 available for _WIN32_WINNT >= 0x501. */
3903 buf->st_uid = dflt_passwd.pw_uid;
3904 buf->st_gid = dflt_passwd.pw_gid;
3905 strcpy (buf->st_uname, dflt_passwd.pw_name);
3906 strcpy (buf->st_gname, dflt_group.gr_name);
3907
3908 buf->st_dev = info.dwVolumeSerialNumber;
3909 buf->st_rdev = info.dwVolumeSerialNumber;
3910
3911 buf->st_size = info.nFileSizeHigh;
3912 buf->st_size <<= 32;
3913 buf->st_size += info.nFileSizeLow;
3914
3915 /* Convert timestamps to Unix format. */
3916 buf->st_mtime = convert_time (info.ftLastWriteTime);
3917 buf->st_atime = convert_time (info.ftLastAccessTime);
3918 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3919 buf->st_ctime = convert_time (info.ftCreationTime);
3920 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3921
3922 /* determine rwx permissions */
3923 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
3924 permission = S_IREAD;
3925 else
3926 permission = S_IREAD | S_IWRITE;
3927
3928 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3929 permission |= S_IEXEC;
3930 else
3931 {
3932 #if 0 /* no way of knowing the filename */
3933 char * p = strrchr (name, '.');
3934 if (p != NULL &&
3935 (xstrcasecmp (p, ".exe") == 0 ||
3936 xstrcasecmp (p, ".com") == 0 ||
3937 xstrcasecmp (p, ".bat") == 0 ||
3938 xstrcasecmp (p, ".cmd") == 0))
3939 permission |= S_IEXEC;
3940 #endif
3941 }
3942
3943 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3944
3945 return 0;
3946 }
3947
3948 int
3949 utime (const char *name, struct utimbuf *times)
3950 {
3951 struct utimbuf deftime;
3952 HANDLE fh;
3953 FILETIME mtime;
3954 FILETIME atime;
3955
3956 if (times == NULL)
3957 {
3958 deftime.modtime = deftime.actime = time (NULL);
3959 times = &deftime;
3960 }
3961
3962 /* Need write access to set times. */
3963 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
3964 /* If NAME specifies a directory, FILE_SHARE_DELETE
3965 allows other processes to delete files inside it,
3966 while we have the directory open. */
3967 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3968 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
3969 if (fh != INVALID_HANDLE_VALUE)
3970 {
3971 convert_from_time_t (times->actime, &atime);
3972 convert_from_time_t (times->modtime, &mtime);
3973 if (!SetFileTime (fh, NULL, &atime, &mtime))
3974 {
3975 CloseHandle (fh);
3976 errno = EACCES;
3977 return -1;
3978 }
3979 CloseHandle (fh);
3980 }
3981 else
3982 {
3983 errno = EINVAL;
3984 return -1;
3985 }
3986 return 0;
3987 }
3988
3989 \f
3990 /* Symlink-related functions. */
3991 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
3992 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
3993 #endif
3994
3995 int
3996 symlink (char const *filename, char const *linkname)
3997 {
3998 char linkfn[MAX_PATH], *tgtfn;
3999 DWORD flags = 0;
4000 int dir_access, filename_ends_in_slash;
4001
4002 /* Diagnostics follows Posix as much as possible. */
4003 if (filename == NULL || linkname == NULL)
4004 {
4005 errno = EFAULT;
4006 return -1;
4007 }
4008 if (!*filename)
4009 {
4010 errno = ENOENT;
4011 return -1;
4012 }
4013 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4014 {
4015 errno = ENAMETOOLONG;
4016 return -1;
4017 }
4018
4019 strcpy (linkfn, map_w32_filename (linkname, NULL));
4020 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4021 {
4022 errno = EPERM;
4023 return -1;
4024 }
4025
4026 /* Note: since empty FILENAME was already rejected, we can safely
4027 refer to FILENAME[1]. */
4028 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4029 {
4030 /* Non-absolute FILENAME is understood as being relative to
4031 LINKNAME's directory. We need to prepend that directory to
4032 FILENAME to get correct results from faccessat below, since
4033 otherwise it will interpret FILENAME relative to the
4034 directory where the Emacs process runs. Note that
4035 make-symbolic-link always makes sure LINKNAME is a fully
4036 expanded file name. */
4037 char tem[MAX_PATH];
4038 char *p = linkfn + strlen (linkfn);
4039
4040 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4041 p--;
4042 if (p > linkfn)
4043 strncpy (tem, linkfn, p - linkfn);
4044 tem[p - linkfn] = '\0';
4045 strcat (tem, filename);
4046 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
4047 }
4048 else
4049 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
4050
4051 /* Since Windows distinguishes between symlinks to directories and
4052 to files, we provide a kludgy feature: if FILENAME doesn't
4053 exist, but ends in a slash, we create a symlink to directory. If
4054 FILENAME exists and is a directory, we always create a symlink to
4055 directory. */
4056 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4057 if (dir_access == 0 || filename_ends_in_slash)
4058 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4059
4060 tgtfn = (char *)map_w32_filename (filename, NULL);
4061 if (filename_ends_in_slash)
4062 tgtfn[strlen (tgtfn) - 1] = '\0';
4063
4064 errno = 0;
4065 if (!create_symbolic_link (linkfn, tgtfn, flags))
4066 {
4067 /* ENOSYS is set by create_symbolic_link, when it detects that
4068 the OS doesn't support the CreateSymbolicLink API. */
4069 if (errno != ENOSYS)
4070 {
4071 DWORD w32err = GetLastError ();
4072
4073 switch (w32err)
4074 {
4075 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4076 TGTFN point to the same file name, go figure. */
4077 case ERROR_SUCCESS:
4078 case ERROR_FILE_EXISTS:
4079 errno = EEXIST;
4080 break;
4081 case ERROR_ACCESS_DENIED:
4082 errno = EACCES;
4083 break;
4084 case ERROR_FILE_NOT_FOUND:
4085 case ERROR_PATH_NOT_FOUND:
4086 case ERROR_BAD_NETPATH:
4087 case ERROR_INVALID_REPARSE_DATA:
4088 errno = ENOENT;
4089 break;
4090 case ERROR_DIRECTORY:
4091 errno = EISDIR;
4092 break;
4093 case ERROR_PRIVILEGE_NOT_HELD:
4094 case ERROR_NOT_ALL_ASSIGNED:
4095 errno = EPERM;
4096 break;
4097 case ERROR_DISK_FULL:
4098 errno = ENOSPC;
4099 break;
4100 default:
4101 errno = EINVAL;
4102 break;
4103 }
4104 }
4105 return -1;
4106 }
4107 return 0;
4108 }
4109
4110 /* A quick inexpensive test of whether FILENAME identifies a file that
4111 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4112 must already be in the normalized form returned by
4113 map_w32_filename.
4114
4115 Note: for repeated operations on many files, it is best to test
4116 whether the underlying volume actually supports symlinks, by
4117 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4118 avoid the call to this function if it doesn't. That's because the
4119 call to GetFileAttributes takes a non-negligible time, especially
4120 on non-local or removable filesystems. See stat_worker for an
4121 example of how to do that. */
4122 static int
4123 is_symlink (const char *filename)
4124 {
4125 DWORD attrs;
4126 WIN32_FIND_DATA wfd;
4127 HANDLE fh;
4128
4129 attrs = GetFileAttributes (filename);
4130 if (attrs == -1)
4131 {
4132 DWORD w32err = GetLastError ();
4133
4134 switch (w32err)
4135 {
4136 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4137 break;
4138 case ERROR_ACCESS_DENIED:
4139 errno = EACCES;
4140 break;
4141 case ERROR_FILE_NOT_FOUND:
4142 case ERROR_PATH_NOT_FOUND:
4143 default:
4144 errno = ENOENT;
4145 break;
4146 }
4147 return 0;
4148 }
4149 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4150 return 0;
4151 logon_network_drive (filename);
4152 fh = FindFirstFile (filename, &wfd);
4153 if (fh == INVALID_HANDLE_VALUE)
4154 return 0;
4155 FindClose (fh);
4156 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4157 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4158 }
4159
4160 /* If NAME identifies a symbolic link, copy into BUF the file name of
4161 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4162 null-terminate the target name, even if it fits. Return the number
4163 of bytes copied, or -1 if NAME is not a symlink or any error was
4164 encountered while resolving it. The file name copied into BUF is
4165 encoded in the current ANSI codepage. */
4166 ssize_t
4167 readlink (const char *name, char *buf, size_t buf_size)
4168 {
4169 const char *path;
4170 TOKEN_PRIVILEGES privs;
4171 int restore_privs = 0;
4172 HANDLE sh;
4173 ssize_t retval;
4174
4175 if (name == NULL)
4176 {
4177 errno = EFAULT;
4178 return -1;
4179 }
4180 if (!*name)
4181 {
4182 errno = ENOENT;
4183 return -1;
4184 }
4185
4186 path = map_w32_filename (name, NULL);
4187
4188 if (strlen (path) > MAX_PATH)
4189 {
4190 errno = ENAMETOOLONG;
4191 return -1;
4192 }
4193
4194 errno = 0;
4195 if (is_windows_9x () == TRUE
4196 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4197 || !is_symlink (path))
4198 {
4199 if (!errno)
4200 errno = EINVAL; /* not a symlink */
4201 return -1;
4202 }
4203
4204 /* Done with simple tests, now we're in for some _real_ work. */
4205 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4206 restore_privs = 1;
4207 /* Implementation note: From here and onward, don't return early,
4208 since that will fail to restore the original set of privileges of
4209 the calling thread. */
4210
4211 retval = -1; /* not too optimistic, are we? */
4212
4213 /* Note: In the next call to CreateFile, we use zero as the 2nd
4214 argument because, when the symlink is a hidden/system file,
4215 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4216 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4217 and directory symlinks. */
4218 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4219 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4220 NULL);
4221 if (sh != INVALID_HANDLE_VALUE)
4222 {
4223 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4224 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4225 DWORD retbytes;
4226
4227 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4228 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4229 &retbytes, NULL))
4230 errno = EIO;
4231 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4232 errno = EINVAL;
4233 else
4234 {
4235 /* Copy the link target name, in wide characters, fro
4236 reparse_data, then convert it to multibyte encoding in
4237 the current locale's codepage. */
4238 WCHAR *lwname;
4239 BYTE lname[MAX_PATH];
4240 USHORT lname_len;
4241 USHORT lwname_len =
4242 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4243 WCHAR *lwname_src =
4244 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4245 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4246
4247 /* According to MSDN, PrintNameLength does not include the
4248 terminating null character. */
4249 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4250 memcpy (lwname, lwname_src, lwname_len);
4251 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4252
4253 /* FIXME: Should we use the current file-name coding system
4254 instead of the fixed value of the ANSI codepage? */
4255 lname_len = WideCharToMultiByte (w32_ansi_code_page, 0, lwname, -1,
4256 lname, MAX_PATH, NULL, NULL);
4257 if (!lname_len)
4258 {
4259 /* WideCharToMultiByte failed. */
4260 DWORD w32err1 = GetLastError ();
4261
4262 switch (w32err1)
4263 {
4264 case ERROR_INSUFFICIENT_BUFFER:
4265 errno = ENAMETOOLONG;
4266 break;
4267 case ERROR_INVALID_PARAMETER:
4268 errno = EFAULT;
4269 break;
4270 case ERROR_NO_UNICODE_TRANSLATION:
4271 errno = ENOENT;
4272 break;
4273 default:
4274 errno = EINVAL;
4275 break;
4276 }
4277 }
4278 else
4279 {
4280 size_t size_to_copy = buf_size;
4281 BYTE *p = lname;
4282 BYTE *pend = p + lname_len;
4283
4284 /* Normalize like dostounix_filename does, but we don't
4285 want to assume that lname is null-terminated. */
4286 if (*p && p[1] == ':' && *p >= 'A' && *p <= 'Z')
4287 *p += 'a' - 'A';
4288 while (p <= pend)
4289 {
4290 if (*p == '\\')
4291 *p = '/';
4292 ++p;
4293 }
4294 /* Testing for null-terminated LNAME is paranoia:
4295 WideCharToMultiByte should always return a
4296 null-terminated string when its 4th argument is -1
4297 and its 3rd argument is null-terminated (which they
4298 are, see above). */
4299 if (lname[lname_len - 1] == '\0')
4300 lname_len--;
4301 if (lname_len <= buf_size)
4302 size_to_copy = lname_len;
4303 strncpy (buf, lname, size_to_copy);
4304 /* Success! */
4305 retval = size_to_copy;
4306 }
4307 }
4308 CloseHandle (sh);
4309 }
4310 else
4311 {
4312 /* CreateFile failed. */
4313 DWORD w32err2 = GetLastError ();
4314
4315 switch (w32err2)
4316 {
4317 case ERROR_FILE_NOT_FOUND:
4318 case ERROR_PATH_NOT_FOUND:
4319 errno = ENOENT;
4320 break;
4321 case ERROR_ACCESS_DENIED:
4322 case ERROR_TOO_MANY_OPEN_FILES:
4323 errno = EACCES;
4324 break;
4325 default:
4326 errno = EPERM;
4327 break;
4328 }
4329 }
4330 if (restore_privs)
4331 {
4332 restore_privilege (&privs);
4333 revert_to_self ();
4334 }
4335
4336 return retval;
4337 }
4338
4339 /* If FILE is a symlink, return its target (stored in a static
4340 buffer); otherwise return FILE.
4341
4342 This function repeatedly resolves symlinks in the last component of
4343 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4344 until it arrives at a file whose last component is not a symlink,
4345 or some error occurs. It returns the target of the last
4346 successfully resolved symlink in the chain. If it succeeds to
4347 resolve even a single symlink, the value returned is an absolute
4348 file name with backslashes (result of GetFullPathName). By
4349 contrast, if the original FILE is returned, it is unaltered.
4350
4351 Note: This function can set errno even if it succeeds.
4352
4353 Implementation note: we only resolve the last portion ("basename")
4354 of the argument FILE and of each following file in the chain,
4355 disregarding any possible symlinks in its leading directories.
4356 This is because Windows system calls and library functions
4357 transparently resolve symlinks in leading directories and return
4358 correct information, as long as the basename is not a symlink. */
4359 static char *
4360 chase_symlinks (const char *file)
4361 {
4362 static char target[MAX_PATH];
4363 char link[MAX_PATH];
4364 ssize_t res, link_len;
4365 int loop_count = 0;
4366
4367 if (is_windows_9x () == TRUE || !is_symlink (file))
4368 return (char *)file;
4369
4370 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
4371 return (char *)file;
4372
4373 target[0] = '\0';
4374 do {
4375
4376 /* Remove trailing slashes, as we want to resolve the last
4377 non-trivial part of the link name. */
4378 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
4379 link[link_len--] = '\0';
4380
4381 res = readlink (link, target, MAX_PATH);
4382 if (res > 0)
4383 {
4384 target[res] = '\0';
4385 if (!(IS_DEVICE_SEP (target[1])
4386 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
4387 {
4388 /* Target is relative. Append it to the directory part of
4389 the symlink, then copy the result back to target. */
4390 char *p = link + link_len;
4391
4392 while (p > link && !IS_ANY_SEP (p[-1]))
4393 p--;
4394 strcpy (p, target);
4395 strcpy (target, link);
4396 }
4397 /* Resolve any "." and ".." to get a fully-qualified file name
4398 in link[] again. */
4399 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
4400 }
4401 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
4402
4403 if (loop_count > 100)
4404 errno = ELOOP;
4405
4406 if (target[0] == '\0') /* not a single call to readlink succeeded */
4407 return (char *)file;
4408 return target;
4409 }
4410
4411 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
4412 have a fixed max size for file names, so we don't need the kind of
4413 alloc/malloc/realloc dance the gnulib version does. We also don't
4414 support FD-relative symlinks. */
4415 char *
4416 careadlinkat (int fd, char const *filename,
4417 char *buffer, size_t buffer_size,
4418 struct allocator const *alloc,
4419 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
4420 {
4421 char linkname[MAX_PATH];
4422 ssize_t link_size;
4423
4424 if (fd != AT_FDCWD)
4425 {
4426 errno = EINVAL;
4427 return NULL;
4428 }
4429
4430 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
4431
4432 if (link_size > 0)
4433 {
4434 char *retval = buffer;
4435
4436 linkname[link_size++] = '\0';
4437 if (link_size > buffer_size)
4438 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
4439 if (retval)
4440 memcpy (retval, linkname, link_size);
4441
4442 return retval;
4443 }
4444 return NULL;
4445 }
4446
4447 ssize_t
4448 careadlinkatcwd (int fd, char const *filename, char *buffer,
4449 size_t buffer_size)
4450 {
4451 (void) fd;
4452 return readlink (filename, buffer, buffer_size);
4453 }
4454
4455 \f
4456 /* Support for browsing other processes and their attributes. See
4457 process.c for the Lisp bindings. */
4458
4459 /* Helper wrapper functions. */
4460
4461 static HANDLE WINAPI
4462 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
4463 {
4464 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
4465
4466 if (g_b_init_create_toolhelp32_snapshot == 0)
4467 {
4468 g_b_init_create_toolhelp32_snapshot = 1;
4469 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
4470 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4471 "CreateToolhelp32Snapshot");
4472 }
4473 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
4474 {
4475 return INVALID_HANDLE_VALUE;
4476 }
4477 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
4478 }
4479
4480 static BOOL WINAPI
4481 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
4482 {
4483 static Process32First_Proc s_pfn_Process32_First = NULL;
4484
4485 if (g_b_init_process32_first == 0)
4486 {
4487 g_b_init_process32_first = 1;
4488 s_pfn_Process32_First = (Process32First_Proc)
4489 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4490 "Process32First");
4491 }
4492 if (s_pfn_Process32_First == NULL)
4493 {
4494 return FALSE;
4495 }
4496 return (s_pfn_Process32_First (hSnapshot, lppe));
4497 }
4498
4499 static BOOL WINAPI
4500 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
4501 {
4502 static Process32Next_Proc s_pfn_Process32_Next = NULL;
4503
4504 if (g_b_init_process32_next == 0)
4505 {
4506 g_b_init_process32_next = 1;
4507 s_pfn_Process32_Next = (Process32Next_Proc)
4508 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4509 "Process32Next");
4510 }
4511 if (s_pfn_Process32_Next == NULL)
4512 {
4513 return FALSE;
4514 }
4515 return (s_pfn_Process32_Next (hSnapshot, lppe));
4516 }
4517
4518 static BOOL WINAPI
4519 open_thread_token (HANDLE ThreadHandle,
4520 DWORD DesiredAccess,
4521 BOOL OpenAsSelf,
4522 PHANDLE TokenHandle)
4523 {
4524 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
4525 HMODULE hm_advapi32 = NULL;
4526 if (is_windows_9x () == TRUE)
4527 {
4528 SetLastError (ERROR_NOT_SUPPORTED);
4529 return FALSE;
4530 }
4531 if (g_b_init_open_thread_token == 0)
4532 {
4533 g_b_init_open_thread_token = 1;
4534 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4535 s_pfn_Open_Thread_Token =
4536 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
4537 }
4538 if (s_pfn_Open_Thread_Token == NULL)
4539 {
4540 SetLastError (ERROR_NOT_SUPPORTED);
4541 return FALSE;
4542 }
4543 return (
4544 s_pfn_Open_Thread_Token (
4545 ThreadHandle,
4546 DesiredAccess,
4547 OpenAsSelf,
4548 TokenHandle)
4549 );
4550 }
4551
4552 static BOOL WINAPI
4553 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
4554 {
4555 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
4556 HMODULE hm_advapi32 = NULL;
4557 if (is_windows_9x () == TRUE)
4558 {
4559 return FALSE;
4560 }
4561 if (g_b_init_impersonate_self == 0)
4562 {
4563 g_b_init_impersonate_self = 1;
4564 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4565 s_pfn_Impersonate_Self =
4566 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
4567 }
4568 if (s_pfn_Impersonate_Self == NULL)
4569 {
4570 return FALSE;
4571 }
4572 return s_pfn_Impersonate_Self (ImpersonationLevel);
4573 }
4574
4575 static BOOL WINAPI
4576 revert_to_self (void)
4577 {
4578 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
4579 HMODULE hm_advapi32 = NULL;
4580 if (is_windows_9x () == TRUE)
4581 {
4582 return FALSE;
4583 }
4584 if (g_b_init_revert_to_self == 0)
4585 {
4586 g_b_init_revert_to_self = 1;
4587 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4588 s_pfn_Revert_To_Self =
4589 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
4590 }
4591 if (s_pfn_Revert_To_Self == NULL)
4592 {
4593 return FALSE;
4594 }
4595 return s_pfn_Revert_To_Self ();
4596 }
4597
4598 static BOOL WINAPI
4599 get_process_memory_info (HANDLE h_proc,
4600 PPROCESS_MEMORY_COUNTERS mem_counters,
4601 DWORD bufsize)
4602 {
4603 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
4604 HMODULE hm_psapi = NULL;
4605 if (is_windows_9x () == TRUE)
4606 {
4607 return FALSE;
4608 }
4609 if (g_b_init_get_process_memory_info == 0)
4610 {
4611 g_b_init_get_process_memory_info = 1;
4612 hm_psapi = LoadLibrary ("Psapi.dll");
4613 if (hm_psapi)
4614 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
4615 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
4616 }
4617 if (s_pfn_Get_Process_Memory_Info == NULL)
4618 {
4619 return FALSE;
4620 }
4621 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
4622 }
4623
4624 static BOOL WINAPI
4625 get_process_working_set_size (HANDLE h_proc,
4626 DWORD *minrss,
4627 DWORD *maxrss)
4628 {
4629 static GetProcessWorkingSetSize_Proc
4630 s_pfn_Get_Process_Working_Set_Size = NULL;
4631
4632 if (is_windows_9x () == TRUE)
4633 {
4634 return FALSE;
4635 }
4636 if (g_b_init_get_process_working_set_size == 0)
4637 {
4638 g_b_init_get_process_working_set_size = 1;
4639 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
4640 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4641 "GetProcessWorkingSetSize");
4642 }
4643 if (s_pfn_Get_Process_Working_Set_Size == NULL)
4644 {
4645 return FALSE;
4646 }
4647 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
4648 }
4649
4650 static BOOL WINAPI
4651 global_memory_status (MEMORYSTATUS *buf)
4652 {
4653 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
4654
4655 if (is_windows_9x () == TRUE)
4656 {
4657 return FALSE;
4658 }
4659 if (g_b_init_global_memory_status == 0)
4660 {
4661 g_b_init_global_memory_status = 1;
4662 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
4663 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4664 "GlobalMemoryStatus");
4665 }
4666 if (s_pfn_Global_Memory_Status == NULL)
4667 {
4668 return FALSE;
4669 }
4670 return s_pfn_Global_Memory_Status (buf);
4671 }
4672
4673 static BOOL WINAPI
4674 global_memory_status_ex (MEMORY_STATUS_EX *buf)
4675 {
4676 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
4677
4678 if (is_windows_9x () == TRUE)
4679 {
4680 return FALSE;
4681 }
4682 if (g_b_init_global_memory_status_ex == 0)
4683 {
4684 g_b_init_global_memory_status_ex = 1;
4685 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
4686 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4687 "GlobalMemoryStatusEx");
4688 }
4689 if (s_pfn_Global_Memory_Status_Ex == NULL)
4690 {
4691 return FALSE;
4692 }
4693 return s_pfn_Global_Memory_Status_Ex (buf);
4694 }
4695
4696 Lisp_Object
4697 list_system_processes (void)
4698 {
4699 struct gcpro gcpro1;
4700 Lisp_Object proclist = Qnil;
4701 HANDLE h_snapshot;
4702
4703 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4704
4705 if (h_snapshot != INVALID_HANDLE_VALUE)
4706 {
4707 PROCESSENTRY32 proc_entry;
4708 DWORD proc_id;
4709 BOOL res;
4710
4711 GCPRO1 (proclist);
4712
4713 proc_entry.dwSize = sizeof (PROCESSENTRY32);
4714 for (res = process32_first (h_snapshot, &proc_entry); res;
4715 res = process32_next (h_snapshot, &proc_entry))
4716 {
4717 proc_id = proc_entry.th32ProcessID;
4718 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
4719 }
4720
4721 CloseHandle (h_snapshot);
4722 UNGCPRO;
4723 proclist = Fnreverse (proclist);
4724 }
4725
4726 return proclist;
4727 }
4728
4729 static int
4730 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
4731 {
4732 TOKEN_PRIVILEGES priv;
4733 DWORD priv_size = sizeof (priv);
4734 DWORD opriv_size = sizeof (*old_priv);
4735 HANDLE h_token = NULL;
4736 HANDLE h_thread = GetCurrentThread ();
4737 int ret_val = 0;
4738 BOOL res;
4739
4740 res = open_thread_token (h_thread,
4741 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4742 FALSE, &h_token);
4743 if (!res && GetLastError () == ERROR_NO_TOKEN)
4744 {
4745 if (impersonate_self (SecurityImpersonation))
4746 res = open_thread_token (h_thread,
4747 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4748 FALSE, &h_token);
4749 }
4750 if (res)
4751 {
4752 priv.PrivilegeCount = 1;
4753 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
4754 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
4755 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
4756 old_priv, &opriv_size)
4757 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4758 ret_val = 1;
4759 }
4760 if (h_token)
4761 CloseHandle (h_token);
4762
4763 return ret_val;
4764 }
4765
4766 static int
4767 restore_privilege (TOKEN_PRIVILEGES *priv)
4768 {
4769 DWORD priv_size = sizeof (*priv);
4770 HANDLE h_token = NULL;
4771 int ret_val = 0;
4772
4773 if (open_thread_token (GetCurrentThread (),
4774 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4775 FALSE, &h_token))
4776 {
4777 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
4778 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4779 ret_val = 1;
4780 }
4781 if (h_token)
4782 CloseHandle (h_token);
4783
4784 return ret_val;
4785 }
4786
4787 static Lisp_Object
4788 ltime (ULONGLONG time_100ns)
4789 {
4790 ULONGLONG time_sec = time_100ns / 10000000;
4791 int subsec = time_100ns % 10000000;
4792 return list4 (make_number (time_sec >> 16),
4793 make_number (time_sec & 0xffff),
4794 make_number (subsec / 10),
4795 make_number (subsec % 10 * 100000));
4796 }
4797
4798 #define U64_TO_LISP_TIME(time) ltime (time)
4799
4800 static int
4801 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
4802 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
4803 double *pcpu)
4804 {
4805 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
4806 ULONGLONG tem1, tem2, tem3, tem;
4807
4808 if (!h_proc
4809 || !get_process_times_fn
4810 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
4811 &ft_kernel, &ft_user))
4812 return 0;
4813
4814 GetSystemTimeAsFileTime (&ft_current);
4815
4816 FILETIME_TO_U64 (tem1, ft_kernel);
4817 *stime = U64_TO_LISP_TIME (tem1);
4818
4819 FILETIME_TO_U64 (tem2, ft_user);
4820 *utime = U64_TO_LISP_TIME (tem2);
4821
4822 tem3 = tem1 + tem2;
4823 *ttime = U64_TO_LISP_TIME (tem3);
4824
4825 FILETIME_TO_U64 (tem, ft_creation);
4826 /* Process no 4 (System) returns zero creation time. */
4827 if (tem)
4828 tem -= utc_base;
4829 *ctime = U64_TO_LISP_TIME (tem);
4830
4831 if (tem)
4832 {
4833 FILETIME_TO_U64 (tem3, ft_current);
4834 tem = (tem3 - utc_base) - tem;
4835 }
4836 *etime = U64_TO_LISP_TIME (tem);
4837
4838 if (tem)
4839 {
4840 *pcpu = 100.0 * (tem1 + tem2) / tem;
4841 if (*pcpu > 100)
4842 *pcpu = 100.0;
4843 }
4844 else
4845 *pcpu = 0;
4846
4847 return 1;
4848 }
4849
4850 Lisp_Object
4851 system_process_attributes (Lisp_Object pid)
4852 {
4853 struct gcpro gcpro1, gcpro2, gcpro3;
4854 Lisp_Object attrs = Qnil;
4855 Lisp_Object cmd_str, decoded_cmd, tem;
4856 HANDLE h_snapshot, h_proc;
4857 DWORD proc_id;
4858 int found_proc = 0;
4859 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
4860 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
4861 DWORD glength = sizeof (gname);
4862 HANDLE token = NULL;
4863 SID_NAME_USE user_type;
4864 unsigned char *buf = NULL;
4865 DWORD blen = 0;
4866 TOKEN_USER user_token;
4867 TOKEN_PRIMARY_GROUP group_token;
4868 unsigned euid;
4869 unsigned egid;
4870 PROCESS_MEMORY_COUNTERS mem;
4871 PROCESS_MEMORY_COUNTERS_EX mem_ex;
4872 DWORD minrss, maxrss;
4873 MEMORYSTATUS memst;
4874 MEMORY_STATUS_EX memstex;
4875 double totphys = 0.0;
4876 Lisp_Object ctime, stime, utime, etime, ttime;
4877 double pcpu;
4878 BOOL result = FALSE;
4879
4880 CHECK_NUMBER_OR_FLOAT (pid);
4881 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
4882
4883 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4884
4885 GCPRO3 (attrs, decoded_cmd, tem);
4886
4887 if (h_snapshot != INVALID_HANDLE_VALUE)
4888 {
4889 PROCESSENTRY32 pe;
4890 BOOL res;
4891
4892 pe.dwSize = sizeof (PROCESSENTRY32);
4893 for (res = process32_first (h_snapshot, &pe); res;
4894 res = process32_next (h_snapshot, &pe))
4895 {
4896 if (proc_id == pe.th32ProcessID)
4897 {
4898 if (proc_id == 0)
4899 decoded_cmd = build_string ("Idle");
4900 else
4901 {
4902 /* Decode the command name from locale-specific
4903 encoding. */
4904 cmd_str = make_unibyte_string (pe.szExeFile,
4905 strlen (pe.szExeFile));
4906 decoded_cmd =
4907 code_convert_string_norecord (cmd_str,
4908 Vlocale_coding_system, 0);
4909 }
4910 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
4911 attrs = Fcons (Fcons (Qppid,
4912 make_fixnum_or_float (pe.th32ParentProcessID)),
4913 attrs);
4914 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
4915 attrs);
4916 attrs = Fcons (Fcons (Qthcount,
4917 make_fixnum_or_float (pe.cntThreads)),
4918 attrs);
4919 found_proc = 1;
4920 break;
4921 }
4922 }
4923
4924 CloseHandle (h_snapshot);
4925 }
4926
4927 if (!found_proc)
4928 {
4929 UNGCPRO;
4930 return Qnil;
4931 }
4932
4933 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4934 FALSE, proc_id);
4935 /* If we were denied a handle to the process, try again after
4936 enabling the SeDebugPrivilege in our process. */
4937 if (!h_proc)
4938 {
4939 TOKEN_PRIVILEGES priv_current;
4940
4941 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
4942 {
4943 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4944 FALSE, proc_id);
4945 restore_privilege (&priv_current);
4946 revert_to_self ();
4947 }
4948 }
4949 if (h_proc)
4950 {
4951 result = open_process_token (h_proc, TOKEN_QUERY, &token);
4952 if (result)
4953 {
4954 result = get_token_information (token, TokenUser, NULL, 0, &blen);
4955 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4956 {
4957 buf = xmalloc (blen);
4958 result = get_token_information (token, TokenUser,
4959 (LPVOID)buf, blen, &needed);
4960 if (result)
4961 {
4962 memcpy (&user_token, buf, sizeof (user_token));
4963 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
4964 {
4965 euid = get_rid (user_token.User.Sid);
4966 result = lookup_account_sid (NULL, user_token.User.Sid,
4967 uname, &ulength,
4968 domain, &dlength,
4969 &user_type);
4970 if (result)
4971 w32_add_to_cache (user_token.User.Sid, euid, uname);
4972 else
4973 {
4974 strcpy (uname, "unknown");
4975 result = TRUE;
4976 }
4977 }
4978 ulength = strlen (uname);
4979 }
4980 }
4981 }
4982 if (result)
4983 {
4984 /* Determine a reasonable euid and gid values. */
4985 if (xstrcasecmp ("administrator", uname) == 0)
4986 {
4987 euid = 500; /* well-known Administrator uid */
4988 egid = 513; /* well-known None gid */
4989 }
4990 else
4991 {
4992 /* Get group id and name. */
4993 result = get_token_information (token, TokenPrimaryGroup,
4994 (LPVOID)buf, blen, &needed);
4995 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4996 {
4997 buf = xrealloc (buf, blen = needed);
4998 result = get_token_information (token, TokenPrimaryGroup,
4999 (LPVOID)buf, blen, &needed);
5000 }
5001 if (result)
5002 {
5003 memcpy (&group_token, buf, sizeof (group_token));
5004 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
5005 {
5006 egid = get_rid (group_token.PrimaryGroup);
5007 dlength = sizeof (domain);
5008 result =
5009 lookup_account_sid (NULL, group_token.PrimaryGroup,
5010 gname, &glength, NULL, &dlength,
5011 &user_type);
5012 if (result)
5013 w32_add_to_cache (group_token.PrimaryGroup,
5014 egid, gname);
5015 else
5016 {
5017 strcpy (gname, "None");
5018 result = TRUE;
5019 }
5020 }
5021 glength = strlen (gname);
5022 }
5023 }
5024 }
5025 xfree (buf);
5026 }
5027 if (!result)
5028 {
5029 if (!is_windows_9x ())
5030 {
5031 /* We couldn't open the process token, presumably because of
5032 insufficient access rights. Assume this process is run
5033 by the system. */
5034 strcpy (uname, "SYSTEM");
5035 strcpy (gname, "None");
5036 euid = 18; /* SYSTEM */
5037 egid = 513; /* None */
5038 glength = strlen (gname);
5039 ulength = strlen (uname);
5040 }
5041 /* If we are running under Windows 9X, where security calls are
5042 not supported, we assume all processes are run by the current
5043 user. */
5044 else if (GetUserName (uname, &ulength))
5045 {
5046 if (xstrcasecmp ("administrator", uname) == 0)
5047 euid = 0;
5048 else
5049 euid = 123;
5050 egid = euid;
5051 strcpy (gname, "None");
5052 glength = strlen (gname);
5053 ulength = strlen (uname);
5054 }
5055 else
5056 {
5057 euid = 123;
5058 egid = 123;
5059 strcpy (uname, "administrator");
5060 ulength = strlen (uname);
5061 strcpy (gname, "None");
5062 glength = strlen (gname);
5063 }
5064 if (token)
5065 CloseHandle (token);
5066 }
5067
5068 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5069 tem = make_unibyte_string (uname, ulength);
5070 attrs = Fcons (Fcons (Quser,
5071 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5072 attrs);
5073 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5074 tem = make_unibyte_string (gname, glength);
5075 attrs = Fcons (Fcons (Qgroup,
5076 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5077 attrs);
5078
5079 if (global_memory_status_ex (&memstex))
5080 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5081 totphys = memstex.ullTotalPhys / 1024.0;
5082 #else
5083 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5084 double, so we need to do this for it... */
5085 {
5086 DWORD tot_hi = memstex.ullTotalPhys >> 32;
5087 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
5088 DWORD tot_lo = memstex.ullTotalPhys % 1024;
5089
5090 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
5091 }
5092 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5093 else if (global_memory_status (&memst))
5094 totphys = memst.dwTotalPhys / 1024.0;
5095
5096 if (h_proc
5097 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
5098 sizeof (mem_ex)))
5099 {
5100 DWORD rss = mem_ex.WorkingSetSize / 1024;
5101
5102 attrs = Fcons (Fcons (Qmajflt,
5103 make_fixnum_or_float (mem_ex.PageFaultCount)),
5104 attrs);
5105 attrs = Fcons (Fcons (Qvsize,
5106 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
5107 attrs);
5108 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5109 if (totphys)
5110 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5111 }
5112 else if (h_proc
5113 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
5114 {
5115 DWORD rss = mem_ex.WorkingSetSize / 1024;
5116
5117 attrs = Fcons (Fcons (Qmajflt,
5118 make_fixnum_or_float (mem.PageFaultCount)),
5119 attrs);
5120 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5121 if (totphys)
5122 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5123 }
5124 else if (h_proc
5125 && get_process_working_set_size (h_proc, &minrss, &maxrss))
5126 {
5127 DWORD rss = maxrss / 1024;
5128
5129 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
5130 if (totphys)
5131 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5132 }
5133
5134 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
5135 {
5136 attrs = Fcons (Fcons (Qutime, utime), attrs);
5137 attrs = Fcons (Fcons (Qstime, stime), attrs);
5138 attrs = Fcons (Fcons (Qtime, ttime), attrs);
5139 attrs = Fcons (Fcons (Qstart, ctime), attrs);
5140 attrs = Fcons (Fcons (Qetime, etime), attrs);
5141 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
5142 }
5143
5144 /* FIXME: Retrieve command line by walking the PEB of the process. */
5145
5146 if (h_proc)
5147 CloseHandle (h_proc);
5148 UNGCPRO;
5149 return attrs;
5150 }
5151
5152 \f
5153 /* Wrappers for winsock functions to map between our file descriptors
5154 and winsock's handles; also set h_errno for convenience.
5155
5156 To allow Emacs to run on systems which don't have winsock support
5157 installed, we dynamically link to winsock on startup if present, and
5158 otherwise provide the minimum necessary functionality
5159 (eg. gethostname). */
5160
5161 /* function pointers for relevant socket functions */
5162 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
5163 void (PASCAL *pfn_WSASetLastError) (int iError);
5164 int (PASCAL *pfn_WSAGetLastError) (void);
5165 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
5166 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
5167 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
5168 int (PASCAL *pfn_socket) (int af, int type, int protocol);
5169 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
5170 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
5171 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
5172 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
5173 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
5174 int (PASCAL *pfn_closesocket) (SOCKET s);
5175 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
5176 int (PASCAL *pfn_WSACleanup) (void);
5177
5178 u_short (PASCAL *pfn_htons) (u_short hostshort);
5179 u_short (PASCAL *pfn_ntohs) (u_short netshort);
5180 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
5181 int (PASCAL *pfn_gethostname) (char * name, int namelen);
5182 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
5183 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
5184 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
5185 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
5186 const char * optval, int optlen);
5187 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
5188 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
5189 int * namelen);
5190 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
5191 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
5192 struct sockaddr * from, int * fromlen);
5193 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
5194 const struct sockaddr * to, int tolen);
5195
5196 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5197 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
5198 #ifndef HANDLE_FLAG_INHERIT
5199 #define HANDLE_FLAG_INHERIT 1
5200 #endif
5201
5202 HANDLE winsock_lib;
5203 static int winsock_inuse;
5204
5205 BOOL
5206 term_winsock (void)
5207 {
5208 if (winsock_lib != NULL && winsock_inuse == 0)
5209 {
5210 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5211 after WSAStartup returns successfully, but it seems reasonable
5212 to allow unloading winsock anyway in that case. */
5213 if (pfn_WSACleanup () == 0 ||
5214 pfn_WSAGetLastError () == WSAENETDOWN)
5215 {
5216 if (FreeLibrary (winsock_lib))
5217 winsock_lib = NULL;
5218 return TRUE;
5219 }
5220 }
5221 return FALSE;
5222 }
5223
5224 BOOL
5225 init_winsock (int load_now)
5226 {
5227 WSADATA winsockData;
5228
5229 if (winsock_lib != NULL)
5230 return TRUE;
5231
5232 pfn_SetHandleInformation
5233 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
5234 "SetHandleInformation");
5235
5236 winsock_lib = LoadLibrary ("Ws2_32.dll");
5237
5238 if (winsock_lib != NULL)
5239 {
5240 /* dynamically link to socket functions */
5241
5242 #define LOAD_PROC(fn) \
5243 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
5244 goto fail;
5245
5246 LOAD_PROC (WSAStartup);
5247 LOAD_PROC (WSASetLastError);
5248 LOAD_PROC (WSAGetLastError);
5249 LOAD_PROC (WSAEventSelect);
5250 LOAD_PROC (WSACreateEvent);
5251 LOAD_PROC (WSACloseEvent);
5252 LOAD_PROC (socket);
5253 LOAD_PROC (bind);
5254 LOAD_PROC (connect);
5255 LOAD_PROC (ioctlsocket);
5256 LOAD_PROC (recv);
5257 LOAD_PROC (send);
5258 LOAD_PROC (closesocket);
5259 LOAD_PROC (shutdown);
5260 LOAD_PROC (htons);
5261 LOAD_PROC (ntohs);
5262 LOAD_PROC (inet_addr);
5263 LOAD_PROC (gethostname);
5264 LOAD_PROC (gethostbyname);
5265 LOAD_PROC (getservbyname);
5266 LOAD_PROC (getpeername);
5267 LOAD_PROC (WSACleanup);
5268 LOAD_PROC (setsockopt);
5269 LOAD_PROC (listen);
5270 LOAD_PROC (getsockname);
5271 LOAD_PROC (accept);
5272 LOAD_PROC (recvfrom);
5273 LOAD_PROC (sendto);
5274 #undef LOAD_PROC
5275
5276 /* specify version 1.1 of winsock */
5277 if (pfn_WSAStartup (0x101, &winsockData) == 0)
5278 {
5279 if (winsockData.wVersion != 0x101)
5280 goto fail;
5281
5282 if (!load_now)
5283 {
5284 /* Report that winsock exists and is usable, but leave
5285 socket functions disabled. I am assuming that calling
5286 WSAStartup does not require any network interaction,
5287 and in particular does not cause or require a dial-up
5288 connection to be established. */
5289
5290 pfn_WSACleanup ();
5291 FreeLibrary (winsock_lib);
5292 winsock_lib = NULL;
5293 }
5294 winsock_inuse = 0;
5295 return TRUE;
5296 }
5297
5298 fail:
5299 FreeLibrary (winsock_lib);
5300 winsock_lib = NULL;
5301 }
5302
5303 return FALSE;
5304 }
5305
5306
5307 int h_errno = 0;
5308
5309 /* function to set h_errno for compatibility; map winsock error codes to
5310 normal system codes where they overlap (non-overlapping definitions
5311 are already in <sys/socket.h> */
5312 static void
5313 set_errno (void)
5314 {
5315 if (winsock_lib == NULL)
5316 h_errno = EINVAL;
5317 else
5318 h_errno = pfn_WSAGetLastError ();
5319
5320 switch (h_errno)
5321 {
5322 case WSAEACCES: h_errno = EACCES; break;
5323 case WSAEBADF: h_errno = EBADF; break;
5324 case WSAEFAULT: h_errno = EFAULT; break;
5325 case WSAEINTR: h_errno = EINTR; break;
5326 case WSAEINVAL: h_errno = EINVAL; break;
5327 case WSAEMFILE: h_errno = EMFILE; break;
5328 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
5329 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
5330 }
5331 errno = h_errno;
5332 }
5333
5334 static void
5335 check_errno (void)
5336 {
5337 if (h_errno == 0 && winsock_lib != NULL)
5338 pfn_WSASetLastError (0);
5339 }
5340
5341 /* Extend strerror to handle the winsock-specific error codes. */
5342 struct {
5343 int errnum;
5344 char * msg;
5345 } _wsa_errlist[] = {
5346 {WSAEINTR , "Interrupted function call"},
5347 {WSAEBADF , "Bad file descriptor"},
5348 {WSAEACCES , "Permission denied"},
5349 {WSAEFAULT , "Bad address"},
5350 {WSAEINVAL , "Invalid argument"},
5351 {WSAEMFILE , "Too many open files"},
5352
5353 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
5354 {WSAEINPROGRESS , "Operation now in progress"},
5355 {WSAEALREADY , "Operation already in progress"},
5356 {WSAENOTSOCK , "Socket operation on non-socket"},
5357 {WSAEDESTADDRREQ , "Destination address required"},
5358 {WSAEMSGSIZE , "Message too long"},
5359 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
5360 {WSAENOPROTOOPT , "Bad protocol option"},
5361 {WSAEPROTONOSUPPORT , "Protocol not supported"},
5362 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
5363 {WSAEOPNOTSUPP , "Operation not supported"},
5364 {WSAEPFNOSUPPORT , "Protocol family not supported"},
5365 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
5366 {WSAEADDRINUSE , "Address already in use"},
5367 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
5368 {WSAENETDOWN , "Network is down"},
5369 {WSAENETUNREACH , "Network is unreachable"},
5370 {WSAENETRESET , "Network dropped connection on reset"},
5371 {WSAECONNABORTED , "Software caused connection abort"},
5372 {WSAECONNRESET , "Connection reset by peer"},
5373 {WSAENOBUFS , "No buffer space available"},
5374 {WSAEISCONN , "Socket is already connected"},
5375 {WSAENOTCONN , "Socket is not connected"},
5376 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
5377 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
5378 {WSAETIMEDOUT , "Connection timed out"},
5379 {WSAECONNREFUSED , "Connection refused"},
5380 {WSAELOOP , "Network loop"}, /* not sure */
5381 {WSAENAMETOOLONG , "Name is too long"},
5382 {WSAEHOSTDOWN , "Host is down"},
5383 {WSAEHOSTUNREACH , "No route to host"},
5384 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
5385 {WSAEPROCLIM , "Too many processes"},
5386 {WSAEUSERS , "Too many users"}, /* not sure */
5387 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
5388 {WSAESTALE , "Data is stale"}, /* not sure */
5389 {WSAEREMOTE , "Remote error"}, /* not sure */
5390
5391 {WSASYSNOTREADY , "Network subsystem is unavailable"},
5392 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
5393 {WSANOTINITIALISED , "Winsock not initialized successfully"},
5394 {WSAEDISCON , "Graceful shutdown in progress"},
5395 #ifdef WSAENOMORE
5396 {WSAENOMORE , "No more operations allowed"}, /* not sure */
5397 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
5398 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
5399 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
5400 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
5401 {WSASYSCALLFAILURE , "System call failure"},
5402 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
5403 {WSATYPE_NOT_FOUND , "Class type not found"},
5404 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
5405 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
5406 {WSAEREFUSED , "Operation refused"}, /* not sure */
5407 #endif
5408
5409 {WSAHOST_NOT_FOUND , "Host not found"},
5410 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
5411 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
5412 {WSANO_DATA , "Valid name, no data record of requested type"},
5413
5414 {-1, NULL}
5415 };
5416
5417 char *
5418 sys_strerror (int error_no)
5419 {
5420 int i;
5421 static char unknown_msg[40];
5422
5423 if (error_no >= 0 && error_no < sys_nerr)
5424 return sys_errlist[error_no];
5425
5426 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
5427 if (_wsa_errlist[i].errnum == error_no)
5428 return _wsa_errlist[i].msg;
5429
5430 sprintf (unknown_msg, "Unidentified error: %d", error_no);
5431 return unknown_msg;
5432 }
5433
5434 /* [andrewi 3-May-96] I've had conflicting results using both methods,
5435 but I believe the method of keeping the socket handle separate (and
5436 insuring it is not inheritable) is the correct one. */
5437
5438 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
5439
5440 static int socket_to_fd (SOCKET s);
5441
5442 int
5443 sys_socket (int af, int type, int protocol)
5444 {
5445 SOCKET s;
5446
5447 if (winsock_lib == NULL)
5448 {
5449 h_errno = ENETDOWN;
5450 return INVALID_SOCKET;
5451 }
5452
5453 check_errno ();
5454
5455 /* call the real socket function */
5456 s = pfn_socket (af, type, protocol);
5457
5458 if (s != INVALID_SOCKET)
5459 return socket_to_fd (s);
5460
5461 set_errno ();
5462 return -1;
5463 }
5464
5465 /* Convert a SOCKET to a file descriptor. */
5466 static int
5467 socket_to_fd (SOCKET s)
5468 {
5469 int fd;
5470 child_process * cp;
5471
5472 /* Although under NT 3.5 _open_osfhandle will accept a socket
5473 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
5474 that does not work under NT 3.1. However, we can get the same
5475 effect by using a backdoor function to replace an existing
5476 descriptor handle with the one we want. */
5477
5478 /* allocate a file descriptor (with appropriate flags) */
5479 fd = _open ("NUL:", _O_RDWR);
5480 if (fd >= 0)
5481 {
5482 /* Make a non-inheritable copy of the socket handle. Note
5483 that it is possible that sockets aren't actually kernel
5484 handles, which appears to be the case on Windows 9x when
5485 the MS Proxy winsock client is installed. */
5486 {
5487 /* Apparently there is a bug in NT 3.51 with some service
5488 packs, which prevents using DuplicateHandle to make a
5489 socket handle non-inheritable (causes WSACleanup to
5490 hang). The work-around is to use SetHandleInformation
5491 instead if it is available and implemented. */
5492 if (pfn_SetHandleInformation)
5493 {
5494 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
5495 }
5496 else
5497 {
5498 HANDLE parent = GetCurrentProcess ();
5499 HANDLE new_s = INVALID_HANDLE_VALUE;
5500
5501 if (DuplicateHandle (parent,
5502 (HANDLE) s,
5503 parent,
5504 &new_s,
5505 0,
5506 FALSE,
5507 DUPLICATE_SAME_ACCESS))
5508 {
5509 /* It is possible that DuplicateHandle succeeds even
5510 though the socket wasn't really a kernel handle,
5511 because a real handle has the same value. So
5512 test whether the new handle really is a socket. */
5513 long nonblocking = 0;
5514 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
5515 {
5516 pfn_closesocket (s);
5517 s = (SOCKET) new_s;
5518 }
5519 else
5520 {
5521 CloseHandle (new_s);
5522 }
5523 }
5524 }
5525 }
5526 fd_info[fd].hnd = (HANDLE) s;
5527
5528 /* set our own internal flags */
5529 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
5530
5531 cp = new_child ();
5532 if (cp)
5533 {
5534 cp->fd = fd;
5535 cp->status = STATUS_READ_ACKNOWLEDGED;
5536
5537 /* attach child_process to fd_info */
5538 if (fd_info[ fd ].cp != NULL)
5539 {
5540 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
5541 emacs_abort ();
5542 }
5543
5544 fd_info[ fd ].cp = cp;
5545
5546 /* success! */
5547 winsock_inuse++; /* count open sockets */
5548 return fd;
5549 }
5550
5551 /* clean up */
5552 _close (fd);
5553 }
5554 pfn_closesocket (s);
5555 h_errno = EMFILE;
5556 return -1;
5557 }
5558
5559 int
5560 sys_bind (int s, const struct sockaddr * addr, int namelen)
5561 {
5562 if (winsock_lib == NULL)
5563 {
5564 h_errno = ENOTSOCK;
5565 return SOCKET_ERROR;
5566 }
5567
5568 check_errno ();
5569 if (fd_info[s].flags & FILE_SOCKET)
5570 {
5571 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
5572 if (rc == SOCKET_ERROR)
5573 set_errno ();
5574 return rc;
5575 }
5576 h_errno = ENOTSOCK;
5577 return SOCKET_ERROR;
5578 }
5579
5580 int
5581 sys_connect (int s, const struct sockaddr * name, int namelen)
5582 {
5583 if (winsock_lib == NULL)
5584 {
5585 h_errno = ENOTSOCK;
5586 return SOCKET_ERROR;
5587 }
5588
5589 check_errno ();
5590 if (fd_info[s].flags & FILE_SOCKET)
5591 {
5592 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
5593 if (rc == SOCKET_ERROR)
5594 set_errno ();
5595 return rc;
5596 }
5597 h_errno = ENOTSOCK;
5598 return SOCKET_ERROR;
5599 }
5600
5601 u_short
5602 sys_htons (u_short hostshort)
5603 {
5604 return (winsock_lib != NULL) ?
5605 pfn_htons (hostshort) : hostshort;
5606 }
5607
5608 u_short
5609 sys_ntohs (u_short netshort)
5610 {
5611 return (winsock_lib != NULL) ?
5612 pfn_ntohs (netshort) : netshort;
5613 }
5614
5615 unsigned long
5616 sys_inet_addr (const char * cp)
5617 {
5618 return (winsock_lib != NULL) ?
5619 pfn_inet_addr (cp) : INADDR_NONE;
5620 }
5621
5622 int
5623 sys_gethostname (char * name, int namelen)
5624 {
5625 if (winsock_lib != NULL)
5626 return pfn_gethostname (name, namelen);
5627
5628 if (namelen > MAX_COMPUTERNAME_LENGTH)
5629 return !GetComputerName (name, (DWORD *)&namelen);
5630
5631 h_errno = EFAULT;
5632 return SOCKET_ERROR;
5633 }
5634
5635 struct hostent *
5636 sys_gethostbyname (const char * name)
5637 {
5638 struct hostent * host;
5639
5640 if (winsock_lib == NULL)
5641 {
5642 h_errno = ENETDOWN;
5643 return NULL;
5644 }
5645
5646 check_errno ();
5647 host = pfn_gethostbyname (name);
5648 if (!host)
5649 set_errno ();
5650 return host;
5651 }
5652
5653 struct servent *
5654 sys_getservbyname (const char * name, const char * proto)
5655 {
5656 struct servent * serv;
5657
5658 if (winsock_lib == NULL)
5659 {
5660 h_errno = ENETDOWN;
5661 return NULL;
5662 }
5663
5664 check_errno ();
5665 serv = pfn_getservbyname (name, proto);
5666 if (!serv)
5667 set_errno ();
5668 return serv;
5669 }
5670
5671 int
5672 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
5673 {
5674 if (winsock_lib == NULL)
5675 {
5676 h_errno = ENETDOWN;
5677 return SOCKET_ERROR;
5678 }
5679
5680 check_errno ();
5681 if (fd_info[s].flags & FILE_SOCKET)
5682 {
5683 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
5684 if (rc == SOCKET_ERROR)
5685 set_errno ();
5686 return rc;
5687 }
5688 h_errno = ENOTSOCK;
5689 return SOCKET_ERROR;
5690 }
5691
5692 int
5693 sys_shutdown (int s, int how)
5694 {
5695 if (winsock_lib == NULL)
5696 {
5697 h_errno = ENETDOWN;
5698 return SOCKET_ERROR;
5699 }
5700
5701 check_errno ();
5702 if (fd_info[s].flags & FILE_SOCKET)
5703 {
5704 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
5705 if (rc == SOCKET_ERROR)
5706 set_errno ();
5707 return rc;
5708 }
5709 h_errno = ENOTSOCK;
5710 return SOCKET_ERROR;
5711 }
5712
5713 int
5714 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
5715 {
5716 if (winsock_lib == NULL)
5717 {
5718 h_errno = ENETDOWN;
5719 return SOCKET_ERROR;
5720 }
5721
5722 check_errno ();
5723 if (fd_info[s].flags & FILE_SOCKET)
5724 {
5725 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
5726 (const char *)optval, optlen);
5727 if (rc == SOCKET_ERROR)
5728 set_errno ();
5729 return rc;
5730 }
5731 h_errno = ENOTSOCK;
5732 return SOCKET_ERROR;
5733 }
5734
5735 int
5736 sys_listen (int s, int backlog)
5737 {
5738 if (winsock_lib == NULL)
5739 {
5740 h_errno = ENETDOWN;
5741 return SOCKET_ERROR;
5742 }
5743
5744 check_errno ();
5745 if (fd_info[s].flags & FILE_SOCKET)
5746 {
5747 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
5748 if (rc == SOCKET_ERROR)
5749 set_errno ();
5750 else
5751 fd_info[s].flags |= FILE_LISTEN;
5752 return rc;
5753 }
5754 h_errno = ENOTSOCK;
5755 return SOCKET_ERROR;
5756 }
5757
5758 int
5759 sys_getsockname (int s, struct sockaddr * name, int * namelen)
5760 {
5761 if (winsock_lib == NULL)
5762 {
5763 h_errno = ENETDOWN;
5764 return SOCKET_ERROR;
5765 }
5766
5767 check_errno ();
5768 if (fd_info[s].flags & FILE_SOCKET)
5769 {
5770 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
5771 if (rc == SOCKET_ERROR)
5772 set_errno ();
5773 return rc;
5774 }
5775 h_errno = ENOTSOCK;
5776 return SOCKET_ERROR;
5777 }
5778
5779 int
5780 sys_accept (int s, struct sockaddr * addr, int * addrlen)
5781 {
5782 if (winsock_lib == NULL)
5783 {
5784 h_errno = ENETDOWN;
5785 return -1;
5786 }
5787
5788 check_errno ();
5789 if (fd_info[s].flags & FILE_LISTEN)
5790 {
5791 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
5792 int fd = -1;
5793 if (t == INVALID_SOCKET)
5794 set_errno ();
5795 else
5796 fd = socket_to_fd (t);
5797
5798 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
5799 ResetEvent (fd_info[s].cp->char_avail);
5800 return fd;
5801 }
5802 h_errno = ENOTSOCK;
5803 return -1;
5804 }
5805
5806 int
5807 sys_recvfrom (int s, char * buf, int len, int flags,
5808 struct sockaddr * from, int * fromlen)
5809 {
5810 if (winsock_lib == NULL)
5811 {
5812 h_errno = ENETDOWN;
5813 return SOCKET_ERROR;
5814 }
5815
5816 check_errno ();
5817 if (fd_info[s].flags & FILE_SOCKET)
5818 {
5819 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
5820 if (rc == SOCKET_ERROR)
5821 set_errno ();
5822 return rc;
5823 }
5824 h_errno = ENOTSOCK;
5825 return SOCKET_ERROR;
5826 }
5827
5828 int
5829 sys_sendto (int s, const char * buf, int len, int flags,
5830 const struct sockaddr * to, int tolen)
5831 {
5832 if (winsock_lib == NULL)
5833 {
5834 h_errno = ENETDOWN;
5835 return SOCKET_ERROR;
5836 }
5837
5838 check_errno ();
5839 if (fd_info[s].flags & FILE_SOCKET)
5840 {
5841 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
5842 if (rc == SOCKET_ERROR)
5843 set_errno ();
5844 return rc;
5845 }
5846 h_errno = ENOTSOCK;
5847 return SOCKET_ERROR;
5848 }
5849
5850 /* Windows does not have an fcntl function. Provide an implementation
5851 solely for making sockets non-blocking. */
5852 int
5853 fcntl (int s, int cmd, int options)
5854 {
5855 if (winsock_lib == NULL)
5856 {
5857 h_errno = ENETDOWN;
5858 return -1;
5859 }
5860
5861 check_errno ();
5862 if (fd_info[s].flags & FILE_SOCKET)
5863 {
5864 if (cmd == F_SETFL && options == O_NONBLOCK)
5865 {
5866 unsigned long nblock = 1;
5867 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
5868 if (rc == SOCKET_ERROR)
5869 set_errno ();
5870 /* Keep track of the fact that we set this to non-blocking. */
5871 fd_info[s].flags |= FILE_NDELAY;
5872 return rc;
5873 }
5874 else
5875 {
5876 h_errno = EINVAL;
5877 return SOCKET_ERROR;
5878 }
5879 }
5880 h_errno = ENOTSOCK;
5881 return SOCKET_ERROR;
5882 }
5883
5884
5885 /* Shadow main io functions: we need to handle pipes and sockets more
5886 intelligently, and implement non-blocking mode as well. */
5887
5888 int
5889 sys_close (int fd)
5890 {
5891 int rc;
5892
5893 if (fd < 0)
5894 {
5895 errno = EBADF;
5896 return -1;
5897 }
5898
5899 if (fd < MAXDESC && fd_info[fd].cp)
5900 {
5901 child_process * cp = fd_info[fd].cp;
5902
5903 fd_info[fd].cp = NULL;
5904
5905 if (CHILD_ACTIVE (cp))
5906 {
5907 /* if last descriptor to active child_process then cleanup */
5908 int i;
5909 for (i = 0; i < MAXDESC; i++)
5910 {
5911 if (i == fd)
5912 continue;
5913 if (fd_info[i].cp == cp)
5914 break;
5915 }
5916 if (i == MAXDESC)
5917 {
5918 if (fd_info[fd].flags & FILE_SOCKET)
5919 {
5920 if (winsock_lib == NULL) emacs_abort ();
5921
5922 pfn_shutdown (SOCK_HANDLE (fd), 2);
5923 rc = pfn_closesocket (SOCK_HANDLE (fd));
5924
5925 winsock_inuse--; /* count open sockets */
5926 }
5927 delete_child (cp);
5928 }
5929 }
5930 }
5931
5932 /* Note that sockets do not need special treatment here (at least on
5933 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5934 closesocket is equivalent to CloseHandle, which is to be expected
5935 because socket handles are fully fledged kernel handles. */
5936 rc = _close (fd);
5937
5938 if (rc == 0 && fd < MAXDESC)
5939 fd_info[fd].flags = 0;
5940
5941 return rc;
5942 }
5943
5944 int
5945 sys_dup (int fd)
5946 {
5947 int new_fd;
5948
5949 new_fd = _dup (fd);
5950 if (new_fd >= 0 && new_fd < MAXDESC)
5951 {
5952 /* duplicate our internal info as well */
5953 fd_info[new_fd] = fd_info[fd];
5954 }
5955 return new_fd;
5956 }
5957
5958 int
5959 sys_dup2 (int src, int dst)
5960 {
5961 int rc;
5962
5963 if (dst < 0 || dst >= MAXDESC)
5964 {
5965 errno = EBADF;
5966 return -1;
5967 }
5968
5969 /* make sure we close the destination first if it's a pipe or socket */
5970 if (src != dst && fd_info[dst].flags != 0)
5971 sys_close (dst);
5972
5973 rc = _dup2 (src, dst);
5974 if (rc == 0)
5975 {
5976 /* duplicate our internal info as well */
5977 fd_info[dst] = fd_info[src];
5978 }
5979 return rc;
5980 }
5981
5982 /* Unix pipe() has only one arg */
5983 int
5984 sys_pipe (int * phandles)
5985 {
5986 int rc;
5987 unsigned flags;
5988
5989 /* make pipe handles non-inheritable; when we spawn a child, we
5990 replace the relevant handle with an inheritable one. Also put
5991 pipes into binary mode; we will do text mode translation ourselves
5992 if required. */
5993 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
5994
5995 if (rc == 0)
5996 {
5997 /* Protect against overflow, since Windows can open more handles than
5998 our fd_info array has room for. */
5999 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
6000 {
6001 _close (phandles[0]);
6002 _close (phandles[1]);
6003 rc = -1;
6004 }
6005 else
6006 {
6007 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
6008 fd_info[phandles[0]].flags = flags;
6009
6010 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6011 fd_info[phandles[1]].flags = flags;
6012 }
6013 }
6014
6015 return rc;
6016 }
6017
6018 /* Function to do blocking read of one byte, needed to implement
6019 select. It is only allowed on sockets and pipes. */
6020 int
6021 _sys_read_ahead (int fd)
6022 {
6023 child_process * cp;
6024 int rc;
6025
6026 if (fd < 0 || fd >= MAXDESC)
6027 return STATUS_READ_ERROR;
6028
6029 cp = fd_info[fd].cp;
6030
6031 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6032 return STATUS_READ_ERROR;
6033
6034 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6035 || (fd_info[fd].flags & FILE_READ) == 0)
6036 {
6037 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
6038 emacs_abort ();
6039 }
6040
6041 cp->status = STATUS_READ_IN_PROGRESS;
6042
6043 if (fd_info[fd].flags & FILE_PIPE)
6044 {
6045 rc = _read (fd, &cp->chr, sizeof (char));
6046
6047 /* Give subprocess time to buffer some more output for us before
6048 reporting that input is available; we need this because Windows 95
6049 connects DOS programs to pipes by making the pipe appear to be
6050 the normal console stdout - as a result most DOS programs will
6051 write to stdout without buffering, ie. one character at a
6052 time. Even some W32 programs do this - "dir" in a command
6053 shell on NT is very slow if we don't do this. */
6054 if (rc > 0)
6055 {
6056 int wait = w32_pipe_read_delay;
6057
6058 if (wait > 0)
6059 Sleep (wait);
6060 else if (wait < 0)
6061 while (++wait <= 0)
6062 /* Yield remainder of our time slice, effectively giving a
6063 temporary priority boost to the child process. */
6064 Sleep (0);
6065 }
6066 }
6067 else if (fd_info[fd].flags & FILE_SERIAL)
6068 {
6069 HANDLE hnd = fd_info[fd].hnd;
6070 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6071 COMMTIMEOUTS ct;
6072
6073 /* Configure timeouts for blocking read. */
6074 if (!GetCommTimeouts (hnd, &ct))
6075 return STATUS_READ_ERROR;
6076 ct.ReadIntervalTimeout = 0;
6077 ct.ReadTotalTimeoutMultiplier = 0;
6078 ct.ReadTotalTimeoutConstant = 0;
6079 if (!SetCommTimeouts (hnd, &ct))
6080 return STATUS_READ_ERROR;
6081
6082 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
6083 {
6084 if (GetLastError () != ERROR_IO_PENDING)
6085 return STATUS_READ_ERROR;
6086 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6087 return STATUS_READ_ERROR;
6088 }
6089 }
6090 else if (fd_info[fd].flags & FILE_SOCKET)
6091 {
6092 unsigned long nblock = 0;
6093 /* We always want this to block, so temporarily disable NDELAY. */
6094 if (fd_info[fd].flags & FILE_NDELAY)
6095 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6096
6097 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
6098
6099 if (fd_info[fd].flags & FILE_NDELAY)
6100 {
6101 nblock = 1;
6102 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6103 }
6104 }
6105
6106 if (rc == sizeof (char))
6107 cp->status = STATUS_READ_SUCCEEDED;
6108 else
6109 cp->status = STATUS_READ_FAILED;
6110
6111 return cp->status;
6112 }
6113
6114 int
6115 _sys_wait_accept (int fd)
6116 {
6117 HANDLE hEv;
6118 child_process * cp;
6119 int rc;
6120
6121 if (fd < 0 || fd >= MAXDESC)
6122 return STATUS_READ_ERROR;
6123
6124 cp = fd_info[fd].cp;
6125
6126 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6127 return STATUS_READ_ERROR;
6128
6129 cp->status = STATUS_READ_FAILED;
6130
6131 hEv = pfn_WSACreateEvent ();
6132 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
6133 if (rc != SOCKET_ERROR)
6134 {
6135 rc = WaitForSingleObject (hEv, INFINITE);
6136 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
6137 if (rc == WAIT_OBJECT_0)
6138 cp->status = STATUS_READ_SUCCEEDED;
6139 }
6140 pfn_WSACloseEvent (hEv);
6141
6142 return cp->status;
6143 }
6144
6145 int
6146 sys_read (int fd, char * buffer, unsigned int count)
6147 {
6148 int nchars;
6149 int to_read;
6150 DWORD waiting;
6151 char * orig_buffer = buffer;
6152
6153 if (fd < 0)
6154 {
6155 errno = EBADF;
6156 return -1;
6157 }
6158
6159 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
6160 {
6161 child_process *cp = fd_info[fd].cp;
6162
6163 if ((fd_info[fd].flags & FILE_READ) == 0)
6164 {
6165 errno = EBADF;
6166 return -1;
6167 }
6168
6169 nchars = 0;
6170
6171 /* re-read CR carried over from last read */
6172 if (fd_info[fd].flags & FILE_LAST_CR)
6173 {
6174 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
6175 *buffer++ = 0x0d;
6176 count--;
6177 nchars++;
6178 fd_info[fd].flags &= ~FILE_LAST_CR;
6179 }
6180
6181 /* presence of a child_process structure means we are operating in
6182 non-blocking mode - otherwise we just call _read directly.
6183 Note that the child_process structure might be missing because
6184 reap_subprocess has been called; in this case the pipe is
6185 already broken, so calling _read on it is okay. */
6186 if (cp)
6187 {
6188 int current_status = cp->status;
6189
6190 switch (current_status)
6191 {
6192 case STATUS_READ_FAILED:
6193 case STATUS_READ_ERROR:
6194 /* report normal EOF if nothing in buffer */
6195 if (nchars <= 0)
6196 fd_info[fd].flags |= FILE_AT_EOF;
6197 return nchars;
6198
6199 case STATUS_READ_READY:
6200 case STATUS_READ_IN_PROGRESS:
6201 DebPrint (("sys_read called when read is in progress\n"));
6202 errno = EWOULDBLOCK;
6203 return -1;
6204
6205 case STATUS_READ_SUCCEEDED:
6206 /* consume read-ahead char */
6207 *buffer++ = cp->chr;
6208 count--;
6209 nchars++;
6210 cp->status = STATUS_READ_ACKNOWLEDGED;
6211 ResetEvent (cp->char_avail);
6212
6213 case STATUS_READ_ACKNOWLEDGED:
6214 break;
6215
6216 default:
6217 DebPrint (("sys_read: bad status %d\n", current_status));
6218 errno = EBADF;
6219 return -1;
6220 }
6221
6222 if (fd_info[fd].flags & FILE_PIPE)
6223 {
6224 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
6225 to_read = min (waiting, (DWORD) count);
6226
6227 if (to_read > 0)
6228 nchars += _read (fd, buffer, to_read);
6229 }
6230 else if (fd_info[fd].flags & FILE_SERIAL)
6231 {
6232 HANDLE hnd = fd_info[fd].hnd;
6233 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6234 int rc = 0;
6235 COMMTIMEOUTS ct;
6236
6237 if (count > 0)
6238 {
6239 /* Configure timeouts for non-blocking read. */
6240 if (!GetCommTimeouts (hnd, &ct))
6241 {
6242 errno = EIO;
6243 return -1;
6244 }
6245 ct.ReadIntervalTimeout = MAXDWORD;
6246 ct.ReadTotalTimeoutMultiplier = 0;
6247 ct.ReadTotalTimeoutConstant = 0;
6248 if (!SetCommTimeouts (hnd, &ct))
6249 {
6250 errno = EIO;
6251 return -1;
6252 }
6253
6254 if (!ResetEvent (ovl->hEvent))
6255 {
6256 errno = EIO;
6257 return -1;
6258 }
6259 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
6260 {
6261 if (GetLastError () != ERROR_IO_PENDING)
6262 {
6263 errno = EIO;
6264 return -1;
6265 }
6266 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6267 {
6268 errno = EIO;
6269 return -1;
6270 }
6271 }
6272 nchars += rc;
6273 }
6274 }
6275 else /* FILE_SOCKET */
6276 {
6277 if (winsock_lib == NULL) emacs_abort ();
6278
6279 /* do the equivalent of a non-blocking read */
6280 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
6281 if (waiting == 0 && nchars == 0)
6282 {
6283 h_errno = errno = EWOULDBLOCK;
6284 return -1;
6285 }
6286
6287 if (waiting)
6288 {
6289 /* always use binary mode for sockets */
6290 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
6291 if (res == SOCKET_ERROR)
6292 {
6293 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
6294 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
6295 set_errno ();
6296 return -1;
6297 }
6298 nchars += res;
6299 }
6300 }
6301 }
6302 else
6303 {
6304 int nread = _read (fd, buffer, count);
6305 if (nread >= 0)
6306 nchars += nread;
6307 else if (nchars == 0)
6308 nchars = nread;
6309 }
6310
6311 if (nchars <= 0)
6312 fd_info[fd].flags |= FILE_AT_EOF;
6313 /* Perform text mode translation if required. */
6314 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
6315 {
6316 nchars = crlf_to_lf (nchars, orig_buffer);
6317 /* If buffer contains only CR, return that. To be absolutely
6318 sure we should attempt to read the next char, but in
6319 practice a CR to be followed by LF would not appear by
6320 itself in the buffer. */
6321 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
6322 {
6323 fd_info[fd].flags |= FILE_LAST_CR;
6324 nchars--;
6325 }
6326 }
6327 }
6328 else
6329 nchars = _read (fd, buffer, count);
6330
6331 return nchars;
6332 }
6333
6334 /* From w32xfns.c */
6335 extern HANDLE interrupt_handle;
6336
6337 /* For now, don't bother with a non-blocking mode */
6338 int
6339 sys_write (int fd, const void * buffer, unsigned int count)
6340 {
6341 int nchars;
6342
6343 if (fd < 0)
6344 {
6345 errno = EBADF;
6346 return -1;
6347 }
6348
6349 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
6350 {
6351 if ((fd_info[fd].flags & FILE_WRITE) == 0)
6352 {
6353 errno = EBADF;
6354 return -1;
6355 }
6356
6357 /* Perform text mode translation if required. */
6358 if ((fd_info[fd].flags & FILE_BINARY) == 0)
6359 {
6360 char * tmpbuf = alloca (count * 2);
6361 unsigned char * src = (void *)buffer;
6362 unsigned char * dst = tmpbuf;
6363 int nbytes = count;
6364
6365 while (1)
6366 {
6367 unsigned char *next;
6368 /* copy next line or remaining bytes */
6369 next = _memccpy (dst, src, '\n', nbytes);
6370 if (next)
6371 {
6372 /* copied one line ending with '\n' */
6373 int copied = next - dst;
6374 nbytes -= copied;
6375 src += copied;
6376 /* insert '\r' before '\n' */
6377 next[-1] = '\r';
6378 next[0] = '\n';
6379 dst = next + 1;
6380 count++;
6381 }
6382 else
6383 /* copied remaining partial line -> now finished */
6384 break;
6385 }
6386 buffer = tmpbuf;
6387 }
6388 }
6389
6390 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
6391 {
6392 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
6393 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
6394 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
6395 DWORD active = 0;
6396
6397 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
6398 {
6399 if (GetLastError () != ERROR_IO_PENDING)
6400 {
6401 errno = EIO;
6402 return -1;
6403 }
6404 if (detect_input_pending ())
6405 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
6406 QS_ALLINPUT);
6407 else
6408 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
6409 if (active == WAIT_OBJECT_0)
6410 { /* User pressed C-g, cancel write, then leave. Don't bother
6411 cleaning up as we may only get stuck in buggy drivers. */
6412 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
6413 CancelIo (hnd);
6414 errno = EIO;
6415 return -1;
6416 }
6417 if (active == WAIT_OBJECT_0 + 1
6418 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
6419 {
6420 errno = EIO;
6421 return -1;
6422 }
6423 }
6424 }
6425 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
6426 {
6427 unsigned long nblock = 0;
6428 if (winsock_lib == NULL) emacs_abort ();
6429
6430 /* TODO: implement select() properly so non-blocking I/O works. */
6431 /* For now, make sure the write blocks. */
6432 if (fd_info[fd].flags & FILE_NDELAY)
6433 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6434
6435 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
6436
6437 /* Set the socket back to non-blocking if it was before,
6438 for other operations that support it. */
6439 if (fd_info[fd].flags & FILE_NDELAY)
6440 {
6441 nblock = 1;
6442 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6443 }
6444
6445 if (nchars == SOCKET_ERROR)
6446 {
6447 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
6448 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
6449 set_errno ();
6450 }
6451 }
6452 else
6453 {
6454 /* Some networked filesystems don't like too large writes, so
6455 break them into smaller chunks. See the Comments section of
6456 the MSDN documentation of WriteFile for details behind the
6457 choice of the value of CHUNK below. See also the thread
6458 http://thread.gmane.org/gmane.comp.version-control.git/145294
6459 in the git mailing list. */
6460 const unsigned char *p = buffer;
6461 const unsigned chunk = 30 * 1024 * 1024;
6462
6463 nchars = 0;
6464 while (count > 0)
6465 {
6466 unsigned this_chunk = count < chunk ? count : chunk;
6467 int n = _write (fd, p, this_chunk);
6468
6469 nchars += n;
6470 if (n < 0)
6471 {
6472 nchars = n;
6473 break;
6474 }
6475 else if (n < this_chunk)
6476 break;
6477 count -= n;
6478 p += n;
6479 }
6480 }
6481
6482 return nchars;
6483 }
6484
6485 /* The Windows CRT functions are "optimized for speed", so they don't
6486 check for timezone and DST changes if they were last called less
6487 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
6488 all Emacs features that repeatedly call time functions (e.g.,
6489 display-time) are in real danger of missing timezone and DST
6490 changes. Calling tzset before each localtime call fixes that. */
6491 struct tm *
6492 sys_localtime (const time_t *t)
6493 {
6494 tzset ();
6495 return localtime (t);
6496 }
6497
6498
6499 \f
6500 /* Try loading LIBRARY_ID from the file(s) specified in
6501 Vdynamic_library_alist. If the library is loaded successfully,
6502 return the handle of the DLL, and record the filename in the
6503 property :loaded-from of LIBRARY_ID. If the library could not be
6504 found, or when it was already loaded (because the handle is not
6505 recorded anywhere, and so is lost after use), return NULL.
6506
6507 We could also save the handle in :loaded-from, but currently
6508 there's no use case for it. */
6509 HMODULE
6510 w32_delayed_load (Lisp_Object library_id)
6511 {
6512 HMODULE library_dll = NULL;
6513
6514 CHECK_SYMBOL (library_id);
6515
6516 if (CONSP (Vdynamic_library_alist)
6517 && NILP (Fassq (library_id, Vlibrary_cache)))
6518 {
6519 Lisp_Object found = Qnil;
6520 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
6521
6522 if (CONSP (dlls))
6523 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
6524 {
6525 CHECK_STRING_CAR (dlls);
6526 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
6527 {
6528 char name[MAX_PATH];
6529 DWORD len;
6530
6531 len = GetModuleFileNameA (library_dll, name, sizeof (name));
6532 found = Fcons (XCAR (dlls),
6533 (len > 0)
6534 /* Possibly truncated */
6535 ? make_specified_string (name, -1, len, 1)
6536 : Qnil);
6537 break;
6538 }
6539 }
6540
6541 Fput (library_id, QCloaded_from, found);
6542 }
6543
6544 return library_dll;
6545 }
6546
6547 \f
6548 void
6549 check_windows_init_file (void)
6550 {
6551 /* A common indication that Emacs is not installed properly is when
6552 it cannot find the Windows installation file. If this file does
6553 not exist in the expected place, tell the user. */
6554
6555 if (!noninteractive && !inhibit_window_system
6556 /* Vload_path is not yet initialized when we are loading
6557 loadup.el. */
6558 && NILP (Vpurify_flag))
6559 {
6560 Lisp_Object init_file;
6561 int fd;
6562
6563 init_file = build_string ("term/w32-win");
6564 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
6565 if (fd < 0)
6566 {
6567 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
6568 char *init_file_name = SDATA (init_file);
6569 char *load_path = SDATA (load_path_print);
6570 char *buffer = alloca (1024
6571 + strlen (init_file_name)
6572 + strlen (load_path));
6573
6574 sprintf (buffer,
6575 "The Emacs Windows initialization file \"%s.el\" "
6576 "could not be found in your Emacs installation. "
6577 "Emacs checked the following directories for this file:\n"
6578 "\n%s\n\n"
6579 "When Emacs cannot find this file, it usually means that it "
6580 "was not installed properly, or its distribution file was "
6581 "not unpacked properly.\nSee the README.W32 file in the "
6582 "top-level Emacs directory for more information.",
6583 init_file_name, load_path);
6584 MessageBox (NULL,
6585 buffer,
6586 "Emacs Abort Dialog",
6587 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
6588 /* Use the low-level system abort. */
6589 abort ();
6590 }
6591 else
6592 {
6593 _close (fd);
6594 }
6595 }
6596 }
6597
6598 void
6599 term_ntproc (int ignored)
6600 {
6601 (void)ignored;
6602
6603 term_timers ();
6604
6605 /* shutdown the socket interface if necessary */
6606 term_winsock ();
6607
6608 term_w32select ();
6609 }
6610
6611 void
6612 init_ntproc (int dumping)
6613 {
6614 sigset_t initial_mask = 0;
6615
6616 /* Initialize the socket interface now if available and requested by
6617 the user by defining PRELOAD_WINSOCK; otherwise loading will be
6618 delayed until open-network-stream is called (w32-has-winsock can
6619 also be used to dynamically load or reload winsock).
6620
6621 Conveniently, init_environment is called before us, so
6622 PRELOAD_WINSOCK can be set in the registry. */
6623
6624 /* Always initialize this correctly. */
6625 winsock_lib = NULL;
6626
6627 if (getenv ("PRELOAD_WINSOCK") != NULL)
6628 init_winsock (TRUE);
6629
6630 /* Initial preparation for subprocess support: replace our standard
6631 handles with non-inheritable versions. */
6632 {
6633 HANDLE parent;
6634 HANDLE stdin_save = INVALID_HANDLE_VALUE;
6635 HANDLE stdout_save = INVALID_HANDLE_VALUE;
6636 HANDLE stderr_save = INVALID_HANDLE_VALUE;
6637
6638 parent = GetCurrentProcess ();
6639
6640 /* ignore errors when duplicating and closing; typically the
6641 handles will be invalid when running as a gui program. */
6642 DuplicateHandle (parent,
6643 GetStdHandle (STD_INPUT_HANDLE),
6644 parent,
6645 &stdin_save,
6646 0,
6647 FALSE,
6648 DUPLICATE_SAME_ACCESS);
6649
6650 DuplicateHandle (parent,
6651 GetStdHandle (STD_OUTPUT_HANDLE),
6652 parent,
6653 &stdout_save,
6654 0,
6655 FALSE,
6656 DUPLICATE_SAME_ACCESS);
6657
6658 DuplicateHandle (parent,
6659 GetStdHandle (STD_ERROR_HANDLE),
6660 parent,
6661 &stderr_save,
6662 0,
6663 FALSE,
6664 DUPLICATE_SAME_ACCESS);
6665
6666 fclose (stdin);
6667 fclose (stdout);
6668 fclose (stderr);
6669
6670 if (stdin_save != INVALID_HANDLE_VALUE)
6671 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
6672 else
6673 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
6674 _fdopen (0, "r");
6675
6676 if (stdout_save != INVALID_HANDLE_VALUE)
6677 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
6678 else
6679 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
6680 _fdopen (1, "w");
6681
6682 if (stderr_save != INVALID_HANDLE_VALUE)
6683 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
6684 else
6685 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
6686 _fdopen (2, "w");
6687 }
6688
6689 /* unfortunately, atexit depends on implementation of malloc */
6690 /* atexit (term_ntproc); */
6691 if (!dumping)
6692 {
6693 /* Make sure we start with all signals unblocked. */
6694 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
6695 signal (SIGABRT, term_ntproc);
6696 }
6697 init_timers ();
6698
6699 /* determine which drives are fixed, for GetCachedVolumeInformation */
6700 {
6701 /* GetDriveType must have trailing backslash. */
6702 char drive[] = "A:\\";
6703
6704 /* Loop over all possible drive letters */
6705 while (*drive <= 'Z')
6706 {
6707 /* Record if this drive letter refers to a fixed drive. */
6708 fixed_drives[DRIVE_INDEX (*drive)] =
6709 (GetDriveType (drive) == DRIVE_FIXED);
6710
6711 (*drive)++;
6712 }
6713
6714 /* Reset the volume info cache. */
6715 volume_cache = NULL;
6716 }
6717 }
6718
6719 /*
6720 shutdown_handler ensures that buffers' autosave files are
6721 up to date when the user logs off, or the system shuts down.
6722 */
6723 static BOOL WINAPI
6724 shutdown_handler (DWORD type)
6725 {
6726 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6727 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
6728 || type == CTRL_LOGOFF_EVENT /* User logs off. */
6729 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
6730 {
6731 /* Shut down cleanly, making sure autosave files are up to date. */
6732 shut_down_emacs (0, Qnil);
6733 }
6734
6735 /* Allow other handlers to handle this signal. */
6736 return FALSE;
6737 }
6738
6739 /*
6740 globals_of_w32 is used to initialize those global variables that
6741 must always be initialized on startup even when the global variable
6742 initialized is non zero (see the function main in emacs.c).
6743 */
6744 void
6745 globals_of_w32 (void)
6746 {
6747 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
6748
6749 get_process_times_fn = (GetProcessTimes_Proc)
6750 GetProcAddress (kernel32, "GetProcessTimes");
6751
6752 DEFSYM (QCloaded_from, ":loaded-from");
6753
6754 g_b_init_is_windows_9x = 0;
6755 g_b_init_open_process_token = 0;
6756 g_b_init_get_token_information = 0;
6757 g_b_init_lookup_account_sid = 0;
6758 g_b_init_get_sid_sub_authority = 0;
6759 g_b_init_get_sid_sub_authority_count = 0;
6760 g_b_init_get_security_info = 0;
6761 g_b_init_get_file_security = 0;
6762 g_b_init_get_security_descriptor_owner = 0;
6763 g_b_init_get_security_descriptor_group = 0;
6764 g_b_init_is_valid_sid = 0;
6765 g_b_init_create_toolhelp32_snapshot = 0;
6766 g_b_init_process32_first = 0;
6767 g_b_init_process32_next = 0;
6768 g_b_init_open_thread_token = 0;
6769 g_b_init_impersonate_self = 0;
6770 g_b_init_revert_to_self = 0;
6771 g_b_init_get_process_memory_info = 0;
6772 g_b_init_get_process_working_set_size = 0;
6773 g_b_init_global_memory_status = 0;
6774 g_b_init_global_memory_status_ex = 0;
6775 g_b_init_equal_sid = 0;
6776 g_b_init_copy_sid = 0;
6777 g_b_init_get_length_sid = 0;
6778 g_b_init_get_native_system_info = 0;
6779 g_b_init_get_system_times = 0;
6780 g_b_init_create_symbolic_link = 0;
6781 num_of_processors = 0;
6782 /* The following sets a handler for shutdown notifications for
6783 console apps. This actually applies to Emacs in both console and
6784 GUI modes, since we had to fool windows into thinking emacs is a
6785 console application to get console mode to work. */
6786 SetConsoleCtrlHandler (shutdown_handler, TRUE);
6787
6788 /* "None" is the default group name on standalone workstations. */
6789 strcpy (dflt_group_name, "None");
6790 }
6791
6792 /* For make-serial-process */
6793 int
6794 serial_open (char *port)
6795 {
6796 HANDLE hnd;
6797 child_process *cp;
6798 int fd = -1;
6799
6800 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
6801 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
6802 if (hnd == INVALID_HANDLE_VALUE)
6803 error ("Could not open %s", port);
6804 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
6805 if (fd == -1)
6806 error ("Could not open %s", port);
6807
6808 cp = new_child ();
6809 if (!cp)
6810 error ("Could not create child process");
6811 cp->fd = fd;
6812 cp->status = STATUS_READ_ACKNOWLEDGED;
6813 fd_info[ fd ].hnd = hnd;
6814 fd_info[ fd ].flags |=
6815 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
6816 if (fd_info[ fd ].cp != NULL)
6817 {
6818 error ("fd_info[fd = %d] is already in use", fd);
6819 }
6820 fd_info[ fd ].cp = cp;
6821 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6822 if (cp->ovl_read.hEvent == NULL)
6823 error ("Could not create read event");
6824 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6825 if (cp->ovl_write.hEvent == NULL)
6826 error ("Could not create write event");
6827
6828 return fd;
6829 }
6830
6831 /* For serial-process-configure */
6832 void
6833 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
6834 {
6835 Lisp_Object childp2 = Qnil;
6836 Lisp_Object tem = Qnil;
6837 HANDLE hnd;
6838 DCB dcb;
6839 COMMTIMEOUTS ct;
6840 char summary[4] = "???"; /* This usually becomes "8N1". */
6841
6842 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
6843 error ("Not a serial process");
6844 hnd = fd_info[ p->outfd ].hnd;
6845
6846 childp2 = Fcopy_sequence (p->childp);
6847
6848 /* Initialize timeouts for blocking read and blocking write. */
6849 if (!GetCommTimeouts (hnd, &ct))
6850 error ("GetCommTimeouts() failed");
6851 ct.ReadIntervalTimeout = 0;
6852 ct.ReadTotalTimeoutMultiplier = 0;
6853 ct.ReadTotalTimeoutConstant = 0;
6854 ct.WriteTotalTimeoutMultiplier = 0;
6855 ct.WriteTotalTimeoutConstant = 0;
6856 if (!SetCommTimeouts (hnd, &ct))
6857 error ("SetCommTimeouts() failed");
6858 /* Read port attributes and prepare default configuration. */
6859 memset (&dcb, 0, sizeof (dcb));
6860 dcb.DCBlength = sizeof (DCB);
6861 if (!GetCommState (hnd, &dcb))
6862 error ("GetCommState() failed");
6863 dcb.fBinary = TRUE;
6864 dcb.fNull = FALSE;
6865 dcb.fAbortOnError = FALSE;
6866 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6867 dcb.ErrorChar = 0;
6868 dcb.EofChar = 0;
6869 dcb.EvtChar = 0;
6870
6871 /* Configure speed. */
6872 if (!NILP (Fplist_member (contact, QCspeed)))
6873 tem = Fplist_get (contact, QCspeed);
6874 else
6875 tem = Fplist_get (p->childp, QCspeed);
6876 CHECK_NUMBER (tem);
6877 dcb.BaudRate = XINT (tem);
6878 childp2 = Fplist_put (childp2, QCspeed, tem);
6879
6880 /* Configure bytesize. */
6881 if (!NILP (Fplist_member (contact, QCbytesize)))
6882 tem = Fplist_get (contact, QCbytesize);
6883 else
6884 tem = Fplist_get (p->childp, QCbytesize);
6885 if (NILP (tem))
6886 tem = make_number (8);
6887 CHECK_NUMBER (tem);
6888 if (XINT (tem) != 7 && XINT (tem) != 8)
6889 error (":bytesize must be nil (8), 7, or 8");
6890 dcb.ByteSize = XINT (tem);
6891 summary[0] = XINT (tem) + '0';
6892 childp2 = Fplist_put (childp2, QCbytesize, tem);
6893
6894 /* Configure parity. */
6895 if (!NILP (Fplist_member (contact, QCparity)))
6896 tem = Fplist_get (contact, QCparity);
6897 else
6898 tem = Fplist_get (p->childp, QCparity);
6899 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
6900 error (":parity must be nil (no parity), `even', or `odd'");
6901 dcb.fParity = FALSE;
6902 dcb.Parity = NOPARITY;
6903 dcb.fErrorChar = FALSE;
6904 if (NILP (tem))
6905 {
6906 summary[1] = 'N';
6907 }
6908 else if (EQ (tem, Qeven))
6909 {
6910 summary[1] = 'E';
6911 dcb.fParity = TRUE;
6912 dcb.Parity = EVENPARITY;
6913 dcb.fErrorChar = TRUE;
6914 }
6915 else if (EQ (tem, Qodd))
6916 {
6917 summary[1] = 'O';
6918 dcb.fParity = TRUE;
6919 dcb.Parity = ODDPARITY;
6920 dcb.fErrorChar = TRUE;
6921 }
6922 childp2 = Fplist_put (childp2, QCparity, tem);
6923
6924 /* Configure stopbits. */
6925 if (!NILP (Fplist_member (contact, QCstopbits)))
6926 tem = Fplist_get (contact, QCstopbits);
6927 else
6928 tem = Fplist_get (p->childp, QCstopbits);
6929 if (NILP (tem))
6930 tem = make_number (1);
6931 CHECK_NUMBER (tem);
6932 if (XINT (tem) != 1 && XINT (tem) != 2)
6933 error (":stopbits must be nil (1 stopbit), 1, or 2");
6934 summary[2] = XINT (tem) + '0';
6935 if (XINT (tem) == 1)
6936 dcb.StopBits = ONESTOPBIT;
6937 else if (XINT (tem) == 2)
6938 dcb.StopBits = TWOSTOPBITS;
6939 childp2 = Fplist_put (childp2, QCstopbits, tem);
6940
6941 /* Configure flowcontrol. */
6942 if (!NILP (Fplist_member (contact, QCflowcontrol)))
6943 tem = Fplist_get (contact, QCflowcontrol);
6944 else
6945 tem = Fplist_get (p->childp, QCflowcontrol);
6946 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
6947 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6948 dcb.fOutxCtsFlow = FALSE;
6949 dcb.fOutxDsrFlow = FALSE;
6950 dcb.fDtrControl = DTR_CONTROL_DISABLE;
6951 dcb.fDsrSensitivity = FALSE;
6952 dcb.fTXContinueOnXoff = FALSE;
6953 dcb.fOutX = FALSE;
6954 dcb.fInX = FALSE;
6955 dcb.fRtsControl = RTS_CONTROL_DISABLE;
6956 dcb.XonChar = 17; /* Control-Q */
6957 dcb.XoffChar = 19; /* Control-S */
6958 if (NILP (tem))
6959 {
6960 /* Already configured. */
6961 }
6962 else if (EQ (tem, Qhw))
6963 {
6964 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
6965 dcb.fOutxCtsFlow = TRUE;
6966 }
6967 else if (EQ (tem, Qsw))
6968 {
6969 dcb.fOutX = TRUE;
6970 dcb.fInX = TRUE;
6971 }
6972 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
6973
6974 /* Activate configuration. */
6975 if (!SetCommState (hnd, &dcb))
6976 error ("SetCommState() failed");
6977
6978 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
6979 pset_childp (p, childp2);
6980 }
6981
6982 #ifdef HAVE_GNUTLS
6983
6984 ssize_t
6985 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
6986 {
6987 int n, sc, err;
6988 SELECT_TYPE fdset;
6989 EMACS_TIME timeout;
6990 struct Lisp_Process *process = (struct Lisp_Process *)p;
6991 int fd = process->infd;
6992
6993 for (;;)
6994 {
6995 n = sys_read (fd, (char*)buf, sz);
6996
6997 if (n >= 0)
6998 return n;
6999
7000 err = errno;
7001
7002 if (err == EWOULDBLOCK)
7003 {
7004 /* Set a small timeout. */
7005 timeout = make_emacs_time (1, 0);
7006 FD_ZERO (&fdset);
7007 FD_SET ((int)fd, &fdset);
7008
7009 /* Use select with the timeout to poll the selector. */
7010 sc = select (fd + 1, &fdset, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7011 &timeout, NULL);
7012
7013 if (sc > 0)
7014 continue; /* Try again. */
7015
7016 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
7017 Also accept select return 0 as an indicator to EAGAIN. */
7018 if (sc == 0 || errno == EWOULDBLOCK)
7019 err = EAGAIN;
7020 else
7021 err = errno; /* Other errors are just passed on. */
7022 }
7023
7024 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
7025
7026 return -1;
7027 }
7028 }
7029
7030 ssize_t
7031 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
7032 {
7033 struct Lisp_Process *process = (struct Lisp_Process *)p;
7034 int fd = process->outfd;
7035 ssize_t n = sys_write (fd, buf, sz);
7036
7037 /* 0 or more bytes written means everything went fine. */
7038 if (n >= 0)
7039 return n;
7040
7041 /* Negative bytes written means we got an error in errno.
7042 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7043 emacs_gnutls_transport_set_errno (process->gnutls_state,
7044 errno == EWOULDBLOCK ? EAGAIN : errno);
7045
7046 return -1;
7047 }
7048 #endif /* HAVE_GNUTLS */
7049
7050 /* end of w32.c */