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