* lisp/textmodes/table.el (table-insert): Don't use `symbol-name' on
[emacs.git] / src / w32.c
blob1c3331516d4f036d5b5474482613bdde7de3c128
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2012 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
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.
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.
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/>. */
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
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>
37 /* must include CRT headers *before* config.h */
39 #include <config.h>
40 #include <mbstring.h> /* for _mbspbrk */
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
56 #undef close
57 #undef dup
58 #undef dup2
59 #undef pipe
60 #undef read
61 #undef write
63 #undef strerror
65 #undef localtime
67 #include "lisp.h"
69 #include <pwd.h>
70 #include <grp.h>
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;
91 #include <lmcons.h>
92 #include <shlobj.h>
94 #include <tlhelp32.h>
95 #include <psapi.h>
96 #ifndef _MSC_VER
97 #include <w32api.h>
98 #endif
99 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100 /* This either is not in psapi.h or guarded by higher value of
101 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
102 defines it in psapi.h */
103 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
104 DWORD cb;
105 DWORD PageFaultCount;
106 DWORD PeakWorkingSetSize;
107 DWORD WorkingSetSize;
108 DWORD QuotaPeakPagedPoolUsage;
109 DWORD QuotaPagedPoolUsage;
110 DWORD QuotaPeakNonPagedPoolUsage;
111 DWORD QuotaNonPagedPoolUsage;
112 DWORD PagefileUsage;
113 DWORD PeakPagefileUsage;
114 DWORD PrivateUsage;
115 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
116 #endif
118 #include <winioctl.h>
119 #include <aclapi.h>
121 #ifdef _MSC_VER
122 /* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
123 associated macros, except on ntifs.h, which cannot be included
124 because it triggers conflicts with other Windows API headers. So
125 we define it here by hand. */
127 typedef struct _REPARSE_DATA_BUFFER {
128 ULONG ReparseTag;
129 USHORT ReparseDataLength;
130 USHORT Reserved;
131 union {
132 struct {
133 USHORT SubstituteNameOffset;
134 USHORT SubstituteNameLength;
135 USHORT PrintNameOffset;
136 USHORT PrintNameLength;
137 ULONG Flags;
138 WCHAR PathBuffer[1];
139 } SymbolicLinkReparseBuffer;
140 struct {
141 USHORT SubstituteNameOffset;
142 USHORT SubstituteNameLength;
143 USHORT PrintNameOffset;
144 USHORT PrintNameLength;
145 WCHAR PathBuffer[1];
146 } MountPointReparseBuffer;
147 struct {
148 UCHAR DataBuffer[1];
149 } GenericReparseBuffer;
150 } DUMMYUNIONNAME;
151 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
153 #define FILE_DEVICE_FILE_SYSTEM 9
154 #define METHOD_BUFFERED 0
155 #define FILE_ANY_ACCESS 0x00000000
156 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
157 #define FSCTL_GET_REPARSE_POINT \
158 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
159 #endif
161 /* TCP connection support. */
162 #include <sys/socket.h>
163 #undef socket
164 #undef bind
165 #undef connect
166 #undef htons
167 #undef ntohs
168 #undef inet_addr
169 #undef gethostname
170 #undef gethostbyname
171 #undef getservbyname
172 #undef getpeername
173 #undef shutdown
174 #undef setsockopt
175 #undef listen
176 #undef getsockname
177 #undef accept
178 #undef recvfrom
179 #undef sendto
181 #include "w32.h"
182 #include "ndir.h"
183 #include "w32common.h"
184 #include "w32heap.h"
185 #include "w32select.h"
186 #include "systime.h"
187 #include "dispextern.h" /* for xstrcasecmp */
188 #include "coding.h" /* for Vlocale_coding_system */
190 #include "careadlinkat.h"
191 #include "allocator.h"
193 /* For serial_configure and serial_open. */
194 #include "process.h"
196 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
197 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
199 Lisp_Object QCloaded_from;
201 void globals_of_w32 (void);
202 static DWORD get_rid (PSID);
203 static int is_symlink (const char *);
204 static char * chase_symlinks (const char *);
205 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
206 static int restore_privilege (TOKEN_PRIVILEGES *);
207 static BOOL WINAPI revert_to_self (void);
209 extern int sys_access (const char *, int);
210 extern void *e_malloc (size_t);
211 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
212 EMACS_TIME *, void *);
216 /* Initialization states.
218 WARNING: If you add any more such variables for additional APIs,
219 you MUST add initialization for them to globals_of_w32
220 below. This is because these variables might get set
221 to non-NULL values during dumping, but the dumped Emacs
222 cannot reuse those values, because it could be run on a
223 different version of the OS, where API addresses are
224 different. */
225 static BOOL g_b_init_is_windows_9x;
226 static BOOL g_b_init_open_process_token;
227 static BOOL g_b_init_get_token_information;
228 static BOOL g_b_init_lookup_account_sid;
229 static BOOL g_b_init_get_sid_sub_authority;
230 static BOOL g_b_init_get_sid_sub_authority_count;
231 static BOOL g_b_init_get_security_info;
232 static BOOL g_b_init_get_file_security;
233 static BOOL g_b_init_get_security_descriptor_owner;
234 static BOOL g_b_init_get_security_descriptor_group;
235 static BOOL g_b_init_is_valid_sid;
236 static BOOL g_b_init_create_toolhelp32_snapshot;
237 static BOOL g_b_init_process32_first;
238 static BOOL g_b_init_process32_next;
239 static BOOL g_b_init_open_thread_token;
240 static BOOL g_b_init_impersonate_self;
241 static BOOL g_b_init_revert_to_self;
242 static BOOL g_b_init_get_process_memory_info;
243 static BOOL g_b_init_get_process_working_set_size;
244 static BOOL g_b_init_global_memory_status;
245 static BOOL g_b_init_global_memory_status_ex;
246 static BOOL g_b_init_get_length_sid;
247 static BOOL g_b_init_equal_sid;
248 static BOOL g_b_init_copy_sid;
249 static BOOL g_b_init_get_native_system_info;
250 static BOOL g_b_init_get_system_times;
251 static BOOL g_b_init_create_symbolic_link;
254 BEGIN: Wrapper functions around OpenProcessToken
255 and other functions in advapi32.dll that are only
256 supported in Windows NT / 2k / XP
258 /* ** Function pointer typedefs ** */
259 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
260 HANDLE ProcessHandle,
261 DWORD DesiredAccess,
262 PHANDLE TokenHandle);
263 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
264 HANDLE TokenHandle,
265 TOKEN_INFORMATION_CLASS TokenInformationClass,
266 LPVOID TokenInformation,
267 DWORD TokenInformationLength,
268 PDWORD ReturnLength);
269 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
270 HANDLE process_handle,
271 LPFILETIME creation_time,
272 LPFILETIME exit_time,
273 LPFILETIME kernel_time,
274 LPFILETIME user_time);
276 GetProcessTimes_Proc get_process_times_fn = NULL;
278 #ifdef _UNICODE
279 const char * const LookupAccountSid_Name = "LookupAccountSidW";
280 const char * const GetFileSecurity_Name = "GetFileSecurityW";
281 #else
282 const char * const LookupAccountSid_Name = "LookupAccountSidA";
283 const char * const GetFileSecurity_Name = "GetFileSecurityA";
284 #endif
285 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
286 LPCTSTR lpSystemName,
287 PSID Sid,
288 LPTSTR Name,
289 LPDWORD cbName,
290 LPTSTR DomainName,
291 LPDWORD cbDomainName,
292 PSID_NAME_USE peUse);
293 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
294 PSID pSid,
295 DWORD n);
296 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
297 PSID pSid);
298 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
299 HANDLE handle,
300 SE_OBJECT_TYPE ObjectType,
301 SECURITY_INFORMATION SecurityInfo,
302 PSID *ppsidOwner,
303 PSID *ppsidGroup,
304 PACL *ppDacl,
305 PACL *ppSacl,
306 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
307 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
308 LPCTSTR lpFileName,
309 SECURITY_INFORMATION RequestedInformation,
310 PSECURITY_DESCRIPTOR pSecurityDescriptor,
311 DWORD nLength,
312 LPDWORD lpnLengthNeeded);
313 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
314 PSECURITY_DESCRIPTOR pSecurityDescriptor,
315 PSID *pOwner,
316 LPBOOL lpbOwnerDefaulted);
317 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
318 PSECURITY_DESCRIPTOR pSecurityDescriptor,
319 PSID *pGroup,
320 LPBOOL lpbGroupDefaulted);
321 typedef BOOL (WINAPI * IsValidSid_Proc) (
322 PSID sid);
323 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
324 DWORD dwFlags,
325 DWORD th32ProcessID);
326 typedef BOOL (WINAPI * Process32First_Proc) (
327 HANDLE hSnapshot,
328 LPPROCESSENTRY32 lppe);
329 typedef BOOL (WINAPI * Process32Next_Proc) (
330 HANDLE hSnapshot,
331 LPPROCESSENTRY32 lppe);
332 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
333 HANDLE ThreadHandle,
334 DWORD DesiredAccess,
335 BOOL OpenAsSelf,
336 PHANDLE TokenHandle);
337 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
338 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
339 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
340 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
341 HANDLE Process,
342 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
343 DWORD cb);
344 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
345 HANDLE hProcess,
346 DWORD * lpMinimumWorkingSetSize,
347 DWORD * lpMaximumWorkingSetSize);
348 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
349 LPMEMORYSTATUS lpBuffer);
350 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
351 LPMEMORY_STATUS_EX lpBuffer);
352 typedef BOOL (WINAPI * CopySid_Proc) (
353 DWORD nDestinationSidLength,
354 PSID pDestinationSid,
355 PSID pSourceSid);
356 typedef BOOL (WINAPI * EqualSid_Proc) (
357 PSID pSid1,
358 PSID pSid2);
359 typedef DWORD (WINAPI * GetLengthSid_Proc) (
360 PSID pSid);
361 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
362 LPSYSTEM_INFO lpSystemInfo);
363 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
364 LPFILETIME lpIdleTime,
365 LPFILETIME lpKernelTime,
366 LPFILETIME lpUserTime);
367 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
368 LPTSTR lpSymlinkFileName,
369 LPTSTR lpTargetFileName,
370 DWORD dwFlags);
372 /* ** A utility function ** */
373 static BOOL
374 is_windows_9x (void)
376 static BOOL s_b_ret = 0;
377 OSVERSIONINFO os_ver;
378 if (g_b_init_is_windows_9x == 0)
380 g_b_init_is_windows_9x = 1;
381 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
382 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
383 if (GetVersionEx (&os_ver))
385 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
388 return s_b_ret;
391 static Lisp_Object ltime (ULONGLONG);
393 /* Get total user and system times for get-internal-run-time.
394 Returns a list of integers if the times are provided by the OS
395 (NT derivatives), otherwise it returns the result of current-time. */
396 Lisp_Object
397 w32_get_internal_run_time (void)
399 if (get_process_times_fn)
401 FILETIME create, exit, kernel, user;
402 HANDLE proc = GetCurrentProcess ();
403 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
405 LARGE_INTEGER user_int, kernel_int, total;
406 user_int.LowPart = user.dwLowDateTime;
407 user_int.HighPart = user.dwHighDateTime;
408 kernel_int.LowPart = kernel.dwLowDateTime;
409 kernel_int.HighPart = kernel.dwHighDateTime;
410 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
411 return ltime (total.QuadPart);
415 return Fcurrent_time ();
418 /* ** The wrapper functions ** */
420 static BOOL WINAPI
421 open_process_token (HANDLE ProcessHandle,
422 DWORD DesiredAccess,
423 PHANDLE TokenHandle)
425 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
426 HMODULE hm_advapi32 = NULL;
427 if (is_windows_9x () == TRUE)
429 return FALSE;
431 if (g_b_init_open_process_token == 0)
433 g_b_init_open_process_token = 1;
434 hm_advapi32 = LoadLibrary ("Advapi32.dll");
435 s_pfn_Open_Process_Token =
436 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
438 if (s_pfn_Open_Process_Token == NULL)
440 return FALSE;
442 return (
443 s_pfn_Open_Process_Token (
444 ProcessHandle,
445 DesiredAccess,
446 TokenHandle)
450 static BOOL WINAPI
451 get_token_information (HANDLE TokenHandle,
452 TOKEN_INFORMATION_CLASS TokenInformationClass,
453 LPVOID TokenInformation,
454 DWORD TokenInformationLength,
455 PDWORD ReturnLength)
457 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
458 HMODULE hm_advapi32 = NULL;
459 if (is_windows_9x () == TRUE)
461 return FALSE;
463 if (g_b_init_get_token_information == 0)
465 g_b_init_get_token_information = 1;
466 hm_advapi32 = LoadLibrary ("Advapi32.dll");
467 s_pfn_Get_Token_Information =
468 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
470 if (s_pfn_Get_Token_Information == NULL)
472 return FALSE;
474 return (
475 s_pfn_Get_Token_Information (
476 TokenHandle,
477 TokenInformationClass,
478 TokenInformation,
479 TokenInformationLength,
480 ReturnLength)
484 static BOOL WINAPI
485 lookup_account_sid (LPCTSTR lpSystemName,
486 PSID Sid,
487 LPTSTR Name,
488 LPDWORD cbName,
489 LPTSTR DomainName,
490 LPDWORD cbDomainName,
491 PSID_NAME_USE peUse)
493 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
494 HMODULE hm_advapi32 = NULL;
495 if (is_windows_9x () == TRUE)
497 return FALSE;
499 if (g_b_init_lookup_account_sid == 0)
501 g_b_init_lookup_account_sid = 1;
502 hm_advapi32 = LoadLibrary ("Advapi32.dll");
503 s_pfn_Lookup_Account_Sid =
504 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
506 if (s_pfn_Lookup_Account_Sid == NULL)
508 return FALSE;
510 return (
511 s_pfn_Lookup_Account_Sid (
512 lpSystemName,
513 Sid,
514 Name,
515 cbName,
516 DomainName,
517 cbDomainName,
518 peUse)
522 static PDWORD WINAPI
523 get_sid_sub_authority (PSID pSid, DWORD n)
525 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
526 static DWORD zero = 0U;
527 HMODULE hm_advapi32 = NULL;
528 if (is_windows_9x () == TRUE)
530 return &zero;
532 if (g_b_init_get_sid_sub_authority == 0)
534 g_b_init_get_sid_sub_authority = 1;
535 hm_advapi32 = LoadLibrary ("Advapi32.dll");
536 s_pfn_Get_Sid_Sub_Authority =
537 (GetSidSubAuthority_Proc) GetProcAddress (
538 hm_advapi32, "GetSidSubAuthority");
540 if (s_pfn_Get_Sid_Sub_Authority == NULL)
542 return &zero;
544 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
547 static PUCHAR WINAPI
548 get_sid_sub_authority_count (PSID pSid)
550 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
551 static UCHAR zero = 0U;
552 HMODULE hm_advapi32 = NULL;
553 if (is_windows_9x () == TRUE)
555 return &zero;
557 if (g_b_init_get_sid_sub_authority_count == 0)
559 g_b_init_get_sid_sub_authority_count = 1;
560 hm_advapi32 = LoadLibrary ("Advapi32.dll");
561 s_pfn_Get_Sid_Sub_Authority_Count =
562 (GetSidSubAuthorityCount_Proc) GetProcAddress (
563 hm_advapi32, "GetSidSubAuthorityCount");
565 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
567 return &zero;
569 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
572 static DWORD WINAPI
573 get_security_info (HANDLE handle,
574 SE_OBJECT_TYPE ObjectType,
575 SECURITY_INFORMATION SecurityInfo,
576 PSID *ppsidOwner,
577 PSID *ppsidGroup,
578 PACL *ppDacl,
579 PACL *ppSacl,
580 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
582 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
583 HMODULE hm_advapi32 = NULL;
584 if (is_windows_9x () == TRUE)
586 return FALSE;
588 if (g_b_init_get_security_info == 0)
590 g_b_init_get_security_info = 1;
591 hm_advapi32 = LoadLibrary ("Advapi32.dll");
592 s_pfn_Get_Security_Info =
593 (GetSecurityInfo_Proc) GetProcAddress (
594 hm_advapi32, "GetSecurityInfo");
596 if (s_pfn_Get_Security_Info == NULL)
598 return FALSE;
600 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
601 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
602 ppSecurityDescriptor));
605 static BOOL WINAPI
606 get_file_security (LPCTSTR lpFileName,
607 SECURITY_INFORMATION RequestedInformation,
608 PSECURITY_DESCRIPTOR pSecurityDescriptor,
609 DWORD nLength,
610 LPDWORD lpnLengthNeeded)
612 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
613 HMODULE hm_advapi32 = NULL;
614 if (is_windows_9x () == TRUE)
616 return FALSE;
618 if (g_b_init_get_file_security == 0)
620 g_b_init_get_file_security = 1;
621 hm_advapi32 = LoadLibrary ("Advapi32.dll");
622 s_pfn_Get_File_Security =
623 (GetFileSecurity_Proc) GetProcAddress (
624 hm_advapi32, GetFileSecurity_Name);
626 if (s_pfn_Get_File_Security == NULL)
628 return FALSE;
630 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
631 pSecurityDescriptor, nLength,
632 lpnLengthNeeded));
635 static BOOL WINAPI
636 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
637 PSID *pOwner,
638 LPBOOL lpbOwnerDefaulted)
640 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
641 HMODULE hm_advapi32 = NULL;
642 if (is_windows_9x () == TRUE)
644 return FALSE;
646 if (g_b_init_get_security_descriptor_owner == 0)
648 g_b_init_get_security_descriptor_owner = 1;
649 hm_advapi32 = LoadLibrary ("Advapi32.dll");
650 s_pfn_Get_Security_Descriptor_Owner =
651 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
652 hm_advapi32, "GetSecurityDescriptorOwner");
654 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
656 return FALSE;
658 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
659 lpbOwnerDefaulted));
662 static BOOL WINAPI
663 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
664 PSID *pGroup,
665 LPBOOL lpbGroupDefaulted)
667 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
668 HMODULE hm_advapi32 = NULL;
669 if (is_windows_9x () == TRUE)
671 return FALSE;
673 if (g_b_init_get_security_descriptor_group == 0)
675 g_b_init_get_security_descriptor_group = 1;
676 hm_advapi32 = LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_Security_Descriptor_Group =
678 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
679 hm_advapi32, "GetSecurityDescriptorGroup");
681 if (s_pfn_Get_Security_Descriptor_Group == NULL)
683 return FALSE;
685 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
686 lpbGroupDefaulted));
689 static BOOL WINAPI
690 is_valid_sid (PSID sid)
692 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
693 HMODULE hm_advapi32 = NULL;
694 if (is_windows_9x () == TRUE)
696 return FALSE;
698 if (g_b_init_is_valid_sid == 0)
700 g_b_init_is_valid_sid = 1;
701 hm_advapi32 = LoadLibrary ("Advapi32.dll");
702 s_pfn_Is_Valid_Sid =
703 (IsValidSid_Proc) GetProcAddress (
704 hm_advapi32, "IsValidSid");
706 if (s_pfn_Is_Valid_Sid == NULL)
708 return FALSE;
710 return (s_pfn_Is_Valid_Sid (sid));
713 static BOOL WINAPI
714 equal_sid (PSID sid1, PSID sid2)
716 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
717 HMODULE hm_advapi32 = NULL;
718 if (is_windows_9x () == TRUE)
720 return FALSE;
722 if (g_b_init_equal_sid == 0)
724 g_b_init_equal_sid = 1;
725 hm_advapi32 = LoadLibrary ("Advapi32.dll");
726 s_pfn_Equal_Sid =
727 (EqualSid_Proc) GetProcAddress (
728 hm_advapi32, "EqualSid");
730 if (s_pfn_Equal_Sid == NULL)
732 return FALSE;
734 return (s_pfn_Equal_Sid (sid1, sid2));
737 static DWORD WINAPI
738 get_length_sid (PSID sid)
740 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
741 HMODULE hm_advapi32 = NULL;
742 if (is_windows_9x () == TRUE)
744 return 0;
746 if (g_b_init_get_length_sid == 0)
748 g_b_init_get_length_sid = 1;
749 hm_advapi32 = LoadLibrary ("Advapi32.dll");
750 s_pfn_Get_Length_Sid =
751 (GetLengthSid_Proc) GetProcAddress (
752 hm_advapi32, "GetLengthSid");
754 if (s_pfn_Get_Length_Sid == NULL)
756 return 0;
758 return (s_pfn_Get_Length_Sid (sid));
761 static BOOL WINAPI
762 copy_sid (DWORD destlen, PSID dest, PSID src)
764 static CopySid_Proc s_pfn_Copy_Sid = NULL;
765 HMODULE hm_advapi32 = NULL;
766 if (is_windows_9x () == TRUE)
768 return FALSE;
770 if (g_b_init_copy_sid == 0)
772 g_b_init_copy_sid = 1;
773 hm_advapi32 = LoadLibrary ("Advapi32.dll");
774 s_pfn_Copy_Sid =
775 (CopySid_Proc) GetProcAddress (
776 hm_advapi32, "CopySid");
778 if (s_pfn_Copy_Sid == NULL)
780 return FALSE;
782 return (s_pfn_Copy_Sid (destlen, dest, src));
786 END: Wrapper functions around OpenProcessToken
787 and other functions in advapi32.dll that are only
788 supported in Windows NT / 2k / XP
791 static void WINAPI
792 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
794 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
795 if (is_windows_9x () != TRUE)
797 if (g_b_init_get_native_system_info == 0)
799 g_b_init_get_native_system_info = 1;
800 s_pfn_Get_Native_System_Info =
801 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
802 "GetNativeSystemInfo");
804 if (s_pfn_Get_Native_System_Info != NULL)
805 s_pfn_Get_Native_System_Info (lpSystemInfo);
807 else
808 lpSystemInfo->dwNumberOfProcessors = -1;
811 static BOOL WINAPI
812 get_system_times (LPFILETIME lpIdleTime,
813 LPFILETIME lpKernelTime,
814 LPFILETIME lpUserTime)
816 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
817 if (is_windows_9x () == TRUE)
819 return FALSE;
821 if (g_b_init_get_system_times == 0)
823 g_b_init_get_system_times = 1;
824 s_pfn_Get_System_times =
825 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
826 "GetSystemTimes");
828 if (s_pfn_Get_System_times == NULL)
829 return FALSE;
830 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
833 static BOOLEAN WINAPI
834 create_symbolic_link (LPTSTR lpSymlinkFilename,
835 LPTSTR lpTargetFileName,
836 DWORD dwFlags)
838 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
839 BOOLEAN retval;
841 if (is_windows_9x () == TRUE)
843 errno = ENOSYS;
844 return 0;
846 if (g_b_init_create_symbolic_link == 0)
848 g_b_init_create_symbolic_link = 1;
849 #ifdef _UNICODE
850 s_pfn_Create_Symbolic_Link =
851 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
852 "CreateSymbolicLinkW");
853 #else
854 s_pfn_Create_Symbolic_Link =
855 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
856 "CreateSymbolicLinkA");
857 #endif
859 if (s_pfn_Create_Symbolic_Link == NULL)
861 errno = ENOSYS;
862 return 0;
865 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
866 dwFlags);
867 /* If we were denied creation of the symlink, try again after
868 enabling the SeCreateSymbolicLinkPrivilege for our process. */
869 if (!retval)
871 TOKEN_PRIVILEGES priv_current;
873 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
875 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
876 dwFlags);
877 restore_privilege (&priv_current);
878 revert_to_self ();
881 return retval;
885 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
886 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
888 This is called from alloc.c:valid_pointer_p. */
890 w32_valid_pointer_p (void *p, int size)
892 SIZE_T done;
893 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
895 if (h)
897 unsigned char *buf = alloca (size);
898 int retval = ReadProcessMemory (h, p, buf, size, &done);
900 CloseHandle (h);
901 return retval;
903 else
904 return -1;
907 static char startup_dir[MAXPATHLEN];
909 /* Get the current working directory. */
910 char *
911 getwd (char *dir)
913 #if 0
914 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
915 return dir;
916 return NULL;
917 #else
918 /* Emacs doesn't actually change directory itself, it stays in the
919 same directory where it was started. */
920 strcpy (dir, startup_dir);
921 return dir;
922 #endif
925 /* Emulate getloadavg. */
927 struct load_sample {
928 time_t sample_time;
929 ULONGLONG idle;
930 ULONGLONG kernel;
931 ULONGLONG user;
934 /* Number of processors on this machine. */
935 static unsigned num_of_processors;
937 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
938 static struct load_sample samples[16*60];
939 static int first_idx = -1, last_idx = -1;
940 static int max_idx = sizeof (samples) / sizeof (samples[0]);
942 static int
943 buf_next (int from)
945 int next_idx = from + 1;
947 if (next_idx >= max_idx)
948 next_idx = 0;
950 return next_idx;
953 static int
954 buf_prev (int from)
956 int prev_idx = from - 1;
958 if (prev_idx < 0)
959 prev_idx = max_idx - 1;
961 return prev_idx;
964 static void
965 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
967 SYSTEM_INFO sysinfo;
968 FILETIME ft_idle, ft_user, ft_kernel;
970 /* Initialize the number of processors on this machine. */
971 if (num_of_processors <= 0)
973 get_native_system_info (&sysinfo);
974 num_of_processors = sysinfo.dwNumberOfProcessors;
975 if (num_of_processors <= 0)
977 GetSystemInfo (&sysinfo);
978 num_of_processors = sysinfo.dwNumberOfProcessors;
980 if (num_of_processors <= 0)
981 num_of_processors = 1;
984 /* TODO: Take into account threads that are ready to run, by
985 sampling the "\System\Processor Queue Length" performance
986 counter. The code below accounts only for threads that are
987 actually running. */
989 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
991 ULARGE_INTEGER uidle, ukernel, uuser;
993 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
994 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
995 memcpy (&uuser, &ft_user, sizeof (ft_user));
996 *idle = uidle.QuadPart;
997 *kernel = ukernel.QuadPart;
998 *user = uuser.QuadPart;
1000 else
1002 *idle = 0;
1003 *kernel = 0;
1004 *user = 0;
1008 /* Produce the load average for a given time interval, using the
1009 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1010 1-minute, 5-minute, or 15-minute average, respectively. */
1011 static double
1012 getavg (int which)
1014 double retval = -1.0;
1015 double tdiff;
1016 int idx;
1017 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1018 time_t now = samples[last_idx].sample_time;
1020 if (first_idx != last_idx)
1022 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1024 tdiff = difftime (now, samples[idx].sample_time);
1025 if (tdiff >= span - 2*DBL_EPSILON*now)
1027 long double sys =
1028 samples[last_idx].kernel + samples[last_idx].user
1029 - (samples[idx].kernel + samples[idx].user);
1030 long double idl = samples[last_idx].idle - samples[idx].idle;
1032 retval = (1.0 - idl / sys) * num_of_processors;
1033 break;
1035 if (idx == first_idx)
1036 break;
1040 return retval;
1044 getloadavg (double loadavg[], int nelem)
1046 int elem;
1047 ULONGLONG idle, kernel, user;
1048 time_t now = time (NULL);
1050 /* Store another sample. We ignore samples that are less than 1 sec
1051 apart. */
1052 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1054 sample_system_load (&idle, &kernel, &user);
1055 last_idx = buf_next (last_idx);
1056 samples[last_idx].sample_time = now;
1057 samples[last_idx].idle = idle;
1058 samples[last_idx].kernel = kernel;
1059 samples[last_idx].user = user;
1060 /* If the buffer has more that 15 min worth of samples, discard
1061 the old ones. */
1062 if (first_idx == -1)
1063 first_idx = last_idx;
1064 while (first_idx != last_idx
1065 && (difftime (now, samples[first_idx].sample_time)
1066 >= 15.0*60 + 2*DBL_EPSILON*now))
1067 first_idx = buf_next (first_idx);
1070 for (elem = 0; elem < nelem; elem++)
1072 double avg = getavg (elem);
1074 if (avg < 0)
1075 break;
1076 loadavg[elem] = avg;
1079 return elem;
1082 /* Emulate getpwuid, getpwnam and others. */
1084 #define PASSWD_FIELD_SIZE 256
1086 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1087 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1088 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1089 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1090 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1092 static struct passwd dflt_passwd =
1094 dflt_passwd_name,
1095 dflt_passwd_passwd,
1099 dflt_passwd_gecos,
1100 dflt_passwd_dir,
1101 dflt_passwd_shell,
1104 static char dflt_group_name[GNLEN+1];
1106 static struct group dflt_group =
1108 /* When group information is not available, we return this as the
1109 group for all files. */
1110 dflt_group_name,
1114 unsigned
1115 getuid (void)
1117 return dflt_passwd.pw_uid;
1120 unsigned
1121 geteuid (void)
1123 /* I could imagine arguing for checking to see whether the user is
1124 in the Administrators group and returning a UID of 0 for that
1125 case, but I don't know how wise that would be in the long run. */
1126 return getuid ();
1129 unsigned
1130 getgid (void)
1132 return dflt_passwd.pw_gid;
1135 unsigned
1136 getegid (void)
1138 return getgid ();
1141 struct passwd *
1142 getpwuid (unsigned uid)
1144 if (uid == dflt_passwd.pw_uid)
1145 return &dflt_passwd;
1146 return NULL;
1149 struct group *
1150 getgrgid (gid_t gid)
1152 return &dflt_group;
1155 struct passwd *
1156 getpwnam (char *name)
1158 struct passwd *pw;
1160 pw = getpwuid (getuid ());
1161 if (!pw)
1162 return pw;
1164 if (xstrcasecmp (name, pw->pw_name))
1165 return NULL;
1167 return pw;
1170 static void
1171 init_user_info (void)
1173 /* Find the user's real name by opening the process token and
1174 looking up the name associated with the user-sid in that token.
1176 Use the relative portion of the identifier authority value from
1177 the user-sid as the user id value (same for group id using the
1178 primary group sid from the process token). */
1180 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1181 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1182 DWORD glength = sizeof (gname);
1183 HANDLE token = NULL;
1184 SID_NAME_USE user_type;
1185 unsigned char *buf = NULL;
1186 DWORD blen = 0;
1187 TOKEN_USER user_token;
1188 TOKEN_PRIMARY_GROUP group_token;
1189 BOOL result;
1191 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1192 if (result)
1194 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1195 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1197 buf = xmalloc (blen);
1198 result = get_token_information (token, TokenUser,
1199 (LPVOID)buf, blen, &needed);
1200 if (result)
1202 memcpy (&user_token, buf, sizeof (user_token));
1203 result = lookup_account_sid (NULL, user_token.User.Sid,
1204 uname, &ulength,
1205 domain, &dlength, &user_type);
1208 else
1209 result = FALSE;
1211 if (result)
1213 strcpy (dflt_passwd.pw_name, uname);
1214 /* Determine a reasonable uid value. */
1215 if (xstrcasecmp ("administrator", uname) == 0)
1217 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1218 dflt_passwd.pw_gid = 513; /* well-known None gid */
1220 else
1222 /* Use the last sub-authority value of the RID, the relative
1223 portion of the SID, as user/group ID. */
1224 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1226 /* Get group id and name. */
1227 result = get_token_information (token, TokenPrimaryGroup,
1228 (LPVOID)buf, blen, &needed);
1229 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1231 buf = xrealloc (buf, blen = needed);
1232 result = get_token_information (token, TokenPrimaryGroup,
1233 (LPVOID)buf, blen, &needed);
1235 if (result)
1237 memcpy (&group_token, buf, sizeof (group_token));
1238 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1239 dlength = sizeof (domain);
1240 /* If we can get at the real Primary Group name, use that.
1241 Otherwise, the default group name was already set to
1242 "None" in globals_of_w32. */
1243 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1244 gname, &glength, NULL, &dlength,
1245 &user_type))
1246 strcpy (dflt_group_name, gname);
1248 else
1249 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1252 /* If security calls are not supported (presumably because we
1253 are running under Windows 9X), fallback to this: */
1254 else if (GetUserName (uname, &ulength))
1256 strcpy (dflt_passwd.pw_name, uname);
1257 if (xstrcasecmp ("administrator", uname) == 0)
1258 dflt_passwd.pw_uid = 0;
1259 else
1260 dflt_passwd.pw_uid = 123;
1261 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1263 else
1265 strcpy (dflt_passwd.pw_name, "unknown");
1266 dflt_passwd.pw_uid = 123;
1267 dflt_passwd.pw_gid = 123;
1269 dflt_group.gr_gid = dflt_passwd.pw_gid;
1271 /* Ensure HOME and SHELL are defined. */
1272 if (getenv ("HOME") == NULL)
1273 emacs_abort ();
1274 if (getenv ("SHELL") == NULL)
1275 emacs_abort ();
1277 /* Set dir and shell from environment variables. */
1278 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1279 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1281 xfree (buf);
1282 if (token)
1283 CloseHandle (token);
1287 random (void)
1289 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1290 return ((rand () << 15) | rand ());
1293 void
1294 srandom (int seed)
1296 srand (seed);
1300 /* Normalize filename by converting all path separators to
1301 the specified separator. Also conditionally convert upper
1302 case path name components to lower case. */
1304 static void
1305 normalize_filename (register char *fp, char path_sep)
1307 char sep;
1308 char *elem;
1310 /* Always lower-case drive letters a-z, even if the filesystem
1311 preserves case in filenames.
1312 This is so filenames can be compared by string comparison
1313 functions that are case-sensitive. Even case-preserving filesystems
1314 do not distinguish case in drive letters. */
1315 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
1317 *fp += 'a' - 'A';
1318 fp += 2;
1321 if (NILP (Vw32_downcase_file_names))
1323 while (*fp)
1325 if (*fp == '/' || *fp == '\\')
1326 *fp = path_sep;
1327 fp++;
1329 return;
1332 sep = path_sep; /* convert to this path separator */
1333 elem = fp; /* start of current path element */
1335 do {
1336 if (*fp >= 'a' && *fp <= 'z')
1337 elem = 0; /* don't convert this element */
1339 if (*fp == 0 || *fp == ':')
1341 sep = *fp; /* restore current separator (or 0) */
1342 *fp = '/'; /* after conversion of this element */
1345 if (*fp == '/' || *fp == '\\')
1347 if (elem && elem != fp)
1349 *fp = 0; /* temporary end of string */
1350 _strlwr (elem); /* while we convert to lower case */
1352 *fp = sep; /* convert (or restore) path separator */
1353 elem = fp + 1; /* next element starts after separator */
1354 sep = path_sep;
1356 } while (*fp++);
1359 /* Destructively turn backslashes into slashes. */
1360 void
1361 dostounix_filename (register char *p)
1363 normalize_filename (p, '/');
1366 /* Destructively turn slashes into backslashes. */
1367 void
1368 unixtodos_filename (register char *p)
1370 normalize_filename (p, '\\');
1373 /* Remove all CR's that are followed by a LF.
1374 (From msdos.c...probably should figure out a way to share it,
1375 although this code isn't going to ever change.) */
1376 static int
1377 crlf_to_lf (register int n, register unsigned char *buf)
1379 unsigned char *np = buf;
1380 unsigned char *startp = buf;
1381 unsigned char *endp = buf + n;
1383 if (n == 0)
1384 return n;
1385 while (buf < endp - 1)
1387 if (*buf == 0x0d)
1389 if (*(++buf) != 0x0a)
1390 *np++ = 0x0d;
1392 else
1393 *np++ = *buf++;
1395 if (buf < endp)
1396 *np++ = *buf++;
1397 return np - startp;
1400 /* Parse the root part of file name, if present. Return length and
1401 optionally store pointer to char after root. */
1402 static int
1403 parse_root (char * name, char ** pPath)
1405 char * start = name;
1407 if (name == NULL)
1408 return 0;
1410 /* find the root name of the volume if given */
1411 if (isalpha (name[0]) && name[1] == ':')
1413 /* skip past drive specifier */
1414 name += 2;
1415 if (IS_DIRECTORY_SEP (name[0]))
1416 name++;
1418 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1420 int slashes = 2;
1421 name += 2;
1424 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1425 break;
1426 name++;
1428 while ( *name );
1429 if (IS_DIRECTORY_SEP (name[0]))
1430 name++;
1433 if (pPath)
1434 *pPath = name;
1436 return name - start;
1439 /* Get long base name for name; name is assumed to be absolute. */
1440 static int
1441 get_long_basename (char * name, char * buf, int size)
1443 WIN32_FIND_DATA find_data;
1444 HANDLE dir_handle;
1445 int len = 0;
1447 /* must be valid filename, no wild cards or other invalid characters */
1448 if (_mbspbrk (name, "*?|<>\""))
1449 return 0;
1451 dir_handle = FindFirstFile (name, &find_data);
1452 if (dir_handle != INVALID_HANDLE_VALUE)
1454 if ((len = strlen (find_data.cFileName)) < size)
1455 memcpy (buf, find_data.cFileName, len + 1);
1456 else
1457 len = 0;
1458 FindClose (dir_handle);
1460 return len;
1463 /* Get long name for file, if possible (assumed to be absolute). */
1464 BOOL
1465 w32_get_long_filename (char * name, char * buf, int size)
1467 char * o = buf;
1468 char * p;
1469 char * q;
1470 char full[ MAX_PATH ];
1471 int len;
1473 len = strlen (name);
1474 if (len >= MAX_PATH)
1475 return FALSE;
1477 /* Use local copy for destructive modification. */
1478 memcpy (full, name, len+1);
1479 unixtodos_filename (full);
1481 /* Copy root part verbatim. */
1482 len = parse_root (full, &p);
1483 memcpy (o, full, len);
1484 o += len;
1485 *o = '\0';
1486 size -= len;
1488 while (p != NULL && *p)
1490 q = p;
1491 p = strchr (q, '\\');
1492 if (p) *p = '\0';
1493 len = get_long_basename (full, o, size);
1494 if (len > 0)
1496 o += len;
1497 size -= len;
1498 if (p != NULL)
1500 *p++ = '\\';
1501 if (size < 2)
1502 return FALSE;
1503 *o++ = '\\';
1504 size--;
1505 *o = '\0';
1508 else
1509 return FALSE;
1512 return TRUE;
1515 static int
1516 is_unc_volume (const char *filename)
1518 const char *ptr = filename;
1520 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1521 return 0;
1523 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1524 return 0;
1526 return 1;
1529 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1531 LPBYTE
1532 w32_get_resource (char *key, LPDWORD lpdwtype)
1534 LPBYTE lpvalue;
1535 HKEY hrootkey = NULL;
1536 DWORD cbData;
1538 /* Check both the current user and the local machine to see if
1539 we have any resources. */
1541 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1543 lpvalue = NULL;
1545 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1546 && (lpvalue = xmalloc (cbData)) != NULL
1547 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1549 RegCloseKey (hrootkey);
1550 return (lpvalue);
1553 xfree (lpvalue);
1555 RegCloseKey (hrootkey);
1558 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1560 lpvalue = NULL;
1562 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1563 && (lpvalue = xmalloc (cbData)) != NULL
1564 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1566 RegCloseKey (hrootkey);
1567 return (lpvalue);
1570 xfree (lpvalue);
1572 RegCloseKey (hrootkey);
1575 return (NULL);
1578 char *get_emacs_configuration (void);
1580 void
1581 init_environment (char ** argv)
1583 static const char * const tempdirs[] = {
1584 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1587 int i;
1589 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1591 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1592 temporary files and assume "/tmp" if $TMPDIR is unset, which
1593 will break on DOS/Windows. Refuse to work if we cannot find
1594 a directory, not even "c:/", usable for that purpose. */
1595 for (i = 0; i < imax ; i++)
1597 const char *tmp = tempdirs[i];
1599 if (*tmp == '$')
1600 tmp = getenv (tmp + 1);
1601 /* Note that `access' can lie to us if the directory resides on a
1602 read-only filesystem, like CD-ROM or a write-protected floppy.
1603 The only way to be really sure is to actually create a file and
1604 see if it succeeds. But I think that's too much to ask. */
1606 /* MSVCRT's _access crashes with D_OK. */
1607 if (tmp && sys_access (tmp, D_OK) == 0)
1609 char * var = alloca (strlen (tmp) + 8);
1610 sprintf (var, "TMPDIR=%s", tmp);
1611 _putenv (strdup (var));
1612 break;
1615 if (i >= imax)
1616 cmd_error_internal
1617 (Fcons (Qerror,
1618 Fcons (build_string ("no usable temporary directories found!!"),
1619 Qnil)),
1620 "While setting TMPDIR: ");
1622 /* Check for environment variables and use registry settings if they
1623 don't exist. Fallback on default values where applicable. */
1625 int i;
1626 LPBYTE lpval;
1627 DWORD dwType;
1628 char locale_name[32];
1629 char default_home[MAX_PATH];
1630 int appdata = 0;
1632 static const struct env_entry
1634 char * name;
1635 char * def_value;
1636 } dflt_envvars[] =
1638 /* If the default value is NULL, we will use the value from the
1639 outside environment or the Registry, but will not push the
1640 variable into the Emacs environment if it is defined neither
1641 in the Registry nor in the outside environment. */
1642 {"HOME", "C:/"},
1643 {"PRELOAD_WINSOCK", NULL},
1644 {"emacs_dir", "C:/emacs"},
1645 {"EMACSLOADPATH", NULL},
1646 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1647 {"EMACSDATA", NULL},
1648 {"EMACSPATH", NULL},
1649 {"INFOPATH", NULL},
1650 {"EMACSDOC", NULL},
1651 {"TERM", "cmd"},
1652 {"LANG", NULL},
1655 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1657 /* We need to copy dflt_envvars[] and work on the copy because we
1658 don't want the dumped Emacs to inherit the values of
1659 environment variables we saw during dumping (which could be on
1660 a different system). The defaults above must be left intact. */
1661 struct env_entry env_vars[N_ENV_VARS];
1663 for (i = 0; i < N_ENV_VARS; i++)
1664 env_vars[i] = dflt_envvars[i];
1666 /* For backwards compatibility, check if a .emacs file exists in C:/
1667 If not, then we can try to default to the appdata directory under the
1668 user's profile, which is more likely to be writable. */
1669 if (!check_existing ("C:/.emacs"))
1671 HRESULT profile_result;
1672 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1673 of Windows 95 and NT4 that have not been updated to include
1674 MSIE 5. */
1675 ShGetFolderPath_fn get_folder_path;
1676 get_folder_path = (ShGetFolderPath_fn)
1677 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1679 if (get_folder_path != NULL)
1681 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
1682 0, default_home);
1684 /* If we can't get the appdata dir, revert to old behavior. */
1685 if (profile_result == S_OK)
1687 env_vars[0].def_value = default_home;
1688 appdata = 1;
1693 /* Get default locale info and use it for LANG. */
1694 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
1695 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1696 locale_name, sizeof (locale_name)))
1698 for (i = 0; i < N_ENV_VARS; i++)
1700 if (strcmp (env_vars[i].name, "LANG") == 0)
1702 env_vars[i].def_value = locale_name;
1703 break;
1708 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1710 /* Treat emacs_dir specially: set it unconditionally based on our
1711 location. */
1713 char *p;
1714 char modname[MAX_PATH];
1716 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1717 emacs_abort ();
1718 if ((p = strrchr (modname, '\\')) == NULL)
1719 emacs_abort ();
1720 *p = 0;
1722 if ((p = strrchr (modname, '\\')) && xstrcasecmp (p, "\\bin") == 0)
1724 char buf[SET_ENV_BUF_SIZE];
1726 *p = 0;
1727 for (p = modname; *p; p++)
1728 if (*p == '\\') *p = '/';
1730 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1731 _putenv (strdup (buf));
1733 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1735 /* FIXME: should use substring of get_emacs_configuration ().
1736 But I don't think the Windows build supports alpha, mips etc
1737 anymore, so have taken the easy option for now. */
1738 else if (p && (xstrcasecmp (p, "\\i386") == 0
1739 || xstrcasecmp (p, "\\AMD64") == 0))
1741 *p = 0;
1742 p = strrchr (modname, '\\');
1743 if (p != NULL)
1745 *p = 0;
1746 p = strrchr (modname, '\\');
1747 if (p && xstrcasecmp (p, "\\src") == 0)
1749 char buf[SET_ENV_BUF_SIZE];
1751 *p = 0;
1752 for (p = modname; *p; p++)
1753 if (*p == '\\') *p = '/';
1755 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1756 _putenv (strdup (buf));
1762 for (i = 0; i < N_ENV_VARS; i++)
1764 if (!getenv (env_vars[i].name))
1766 int dont_free = 0;
1768 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
1769 /* Also ignore empty environment variables. */
1770 || *lpval == 0)
1772 xfree (lpval);
1773 lpval = env_vars[i].def_value;
1774 dwType = REG_EXPAND_SZ;
1775 dont_free = 1;
1776 if (!strcmp (env_vars[i].name, "HOME") && !appdata)
1777 Vdelayed_warnings_list
1778 = Fcons (listn (CONSTYPE_HEAP, 2,
1779 intern ("initialization"),
1780 build_string ("Setting HOME to C:\\ by default is deprecated")),
1781 Vdelayed_warnings_list);
1784 if (lpval)
1786 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
1788 if (dwType == REG_EXPAND_SZ)
1789 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
1790 else if (dwType == REG_SZ)
1791 strcpy (buf1, lpval);
1792 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
1794 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
1795 buf1);
1796 _putenv (strdup (buf2));
1799 if (!dont_free)
1800 xfree (lpval);
1806 /* Rebuild system configuration to reflect invoking system. */
1807 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
1809 /* Another special case: on NT, the PATH variable is actually named
1810 "Path" although cmd.exe (perhaps NT itself) arranges for
1811 environment variable lookup and setting to be case insensitive.
1812 However, Emacs assumes a fully case sensitive environment, so we
1813 need to change "Path" to "PATH" to match the expectations of
1814 various elisp packages. We do this by the sneaky method of
1815 modifying the string in the C runtime environ entry.
1817 The same applies to COMSPEC. */
1819 char ** envp;
1821 for (envp = environ; *envp; envp++)
1822 if (_strnicmp (*envp, "PATH=", 5) == 0)
1823 memcpy (*envp, "PATH=", 5);
1824 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
1825 memcpy (*envp, "COMSPEC=", 8);
1828 /* Remember the initial working directory for getwd. */
1829 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
1830 Does it matter anywhere in Emacs? */
1831 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
1832 emacs_abort ();
1835 static char modname[MAX_PATH];
1837 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1838 emacs_abort ();
1839 argv[0] = modname;
1842 /* Determine if there is a middle mouse button, to allow parse_button
1843 to decide whether right mouse events should be mouse-2 or
1844 mouse-3. */
1845 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
1847 init_user_info ();
1850 /* Called from expand-file-name when default-directory is not a string. */
1852 char *
1853 emacs_root_dir (void)
1855 static char root_dir[FILENAME_MAX];
1856 const char *p;
1858 p = getenv ("emacs_dir");
1859 if (p == NULL)
1860 emacs_abort ();
1861 strcpy (root_dir, p);
1862 root_dir[parse_root (root_dir, NULL)] = '\0';
1863 dostounix_filename (root_dir);
1864 return root_dir;
1867 /* We don't have scripts to automatically determine the system configuration
1868 for Emacs before it's compiled, and we don't want to have to make the
1869 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1870 routine. */
1872 char *
1873 get_emacs_configuration (void)
1875 char *arch, *oem, *os;
1876 int build_num;
1877 static char configuration_buffer[32];
1879 /* Determine the processor type. */
1880 switch (get_processor_type ())
1883 #ifdef PROCESSOR_INTEL_386
1884 case PROCESSOR_INTEL_386:
1885 case PROCESSOR_INTEL_486:
1886 case PROCESSOR_INTEL_PENTIUM:
1887 #ifdef _WIN64
1888 arch = "amd64";
1889 #else
1890 arch = "i386";
1891 #endif
1892 break;
1893 #endif
1894 #ifdef PROCESSOR_AMD_X8664
1895 case PROCESSOR_AMD_X8664:
1896 arch = "amd64";
1897 break;
1898 #endif
1900 #ifdef PROCESSOR_MIPS_R2000
1901 case PROCESSOR_MIPS_R2000:
1902 case PROCESSOR_MIPS_R3000:
1903 case PROCESSOR_MIPS_R4000:
1904 arch = "mips";
1905 break;
1906 #endif
1908 #ifdef PROCESSOR_ALPHA_21064
1909 case PROCESSOR_ALPHA_21064:
1910 arch = "alpha";
1911 break;
1912 #endif
1914 default:
1915 arch = "unknown";
1916 break;
1919 /* Use the OEM field to reflect the compiler/library combination. */
1920 #ifdef _MSC_VER
1921 #define COMPILER_NAME "msvc"
1922 #else
1923 #ifdef __GNUC__
1924 #define COMPILER_NAME "mingw"
1925 #else
1926 #define COMPILER_NAME "unknown"
1927 #endif
1928 #endif
1929 oem = COMPILER_NAME;
1931 switch (osinfo_cache.dwPlatformId) {
1932 case VER_PLATFORM_WIN32_NT:
1933 os = "nt";
1934 build_num = osinfo_cache.dwBuildNumber;
1935 break;
1936 case VER_PLATFORM_WIN32_WINDOWS:
1937 if (osinfo_cache.dwMinorVersion == 0) {
1938 os = "windows95";
1939 } else {
1940 os = "windows98";
1942 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1943 break;
1944 case VER_PLATFORM_WIN32s:
1945 /* Not supported, should not happen. */
1946 os = "windows32s";
1947 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1948 break;
1949 default:
1950 os = "unknown";
1951 build_num = 0;
1952 break;
1955 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1956 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
1957 get_w32_major_version (), get_w32_minor_version (), build_num);
1958 } else {
1959 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
1962 return configuration_buffer;
1965 char *
1966 get_emacs_configuration_options (void)
1968 static char *options_buffer;
1969 char cv[32]; /* Enough for COMPILER_VERSION. */
1970 char *options[] = {
1971 cv, /* To be filled later. */
1972 #ifdef EMACSDEBUG
1973 " --no-opt",
1974 #endif
1975 #ifdef ENABLE_CHECKING
1976 " --enable-checking",
1977 #endif
1978 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1979 with a starting space to save work here. */
1980 #ifdef USER_CFLAGS
1981 " --cflags", USER_CFLAGS,
1982 #endif
1983 #ifdef USER_LDFLAGS
1984 " --ldflags", USER_LDFLAGS,
1985 #endif
1986 NULL
1988 size_t size = 0;
1989 int i;
1991 /* Work out the effective configure options for this build. */
1992 #ifdef _MSC_VER
1993 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1994 #else
1995 #ifdef __GNUC__
1996 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1997 #else
1998 #define COMPILER_VERSION ""
1999 #endif
2000 #endif
2002 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2003 return "Error: not enough space for compiler version";
2004 cv[sizeof (cv) - 1] = '\0';
2006 for (i = 0; options[i]; i++)
2007 size += strlen (options[i]);
2009 options_buffer = xmalloc (size + 1);
2010 options_buffer[0] = '\0';
2012 for (i = 0; options[i]; i++)
2013 strcat (options_buffer, options[i]);
2015 return options_buffer;
2019 #include <sys/timeb.h>
2021 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2022 void
2023 gettimeofday (struct timeval *tv, struct timezone *tz)
2025 struct _timeb tb;
2026 _ftime (&tb);
2028 tv->tv_sec = tb.time;
2029 tv->tv_usec = tb.millitm * 1000L;
2030 /* Implementation note: _ftime sometimes doesn't update the dstflag
2031 according to the new timezone when the system timezone is
2032 changed. We could fix that by using GetSystemTime and
2033 GetTimeZoneInformation, but that doesn't seem necessary, since
2034 Emacs always calls gettimeofday with the 2nd argument NULL (see
2035 current_emacs_time). */
2036 if (tz)
2038 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2039 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2043 /* Emulate fdutimens. */
2045 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2046 TIMESPEC[0] and TIMESPEC[1], respectively.
2047 FD must be either negative -- in which case it is ignored --
2048 or a file descriptor that is open on FILE.
2049 If FD is nonnegative, then FILE can be NULL, which means
2050 use just futimes instead of utimes.
2051 If TIMESPEC is null, FAIL.
2052 Return 0 on success, -1 (setting errno) on failure. */
2055 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2057 struct _utimbuf ut;
2059 if (!timespec)
2061 errno = ENOSYS;
2062 return -1;
2064 if (fd < 0 && !file)
2066 errno = EBADF;
2067 return -1;
2069 ut.actime = timespec[0].tv_sec;
2070 ut.modtime = timespec[1].tv_sec;
2071 if (fd >= 0)
2072 return _futime (fd, &ut);
2073 else
2074 return _utime (file, &ut);
2078 /* ------------------------------------------------------------------------- */
2079 /* IO support and wrapper functions for the Windows API. */
2080 /* ------------------------------------------------------------------------- */
2082 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2083 on network directories, so we handle that case here.
2084 (Ulrich Leodolter, 1/11/95). */
2085 char *
2086 sys_ctime (const time_t *t)
2088 char *str = (char *) ctime (t);
2089 return (str ? str : "Sun Jan 01 00:00:00 1970");
2092 /* Emulate sleep...we could have done this with a define, but that
2093 would necessitate including windows.h in the files that used it.
2094 This is much easier. */
2095 void
2096 sys_sleep (int seconds)
2098 Sleep (seconds * 1000);
2101 /* Internal MSVC functions for low-level descriptor munging */
2102 extern int __cdecl _set_osfhnd (int fd, long h);
2103 extern int __cdecl _free_osfhnd (int fd);
2105 /* parallel array of private info on file handles */
2106 filedesc fd_info [ MAXDESC ];
2108 typedef struct volume_info_data {
2109 struct volume_info_data * next;
2111 /* time when info was obtained */
2112 DWORD timestamp;
2114 /* actual volume info */
2115 char * root_dir;
2116 DWORD serialnum;
2117 DWORD maxcomp;
2118 DWORD flags;
2119 char * name;
2120 char * type;
2121 } volume_info_data;
2123 /* Global referenced by various functions. */
2124 static volume_info_data volume_info;
2126 /* Vector to indicate which drives are local and fixed (for which cached
2127 data never expires). */
2128 static BOOL fixed_drives[26];
2130 /* Consider cached volume information to be stale if older than 10s,
2131 at least for non-local drives. Info for fixed drives is never stale. */
2132 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2133 #define VOLINFO_STILL_VALID( root_dir, info ) \
2134 ( ( isalpha (root_dir[0]) && \
2135 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2136 || GetTickCount () - info->timestamp < 10000 )
2138 /* Cache support functions. */
2140 /* Simple linked list with linear search is sufficient. */
2141 static volume_info_data *volume_cache = NULL;
2143 static volume_info_data *
2144 lookup_volume_info (char * root_dir)
2146 volume_info_data * info;
2148 for (info = volume_cache; info; info = info->next)
2149 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2150 break;
2151 return info;
2154 static void
2155 add_volume_info (char * root_dir, volume_info_data * info)
2157 info->root_dir = xstrdup (root_dir);
2158 info->next = volume_cache;
2159 volume_cache = info;
2163 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2164 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2165 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2166 static volume_info_data *
2167 GetCachedVolumeInformation (char * root_dir)
2169 volume_info_data * info;
2170 char default_root[ MAX_PATH ];
2172 /* NULL for root_dir means use root from current directory. */
2173 if (root_dir == NULL)
2175 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2176 return NULL;
2177 parse_root (default_root, &root_dir);
2178 *root_dir = 0;
2179 root_dir = default_root;
2182 /* Local fixed drives can be cached permanently. Removable drives
2183 cannot be cached permanently, since the volume name and serial
2184 number (if nothing else) can change. Remote drives should be
2185 treated as if they are removable, since there is no sure way to
2186 tell whether they are or not. Also, the UNC association of drive
2187 letters mapped to remote volumes can be changed at any time (even
2188 by other processes) without notice.
2190 As a compromise, so we can benefit from caching info for remote
2191 volumes, we use a simple expiry mechanism to invalidate cache
2192 entries that are more than ten seconds old. */
2194 #if 0
2195 /* No point doing this, because WNetGetConnection is even slower than
2196 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2197 GetDriveType is about the only call of this type which does not
2198 involve network access, and so is extremely quick). */
2200 /* Map drive letter to UNC if remote. */
2201 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2203 char remote_name[ 256 ];
2204 char drive[3] = { root_dir[0], ':' };
2206 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2207 == NO_ERROR)
2208 /* do something */ ;
2210 #endif
2212 info = lookup_volume_info (root_dir);
2214 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2216 char name[ 256 ];
2217 DWORD serialnum;
2218 DWORD maxcomp;
2219 DWORD flags;
2220 char type[ 256 ];
2222 /* Info is not cached, or is stale. */
2223 if (!GetVolumeInformation (root_dir,
2224 name, sizeof (name),
2225 &serialnum,
2226 &maxcomp,
2227 &flags,
2228 type, sizeof (type)))
2229 return NULL;
2231 /* Cache the volume information for future use, overwriting existing
2232 entry if present. */
2233 if (info == NULL)
2235 info = xmalloc (sizeof (volume_info_data));
2236 add_volume_info (root_dir, info);
2238 else
2240 xfree (info->name);
2241 xfree (info->type);
2244 info->name = xstrdup (name);
2245 info->serialnum = serialnum;
2246 info->maxcomp = maxcomp;
2247 info->flags = flags;
2248 info->type = xstrdup (type);
2249 info->timestamp = GetTickCount ();
2252 return info;
2255 /* Get information on the volume where NAME is held; set path pointer to
2256 start of pathname in NAME (past UNC header\volume header if present),
2257 if pPath is non-NULL.
2259 Note: if NAME includes symlinks, the information is for the volume
2260 of the symlink, not of its target. That's because, even though
2261 GetVolumeInformation returns information about the symlink target
2262 of its argument, we only pass the root directory to
2263 GetVolumeInformation, not the full NAME. */
2264 static int
2265 get_volume_info (const char * name, const char ** pPath)
2267 char temp[MAX_PATH];
2268 char *rootname = NULL; /* default to current volume */
2269 volume_info_data * info;
2271 if (name == NULL)
2272 return FALSE;
2274 /* Find the root name of the volume if given. */
2275 if (isalpha (name[0]) && name[1] == ':')
2277 rootname = temp;
2278 temp[0] = *name++;
2279 temp[1] = *name++;
2280 temp[2] = '\\';
2281 temp[3] = 0;
2283 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2285 char *str = temp;
2286 int slashes = 4;
2287 rootname = temp;
2290 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2291 break;
2292 *str++ = *name++;
2294 while ( *name );
2296 *str++ = '\\';
2297 *str = 0;
2300 if (pPath)
2301 *pPath = name;
2303 info = GetCachedVolumeInformation (rootname);
2304 if (info != NULL)
2306 /* Set global referenced by other functions. */
2307 volume_info = *info;
2308 return TRUE;
2310 return FALSE;
2313 /* Determine if volume is FAT format (ie. only supports short 8.3
2314 names); also set path pointer to start of pathname in name, if
2315 pPath is non-NULL. */
2316 static int
2317 is_fat_volume (const char * name, const char ** pPath)
2319 if (get_volume_info (name, pPath))
2320 return (volume_info.maxcomp == 12);
2321 return FALSE;
2324 /* Map filename to a valid 8.3 name if necessary.
2325 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2326 const char *
2327 map_w32_filename (const char * name, const char ** pPath)
2329 static char shortname[MAX_PATH];
2330 char * str = shortname;
2331 char c;
2332 char * path;
2333 const char * save_name = name;
2335 if (strlen (name) >= MAX_PATH)
2337 /* Return a filename which will cause callers to fail. */
2338 strcpy (shortname, "?");
2339 return shortname;
2342 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2344 register int left = 8; /* maximum number of chars in part */
2345 register int extn = 0; /* extension added? */
2346 register int dots = 2; /* maximum number of dots allowed */
2348 while (name < path)
2349 *str++ = *name++; /* skip past UNC header */
2351 while ((c = *name++))
2353 switch ( c )
2355 case ':':
2356 case '\\':
2357 case '/':
2358 *str++ = (c == ':' ? ':' : '\\');
2359 extn = 0; /* reset extension flags */
2360 dots = 2; /* max 2 dots */
2361 left = 8; /* max length 8 for main part */
2362 break;
2363 case '.':
2364 if ( dots )
2366 /* Convert path components of the form .xxx to _xxx,
2367 but leave . and .. as they are. This allows .emacs
2368 to be read as _emacs, for example. */
2370 if (! *name ||
2371 *name == '.' ||
2372 IS_DIRECTORY_SEP (*name))
2374 *str++ = '.';
2375 dots--;
2377 else
2379 *str++ = '_';
2380 left--;
2381 dots = 0;
2384 else if ( !extn )
2386 *str++ = '.';
2387 extn = 1; /* we've got an extension */
2388 left = 3; /* 3 chars in extension */
2390 else
2392 /* any embedded dots after the first are converted to _ */
2393 *str++ = '_';
2395 break;
2396 case '~':
2397 case '#': /* don't lose these, they're important */
2398 if ( ! left )
2399 str[-1] = c; /* replace last character of part */
2400 /* FALLTHRU */
2401 default:
2402 if ( left )
2404 *str++ = tolower (c); /* map to lower case (looks nicer) */
2405 left--;
2406 dots = 0; /* started a path component */
2408 break;
2411 *str = '\0';
2413 else
2415 strcpy (shortname, name);
2416 unixtodos_filename (shortname);
2419 if (pPath)
2420 *pPath = shortname + (path - save_name);
2422 return shortname;
2425 static int
2426 is_exec (const char * name)
2428 char * p = strrchr (name, '.');
2429 return
2430 (p != NULL
2431 && (xstrcasecmp (p, ".exe") == 0 ||
2432 xstrcasecmp (p, ".com") == 0 ||
2433 xstrcasecmp (p, ".bat") == 0 ||
2434 xstrcasecmp (p, ".cmd") == 0));
2437 /* Emulate the Unix directory procedures opendir, closedir,
2438 and readdir. We can't use the procedures supplied in sysdep.c,
2439 so we provide them here. */
2441 struct direct dir_static; /* simulated directory contents */
2442 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2443 static int dir_is_fat;
2444 static char dir_pathname[MAXPATHLEN+1];
2445 static WIN32_FIND_DATA dir_find_data;
2447 /* Support shares on a network resource as subdirectories of a read-only
2448 root directory. */
2449 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2450 static HANDLE open_unc_volume (const char *);
2451 static char *read_unc_volume (HANDLE, char *, int);
2452 static void close_unc_volume (HANDLE);
2454 DIR *
2455 opendir (char *filename)
2457 DIR *dirp;
2459 /* Opening is done by FindFirstFile. However, a read is inherent to
2460 this operation, so we defer the open until read time. */
2462 if (dir_find_handle != INVALID_HANDLE_VALUE)
2463 return NULL;
2464 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2465 return NULL;
2467 /* Note: We don't support traversal of UNC volumes via symlinks.
2468 Doing so would mean punishing 99.99% of use cases by resolving
2469 all the possible symlinks in FILENAME, recursively. */
2470 if (is_unc_volume (filename))
2472 wnet_enum_handle = open_unc_volume (filename);
2473 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2474 return NULL;
2477 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2478 return NULL;
2480 dirp->dd_fd = 0;
2481 dirp->dd_loc = 0;
2482 dirp->dd_size = 0;
2484 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2485 dir_pathname[MAXPATHLEN] = '\0';
2486 /* Note: We don't support symlinks to file names on FAT volumes.
2487 Doing so would mean punishing 99.99% of use cases by resolving
2488 all the possible symlinks in FILENAME, recursively. */
2489 dir_is_fat = is_fat_volume (filename, NULL);
2491 return dirp;
2494 void
2495 closedir (DIR *dirp)
2497 /* If we have a find-handle open, close it. */
2498 if (dir_find_handle != INVALID_HANDLE_VALUE)
2500 FindClose (dir_find_handle);
2501 dir_find_handle = INVALID_HANDLE_VALUE;
2503 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2505 close_unc_volume (wnet_enum_handle);
2506 wnet_enum_handle = INVALID_HANDLE_VALUE;
2508 xfree ((char *) dirp);
2511 struct direct *
2512 readdir (DIR *dirp)
2514 int downcase = !NILP (Vw32_downcase_file_names);
2516 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2518 if (!read_unc_volume (wnet_enum_handle,
2519 dir_find_data.cFileName,
2520 MAX_PATH))
2521 return NULL;
2523 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2524 else if (dir_find_handle == INVALID_HANDLE_VALUE)
2526 char filename[MAXNAMLEN + 3];
2527 int ln;
2529 strcpy (filename, dir_pathname);
2530 ln = strlen (filename) - 1;
2531 if (!IS_DIRECTORY_SEP (filename[ln]))
2532 strcat (filename, "\\");
2533 strcat (filename, "*");
2535 /* Note: No need to resolve symlinks in FILENAME, because
2536 FindFirst opens the directory that is the target of a
2537 symlink. */
2538 dir_find_handle = FindFirstFile (filename, &dir_find_data);
2540 if (dir_find_handle == INVALID_HANDLE_VALUE)
2541 return NULL;
2543 else
2545 if (!FindNextFile (dir_find_handle, &dir_find_data))
2546 return NULL;
2549 /* Emacs never uses this value, so don't bother making it match
2550 value returned by stat(). */
2551 dir_static.d_ino = 1;
2553 strcpy (dir_static.d_name, dir_find_data.cFileName);
2555 /* If the file name in cFileName[] includes `?' characters, it means
2556 the original file name used characters that cannot be represented
2557 by the current ANSI codepage. To avoid total lossage, retrieve
2558 the short 8+3 alias of the long file name. */
2559 if (_mbspbrk (dir_static.d_name, "?"))
2561 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2562 downcase = 1; /* 8+3 aliases are returned in all caps */
2564 dir_static.d_namlen = strlen (dir_static.d_name);
2565 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
2566 dir_static.d_namlen - dir_static.d_namlen % 4;
2568 /* If the file name in cFileName[] includes `?' characters, it means
2569 the original file name used characters that cannot be represented
2570 by the current ANSI codepage. To avoid total lossage, retrieve
2571 the short 8+3 alias of the long file name. */
2572 if (_mbspbrk (dir_find_data.cFileName, "?"))
2574 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2575 /* 8+3 aliases are returned in all caps, which could break
2576 various alists that look at filenames' extensions. */
2577 downcase = 1;
2579 else
2580 strcpy (dir_static.d_name, dir_find_data.cFileName);
2581 dir_static.d_namlen = strlen (dir_static.d_name);
2582 if (dir_is_fat)
2583 _strlwr (dir_static.d_name);
2584 else if (downcase)
2586 register char *p;
2587 for (p = dir_static.d_name; *p; p++)
2588 if (*p >= 'a' && *p <= 'z')
2589 break;
2590 if (!*p)
2591 _strlwr (dir_static.d_name);
2594 return &dir_static;
2597 static HANDLE
2598 open_unc_volume (const char *path)
2600 NETRESOURCE nr;
2601 HANDLE henum;
2602 int result;
2604 nr.dwScope = RESOURCE_GLOBALNET;
2605 nr.dwType = RESOURCETYPE_DISK;
2606 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
2607 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
2608 nr.lpLocalName = NULL;
2609 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
2610 nr.lpComment = NULL;
2611 nr.lpProvider = NULL;
2613 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
2614 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
2616 if (result == NO_ERROR)
2617 return henum;
2618 else
2619 return INVALID_HANDLE_VALUE;
2622 static char *
2623 read_unc_volume (HANDLE henum, char *readbuf, int size)
2625 DWORD count;
2626 int result;
2627 DWORD bufsize = 512;
2628 char *buffer;
2629 char *ptr;
2631 count = 1;
2632 buffer = alloca (bufsize);
2633 result = WNetEnumResource (henum, &count, buffer, &bufsize);
2634 if (result != NO_ERROR)
2635 return NULL;
2637 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2638 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
2639 ptr += 2;
2640 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
2641 ptr++;
2643 strncpy (readbuf, ptr, size);
2644 return readbuf;
2647 static void
2648 close_unc_volume (HANDLE henum)
2650 if (henum != INVALID_HANDLE_VALUE)
2651 WNetCloseEnum (henum);
2654 static DWORD
2655 unc_volume_file_attributes (const char *path)
2657 HANDLE henum;
2658 DWORD attrs;
2660 henum = open_unc_volume (path);
2661 if (henum == INVALID_HANDLE_VALUE)
2662 return -1;
2664 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
2666 close_unc_volume (henum);
2668 return attrs;
2671 /* Ensure a network connection is authenticated. */
2672 static void
2673 logon_network_drive (const char *path)
2675 NETRESOURCE resource;
2676 char share[MAX_PATH];
2677 int i, n_slashes;
2678 char drive[4];
2679 UINT drvtype;
2681 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
2682 drvtype = DRIVE_REMOTE;
2683 else if (path[0] == '\0' || path[1] != ':')
2684 drvtype = GetDriveType (NULL);
2685 else
2687 drive[0] = path[0];
2688 drive[1] = ':';
2689 drive[2] = '\\';
2690 drive[3] = '\0';
2691 drvtype = GetDriveType (drive);
2694 /* Only logon to networked drives. */
2695 if (drvtype != DRIVE_REMOTE)
2696 return;
2698 n_slashes = 2;
2699 strncpy (share, path, MAX_PATH);
2700 /* Truncate to just server and share name. */
2701 for (i = 2; i < MAX_PATH; i++)
2703 if (IS_DIRECTORY_SEP (share[i]) && ++n_slashes > 3)
2705 share[i] = '\0';
2706 break;
2710 resource.dwType = RESOURCETYPE_DISK;
2711 resource.lpLocalName = NULL;
2712 resource.lpRemoteName = share;
2713 resource.lpProvider = NULL;
2715 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
2718 /* Shadow some MSVC runtime functions to map requests for long filenames
2719 to reasonable short names if necessary. This was originally added to
2720 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2721 long file names. */
2724 sys_access (const char * path, int mode)
2726 DWORD attributes;
2728 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
2729 newer versions blow up when passed D_OK. */
2730 path = map_w32_filename (path, NULL);
2731 /* If the last element of PATH is a symlink, we need to resolve it
2732 to get the attributes of its target file. Note: any symlinks in
2733 PATH elements other than the last one are transparently resolved
2734 by GetFileAttributes below. */
2735 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
2736 path = chase_symlinks (path);
2738 if ((attributes = GetFileAttributes (path)) == -1)
2740 DWORD w32err = GetLastError ();
2742 switch (w32err)
2744 case ERROR_INVALID_NAME:
2745 case ERROR_BAD_PATHNAME:
2746 if (is_unc_volume (path))
2748 attributes = unc_volume_file_attributes (path);
2749 if (attributes == -1)
2751 errno = EACCES;
2752 return -1;
2754 break;
2756 /* FALLTHROUGH */
2757 case ERROR_FILE_NOT_FOUND:
2758 case ERROR_BAD_NETPATH:
2759 errno = ENOENT;
2760 break;
2761 default:
2762 errno = EACCES;
2763 break;
2765 return -1;
2767 if ((mode & X_OK) != 0 && !is_exec (path))
2769 errno = EACCES;
2770 return -1;
2772 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
2774 errno = EACCES;
2775 return -1;
2777 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
2779 errno = EACCES;
2780 return -1;
2782 return 0;
2786 sys_chdir (const char * path)
2788 return _chdir (map_w32_filename (path, NULL));
2792 sys_chmod (const char * path, int mode)
2794 path = chase_symlinks (map_w32_filename (path, NULL));
2795 return _chmod (path, mode);
2799 sys_chown (const char *path, uid_t owner, gid_t group)
2801 if (sys_chmod (path, S_IREAD) == -1) /* check if file exists */
2802 return -1;
2803 return 0;
2807 sys_creat (const char * path, int mode)
2809 return _creat (map_w32_filename (path, NULL), mode);
2812 FILE *
2813 sys_fopen (const char * path, const char * mode)
2815 int fd;
2816 int oflag;
2817 const char * mode_save = mode;
2819 /* Force all file handles to be non-inheritable. This is necessary to
2820 ensure child processes don't unwittingly inherit handles that might
2821 prevent future file access. */
2823 if (mode[0] == 'r')
2824 oflag = O_RDONLY;
2825 else if (mode[0] == 'w' || mode[0] == 'a')
2826 oflag = O_WRONLY | O_CREAT | O_TRUNC;
2827 else
2828 return NULL;
2830 /* Only do simplistic option parsing. */
2831 while (*++mode)
2832 if (mode[0] == '+')
2834 oflag &= ~(O_RDONLY | O_WRONLY);
2835 oflag |= O_RDWR;
2837 else if (mode[0] == 'b')
2839 oflag &= ~O_TEXT;
2840 oflag |= O_BINARY;
2842 else if (mode[0] == 't')
2844 oflag &= ~O_BINARY;
2845 oflag |= O_TEXT;
2847 else break;
2849 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
2850 if (fd < 0)
2851 return NULL;
2853 return _fdopen (fd, mode_save);
2856 /* This only works on NTFS volumes, but is useful to have. */
2858 sys_link (const char * old, const char * new)
2860 HANDLE fileh;
2861 int result = -1;
2862 char oldname[MAX_PATH], newname[MAX_PATH];
2864 if (old == NULL || new == NULL)
2866 errno = ENOENT;
2867 return -1;
2870 strcpy (oldname, map_w32_filename (old, NULL));
2871 strcpy (newname, map_w32_filename (new, NULL));
2873 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
2874 FILE_FLAG_BACKUP_SEMANTICS, NULL);
2875 if (fileh != INVALID_HANDLE_VALUE)
2877 int wlen;
2879 /* Confusingly, the "alternate" stream name field does not apply
2880 when restoring a hard link, and instead contains the actual
2881 stream data for the link (ie. the name of the link to create).
2882 The WIN32_STREAM_ID structure before the cStreamName field is
2883 the stream header, which is then immediately followed by the
2884 stream data. */
2886 struct {
2887 WIN32_STREAM_ID wid;
2888 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
2889 } data;
2891 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
2892 data.wid.cStreamName, MAX_PATH);
2893 if (wlen > 0)
2895 LPVOID context = NULL;
2896 DWORD wbytes = 0;
2898 data.wid.dwStreamId = BACKUP_LINK;
2899 data.wid.dwStreamAttributes = 0;
2900 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
2901 data.wid.Size.HighPart = 0;
2902 data.wid.dwStreamNameSize = 0;
2904 if (BackupWrite (fileh, (LPBYTE)&data,
2905 offsetof (WIN32_STREAM_ID, cStreamName)
2906 + data.wid.Size.LowPart,
2907 &wbytes, FALSE, FALSE, &context)
2908 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
2910 /* succeeded */
2911 result = 0;
2913 else
2915 /* Should try mapping GetLastError to errno; for now just
2916 indicate a general error (eg. links not supported). */
2917 errno = EINVAL; // perhaps EMLINK?
2921 CloseHandle (fileh);
2923 else
2924 errno = ENOENT;
2926 return result;
2930 sys_mkdir (const char * path)
2932 return _mkdir (map_w32_filename (path, NULL));
2935 /* Because of long name mapping issues, we need to implement this
2936 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2937 a unique name, instead of setting the input template to an empty
2938 string.
2940 Standard algorithm seems to be use pid or tid with a letter on the
2941 front (in place of the 6 X's) and cycle through the letters to find a
2942 unique name. We extend that to allow any reasonable character as the
2943 first of the 6 X's. */
2944 char *
2945 sys_mktemp (char * template)
2947 char * p;
2948 int i;
2949 unsigned uid = GetCurrentThreadId ();
2950 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2952 if (template == NULL)
2953 return NULL;
2954 p = template + strlen (template);
2955 i = 5;
2956 /* replace up to the last 5 X's with uid in decimal */
2957 while (--p >= template && p[0] == 'X' && --i >= 0)
2959 p[0] = '0' + uid % 10;
2960 uid /= 10;
2963 if (i < 0 && p[0] == 'X')
2965 i = 0;
2968 int save_errno = errno;
2969 p[0] = first_char[i];
2970 if (sys_access (template, 0) < 0)
2972 errno = save_errno;
2973 return template;
2976 while (++i < sizeof (first_char));
2979 /* Template is badly formed or else we can't generate a unique name,
2980 so return empty string */
2981 template[0] = 0;
2982 return template;
2986 sys_open (const char * path, int oflag, int mode)
2988 const char* mpath = map_w32_filename (path, NULL);
2989 /* Try to open file without _O_CREAT, to be able to write to hidden
2990 and system files. Force all file handles to be
2991 non-inheritable. */
2992 int res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
2993 if (res >= 0)
2994 return res;
2995 return _open (mpath, oflag | _O_NOINHERIT, mode);
2999 sys_rename (const char * oldname, const char * newname)
3001 BOOL result;
3002 char temp[MAX_PATH];
3003 int newname_dev;
3004 int oldname_dev;
3006 /* MoveFile on Windows 95 doesn't correctly change the short file name
3007 alias in a number of circumstances (it is not easy to predict when
3008 just by looking at oldname and newname, unfortunately). In these
3009 cases, renaming through a temporary name avoids the problem.
3011 A second problem on Windows 95 is that renaming through a temp name when
3012 newname is uppercase fails (the final long name ends up in
3013 lowercase, although the short alias might be uppercase) UNLESS the
3014 long temp name is not 8.3.
3016 So, on Windows 95 we always rename through a temp name, and we make sure
3017 the temp name has a long extension to ensure correct renaming. */
3019 strcpy (temp, map_w32_filename (oldname, NULL));
3021 /* volume_info is set indirectly by map_w32_filename. */
3022 oldname_dev = volume_info.serialnum;
3024 if (os_subtype == OS_9X)
3026 char * o;
3027 char * p;
3028 int i = 0;
3030 oldname = map_w32_filename (oldname, NULL);
3031 if ((o = strrchr (oldname, '\\')))
3032 o++;
3033 else
3034 o = (char *) oldname;
3036 if ((p = strrchr (temp, '\\')))
3037 p++;
3038 else
3039 p = temp;
3043 /* Force temp name to require a manufactured 8.3 alias - this
3044 seems to make the second rename work properly. */
3045 sprintf (p, "_.%s.%u", o, i);
3046 i++;
3047 result = rename (oldname, temp);
3049 /* This loop must surely terminate! */
3050 while (result < 0 && errno == EEXIST);
3051 if (result < 0)
3052 return -1;
3055 /* Emulate Unix behavior - newname is deleted if it already exists
3056 (at least if it is a file; don't do this for directories).
3058 Since we mustn't do this if we are just changing the case of the
3059 file name (we would end up deleting the file we are trying to
3060 rename!), we let rename detect if the destination file already
3061 exists - that way we avoid the possible pitfalls of trying to
3062 determine ourselves whether two names really refer to the same
3063 file, which is not always possible in the general case. (Consider
3064 all the permutations of shared or subst'd drives, etc.) */
3066 newname = map_w32_filename (newname, NULL);
3068 /* volume_info is set indirectly by map_w32_filename. */
3069 newname_dev = volume_info.serialnum;
3071 result = rename (temp, newname);
3073 if (result < 0)
3075 DWORD w32err = GetLastError ();
3077 if (errno == EACCES
3078 && newname_dev != oldname_dev)
3080 /* The implementation of `rename' on Windows does not return
3081 errno = EXDEV when you are moving a directory to a
3082 different storage device (ex. logical disk). It returns
3083 EACCES instead. So here we handle such situations and
3084 return EXDEV. */
3085 DWORD attributes;
3087 if ((attributes = GetFileAttributes (temp)) != -1
3088 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3089 errno = EXDEV;
3091 else if (errno == EEXIST)
3093 if (_chmod (newname, 0666) != 0)
3094 return result;
3095 if (_unlink (newname) != 0)
3096 return result;
3097 result = rename (temp, newname);
3099 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3100 && is_symlink (temp))
3102 /* This is Windows prohibiting the user from creating a
3103 symlink in another place, since that requires
3104 privileges. */
3105 errno = EPERM;
3109 return result;
3113 sys_rmdir (const char * path)
3115 return _rmdir (map_w32_filename (path, NULL));
3119 sys_unlink (const char * path)
3121 path = map_w32_filename (path, NULL);
3123 /* On Unix, unlink works without write permission. */
3124 _chmod (path, 0666);
3125 return _unlink (path);
3128 static FILETIME utc_base_ft;
3129 static ULONGLONG utc_base; /* In 100ns units */
3130 static int init = 0;
3132 #define FILETIME_TO_U64(result, ft) \
3133 do { \
3134 ULARGE_INTEGER uiTemp; \
3135 uiTemp.LowPart = (ft).dwLowDateTime; \
3136 uiTemp.HighPart = (ft).dwHighDateTime; \
3137 result = uiTemp.QuadPart; \
3138 } while (0)
3140 static void
3141 initialize_utc_base (void)
3143 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3144 SYSTEMTIME st;
3146 st.wYear = 1970;
3147 st.wMonth = 1;
3148 st.wDay = 1;
3149 st.wHour = 0;
3150 st.wMinute = 0;
3151 st.wSecond = 0;
3152 st.wMilliseconds = 0;
3154 SystemTimeToFileTime (&st, &utc_base_ft);
3155 FILETIME_TO_U64 (utc_base, utc_base_ft);
3158 static time_t
3159 convert_time (FILETIME ft)
3161 ULONGLONG tmp;
3163 if (!init)
3165 initialize_utc_base ();
3166 init = 1;
3169 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3170 return 0;
3172 FILETIME_TO_U64 (tmp, ft);
3173 return (time_t) ((tmp - utc_base) / 10000000L);
3176 static void
3177 convert_from_time_t (time_t time, FILETIME * pft)
3179 ULARGE_INTEGER tmp;
3181 if (!init)
3183 initialize_utc_base ();
3184 init = 1;
3187 /* time in 100ns units since 1-Jan-1601 */
3188 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3189 pft->dwHighDateTime = tmp.HighPart;
3190 pft->dwLowDateTime = tmp.LowPart;
3193 #if 0
3194 /* No reason to keep this; faking inode values either by hashing or even
3195 using the file index from GetInformationByHandle, is not perfect and
3196 so by default Emacs doesn't use the inode values on Windows.
3197 Instead, we now determine file-truename correctly (except for
3198 possible drive aliasing etc). */
3200 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3201 static unsigned
3202 hashval (const unsigned char * str)
3204 unsigned h = 0;
3205 while (*str)
3207 h = (h << 4) + *str++;
3208 h ^= (h >> 28);
3210 return h;
3213 /* Return the hash value of the canonical pathname, excluding the
3214 drive/UNC header, to get a hopefully unique inode number. */
3215 static DWORD
3216 generate_inode_val (const char * name)
3218 char fullname[ MAX_PATH ];
3219 char * p;
3220 unsigned hash;
3222 /* Get the truly canonical filename, if it exists. (Note: this
3223 doesn't resolve aliasing due to subst commands, or recognize hard
3224 links. */
3225 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3226 emacs_abort ();
3228 parse_root (fullname, &p);
3229 /* Normal W32 filesystems are still case insensitive. */
3230 _strlwr (p);
3231 return hashval (p);
3234 #endif
3236 static PSECURITY_DESCRIPTOR
3237 get_file_security_desc_by_handle (HANDLE h)
3239 PSECURITY_DESCRIPTOR psd = NULL;
3240 DWORD err;
3241 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3242 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3244 err = get_security_info (h, SE_FILE_OBJECT, si,
3245 NULL, NULL, NULL, NULL, &psd);
3246 if (err != ERROR_SUCCESS)
3247 return NULL;
3249 return psd;
3252 static PSECURITY_DESCRIPTOR
3253 get_file_security_desc_by_name (const char *fname)
3255 PSECURITY_DESCRIPTOR psd = NULL;
3256 DWORD sd_len, err;
3257 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3258 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3260 if (!get_file_security (fname, si, psd, 0, &sd_len))
3262 err = GetLastError ();
3263 if (err != ERROR_INSUFFICIENT_BUFFER)
3264 return NULL;
3267 psd = xmalloc (sd_len);
3268 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3270 xfree (psd);
3271 return NULL;
3274 return psd;
3277 static DWORD
3278 get_rid (PSID sid)
3280 unsigned n_subauthorities;
3282 /* Use the last sub-authority value of the RID, the relative
3283 portion of the SID, as user/group ID. */
3284 n_subauthorities = *get_sid_sub_authority_count (sid);
3285 if (n_subauthorities < 1)
3286 return 0; /* the "World" RID */
3287 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3290 /* Caching SID and account values for faster lokup. */
3292 #ifdef __GNUC__
3293 # define FLEXIBLE_ARRAY_MEMBER
3294 #else
3295 # define FLEXIBLE_ARRAY_MEMBER 1
3296 #endif
3298 struct w32_id {
3299 unsigned rid;
3300 struct w32_id *next;
3301 char name[GNLEN+1];
3302 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3305 static struct w32_id *w32_idlist;
3307 static int
3308 w32_cached_id (PSID sid, unsigned *id, char *name)
3310 struct w32_id *tail, *found;
3312 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3314 if (equal_sid ((PSID)tail->sid, sid))
3316 found = tail;
3317 break;
3320 if (found)
3322 *id = found->rid;
3323 strcpy (name, found->name);
3324 return 1;
3326 else
3327 return 0;
3330 static void
3331 w32_add_to_cache (PSID sid, unsigned id, char *name)
3333 DWORD sid_len;
3334 struct w32_id *new_entry;
3336 /* We don't want to leave behind stale cache from when Emacs was
3337 dumped. */
3338 if (initialized)
3340 sid_len = get_length_sid (sid);
3341 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3342 if (new_entry)
3344 new_entry->rid = id;
3345 strcpy (new_entry->name, name);
3346 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3347 new_entry->next = w32_idlist;
3348 w32_idlist = new_entry;
3353 #define UID 1
3354 #define GID 2
3356 static int
3357 get_name_and_id (PSECURITY_DESCRIPTOR psd, const char *fname,
3358 unsigned *id, char *nm, int what)
3360 PSID sid = NULL;
3361 char machine[MAX_COMPUTERNAME_LENGTH+1];
3362 BOOL dflt;
3363 SID_NAME_USE ignore;
3364 char name[UNLEN+1];
3365 DWORD name_len = sizeof (name);
3366 char domain[1024];
3367 DWORD domain_len = sizeof (domain);
3368 char *mp = NULL;
3369 int use_dflt = 0;
3370 int result;
3372 if (what == UID)
3373 result = get_security_descriptor_owner (psd, &sid, &dflt);
3374 else if (what == GID)
3375 result = get_security_descriptor_group (psd, &sid, &dflt);
3376 else
3377 result = 0;
3379 if (!result || !is_valid_sid (sid))
3380 use_dflt = 1;
3381 else if (!w32_cached_id (sid, id, nm))
3383 /* If FNAME is a UNC, we need to lookup account on the
3384 specified machine. */
3385 if (IS_DIRECTORY_SEP (fname[0]) && IS_DIRECTORY_SEP (fname[1])
3386 && fname[2] != '\0')
3388 const char *s;
3389 char *p;
3391 for (s = fname + 2, p = machine;
3392 *s && !IS_DIRECTORY_SEP (*s); s++, p++)
3393 *p = *s;
3394 *p = '\0';
3395 mp = machine;
3398 if (!lookup_account_sid (mp, sid, name, &name_len,
3399 domain, &domain_len, &ignore)
3400 || name_len > UNLEN+1)
3401 use_dflt = 1;
3402 else
3404 *id = get_rid (sid);
3405 strcpy (nm, name);
3406 w32_add_to_cache (sid, *id, name);
3409 return use_dflt;
3412 static void
3413 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd,
3414 const char *fname,
3415 struct stat *st)
3417 int dflt_usr = 0, dflt_grp = 0;
3419 if (!psd)
3421 dflt_usr = 1;
3422 dflt_grp = 1;
3424 else
3426 if (get_name_and_id (psd, fname, &st->st_uid, st->st_uname, UID))
3427 dflt_usr = 1;
3428 if (get_name_and_id (psd, fname, &st->st_gid, st->st_gname, GID))
3429 dflt_grp = 1;
3431 /* Consider files to belong to current user/group, if we cannot get
3432 more accurate information. */
3433 if (dflt_usr)
3435 st->st_uid = dflt_passwd.pw_uid;
3436 strcpy (st->st_uname, dflt_passwd.pw_name);
3438 if (dflt_grp)
3440 st->st_gid = dflt_passwd.pw_gid;
3441 strcpy (st->st_gname, dflt_group.gr_name);
3445 /* Return non-zero if NAME is a potentially slow filesystem. */
3447 is_slow_fs (const char *name)
3449 char drive_root[4];
3450 UINT devtype;
3452 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3453 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3454 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3455 devtype = GetDriveType (NULL); /* use root of current drive */
3456 else
3458 /* GetDriveType needs the root directory of the drive. */
3459 strncpy (drive_root, name, 2);
3460 drive_root[2] = '\\';
3461 drive_root[3] = '\0';
3462 devtype = GetDriveType (drive_root);
3464 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3467 /* MSVC stat function can't cope with UNC names and has other bugs, so
3468 replace it with our own. This also allows us to calculate consistent
3469 inode values and owner/group without hacks in the main Emacs code. */
3471 static int
3472 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
3474 char *name, *save_name, *r;
3475 WIN32_FIND_DATA wfd;
3476 HANDLE fh;
3477 unsigned __int64 fake_inode = 0;
3478 int permission;
3479 int len;
3480 int rootdir = FALSE;
3481 PSECURITY_DESCRIPTOR psd = NULL;
3482 int is_a_symlink = 0;
3483 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
3484 DWORD access_rights = 0;
3485 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
3486 FILETIME ctime, atime, wtime;
3488 if (path == NULL || buf == NULL)
3490 errno = EFAULT;
3491 return -1;
3494 save_name = name = (char *) map_w32_filename (path, &path);
3495 /* Must be valid filename, no wild cards or other invalid
3496 characters. We use _mbspbrk to support multibyte strings that
3497 might look to strpbrk as if they included literal *, ?, and other
3498 characters mentioned below that are disallowed by Windows
3499 filesystems. */
3500 if (_mbspbrk (name, "*?|<>\""))
3502 errno = ENOENT;
3503 return -1;
3506 /* Remove trailing directory separator, unless name is the root
3507 directory of a drive or UNC volume in which case ensure there
3508 is a trailing separator. */
3509 len = strlen (name);
3510 name = strcpy (alloca (len + 2), name);
3512 /* Avoid a somewhat costly call to is_symlink if the filesystem
3513 doesn't support symlinks. */
3514 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
3515 is_a_symlink = is_symlink (name);
3517 /* Plan A: Open the file and get all the necessary information via
3518 the resulting handle. This solves several issues in one blow:
3520 . retrieves attributes for the target of a symlink, if needed
3521 . gets attributes of root directories and symlinks pointing to
3522 root directories, thus avoiding the need for special-casing
3523 these and detecting them by examining the file-name format
3524 . retrieves more accurate attributes (e.g., non-zero size for
3525 some directories, esp. directories that are junction points)
3526 . correctly resolves "c:/..", "/.." and similar file names
3527 . avoids run-time penalties for 99% of use cases
3529 Plan A is always tried first, unless the user asked not to (but
3530 if the file is a symlink and we need to follow links, we try Plan
3531 A even if the user asked not to).
3533 If Plan A fails, we go to Plan B (below), where various
3534 potentially expensive techniques must be used to handle "special"
3535 files such as UNC volumes etc. */
3536 if (!(NILP (Vw32_get_true_file_attributes)
3537 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
3538 /* Following symlinks requires getting the info by handle. */
3539 || (is_a_symlink && follow_symlinks))
3541 BY_HANDLE_FILE_INFORMATION info;
3543 if (is_a_symlink && !follow_symlinks)
3544 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
3545 /* READ_CONTROL access rights are required to get security info
3546 by handle. But if the OS doesn't support security in the
3547 first place, we don't need to try. */
3548 if (is_windows_9x () != TRUE)
3549 access_rights |= READ_CONTROL;
3551 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
3552 file_flags, NULL);
3553 /* If CreateFile fails with READ_CONTROL, try again with zero as
3554 access rights. */
3555 if (fh == INVALID_HANDLE_VALUE && access_rights)
3556 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
3557 file_flags, NULL);
3558 if (fh == INVALID_HANDLE_VALUE)
3559 goto no_true_file_attributes;
3561 /* This is more accurate in terms of getting the correct number
3562 of links, but is quite slow (it is noticeable when Emacs is
3563 making a list of file name completions). */
3564 if (GetFileInformationByHandle (fh, &info))
3566 nlinks = info.nNumberOfLinks;
3567 /* Might as well use file index to fake inode values, but this
3568 is not guaranteed to be unique unless we keep a handle open
3569 all the time (even then there are situations where it is
3570 not unique). Reputedly, there are at most 48 bits of info
3571 (on NTFS, presumably less on FAT). */
3572 fake_inode = info.nFileIndexHigh;
3573 fake_inode <<= 32;
3574 fake_inode += info.nFileIndexLow;
3575 serialnum = info.dwVolumeSerialNumber;
3576 fs_high = info.nFileSizeHigh;
3577 fs_low = info.nFileSizeLow;
3578 ctime = info.ftCreationTime;
3579 atime = info.ftLastAccessTime;
3580 wtime = info.ftLastWriteTime;
3581 fattrs = info.dwFileAttributes;
3583 else
3585 /* We don't go to Plan B here, because it's not clear that
3586 it's a good idea. The only known use case where
3587 CreateFile succeeds, but GetFileInformationByHandle fails
3588 (with ERROR_INVALID_FUNCTION) is for character devices
3589 such as NUL, PRN, etc. For these, switching to Plan B is
3590 a net loss, because we lose the character device
3591 attribute returned by GetFileType below (FindFirstFile
3592 doesn't set that bit in the attributes), and the other
3593 fields don't make sense for character devices anyway.
3594 Emacs doesn't really care for non-file entities in the
3595 context of l?stat, so neither do we. */
3597 /* w32err is assigned so one could put a breakpoint here and
3598 examine its value, when GetFileInformationByHandle
3599 fails. */
3600 DWORD w32err = GetLastError ();
3602 switch (w32err)
3604 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
3605 errno = ENOENT;
3606 return -1;
3610 /* Test for a symlink before testing for a directory, since
3611 symlinks to directories have the directory bit set, but we
3612 don't want them to appear as directories. */
3613 if (is_a_symlink && !follow_symlinks)
3614 buf->st_mode = S_IFLNK;
3615 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3616 buf->st_mode = S_IFDIR;
3617 else
3619 DWORD ftype = GetFileType (fh);
3621 switch (ftype)
3623 case FILE_TYPE_DISK:
3624 buf->st_mode = S_IFREG;
3625 break;
3626 case FILE_TYPE_PIPE:
3627 buf->st_mode = S_IFIFO;
3628 break;
3629 case FILE_TYPE_CHAR:
3630 case FILE_TYPE_UNKNOWN:
3631 default:
3632 buf->st_mode = S_IFCHR;
3635 /* We produce the fallback owner and group data, based on the
3636 current user that runs Emacs, in the following cases:
3638 . this is Windows 9X
3639 . getting security by handle failed, and we need to produce
3640 information for the target of a symlink (this is better
3641 than producing a potentially misleading info about the
3642 symlink itself)
3644 If getting security by handle fails, and we don't need to
3645 resolve symlinks, we try getting security by name. */
3646 if (is_windows_9x () != TRUE)
3647 psd = get_file_security_desc_by_handle (fh);
3648 if (psd)
3650 get_file_owner_and_group (psd, name, buf);
3651 LocalFree (psd);
3653 else if (is_windows_9x () == TRUE)
3654 get_file_owner_and_group (NULL, name, buf);
3655 else if (!(is_a_symlink && follow_symlinks))
3657 psd = get_file_security_desc_by_name (name);
3658 get_file_owner_and_group (psd, name, buf);
3659 xfree (psd);
3661 else
3662 get_file_owner_and_group (NULL, name, buf);
3663 CloseHandle (fh);
3665 else
3667 no_true_file_attributes:
3668 /* Plan B: Either getting a handle on the file failed, or the
3669 caller explicitly asked us to not bother making this
3670 information more accurate.
3672 Implementation note: In Plan B, we never bother to resolve
3673 symlinks, even if we got here because we tried Plan A and
3674 failed. That's because, even if the caller asked for extra
3675 precision by setting Vw32_get_true_file_attributes to t,
3676 resolving symlinks requires acquiring a file handle to the
3677 symlink, which we already know will fail. And if the user
3678 did not ask for extra precision, resolving symlinks will fly
3679 in the face of that request, since the user then wants the
3680 lightweight version of the code. */
3681 rootdir = (path >= save_name + len - 1
3682 && (IS_DIRECTORY_SEP (*path) || *path == 0));
3684 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3685 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
3686 if (IS_DIRECTORY_SEP (r[0])
3687 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
3688 r[1] = r[2] = '\0';
3690 /* Note: If NAME is a symlink to the root of a UNC volume
3691 (i.e. "\\SERVER"), we will not detect that here, and we will
3692 return data about the symlink as result of FindFirst below.
3693 This is unfortunate, but that marginal use case does not
3694 justify a call to chase_symlinks which would impose a penalty
3695 on all the other use cases. (We get here for symlinks to
3696 roots of UNC volumes because CreateFile above fails for them,
3697 unlike with symlinks to root directories X:\ of drives.) */
3698 if (is_unc_volume (name))
3700 fattrs = unc_volume_file_attributes (name);
3701 if (fattrs == -1)
3702 return -1;
3704 ctime = atime = wtime = utc_base_ft;
3706 else if (rootdir)
3708 if (!IS_DIRECTORY_SEP (name[len-1]))
3709 strcat (name, "\\");
3710 if (GetDriveType (name) < 2)
3712 errno = ENOENT;
3713 return -1;
3716 fattrs = FILE_ATTRIBUTE_DIRECTORY;
3717 ctime = atime = wtime = utc_base_ft;
3719 else
3721 if (IS_DIRECTORY_SEP (name[len-1]))
3722 name[len - 1] = 0;
3724 /* (This is hacky, but helps when doing file completions on
3725 network drives.) Optimize by using information available from
3726 active readdir if possible. */
3727 len = strlen (dir_pathname);
3728 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
3729 len--;
3730 if (dir_find_handle != INVALID_HANDLE_VALUE
3731 && !(is_a_symlink && follow_symlinks)
3732 && strnicmp (save_name, dir_pathname, len) == 0
3733 && IS_DIRECTORY_SEP (name[len])
3734 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
3736 /* This was the last entry returned by readdir. */
3737 wfd = dir_find_data;
3739 else
3741 logon_network_drive (name);
3743 fh = FindFirstFile (name, &wfd);
3744 if (fh == INVALID_HANDLE_VALUE)
3746 errno = ENOENT;
3747 return -1;
3749 FindClose (fh);
3751 /* Note: if NAME is a symlink, the information we get from
3752 FindFirstFile is for the symlink, not its target. */
3753 fattrs = wfd.dwFileAttributes;
3754 ctime = wfd.ftCreationTime;
3755 atime = wfd.ftLastAccessTime;
3756 wtime = wfd.ftLastWriteTime;
3757 fs_high = wfd.nFileSizeHigh;
3758 fs_low = wfd.nFileSizeLow;
3759 fake_inode = 0;
3760 nlinks = 1;
3761 serialnum = volume_info.serialnum;
3763 if (is_a_symlink && !follow_symlinks)
3764 buf->st_mode = S_IFLNK;
3765 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3766 buf->st_mode = S_IFDIR;
3767 else
3768 buf->st_mode = S_IFREG;
3770 get_file_owner_and_group (NULL, name, buf);
3773 #if 0
3774 /* Not sure if there is any point in this. */
3775 if (!NILP (Vw32_generate_fake_inodes))
3776 fake_inode = generate_inode_val (name);
3777 else if (fake_inode == 0)
3779 /* For want of something better, try to make everything unique. */
3780 static DWORD gen_num = 0;
3781 fake_inode = ++gen_num;
3783 #endif
3785 buf->st_ino = fake_inode;
3787 buf->st_dev = serialnum;
3788 buf->st_rdev = serialnum;
3790 buf->st_size = fs_high;
3791 buf->st_size <<= 32;
3792 buf->st_size += fs_low;
3793 buf->st_nlink = nlinks;
3795 /* Convert timestamps to Unix format. */
3796 buf->st_mtime = convert_time (wtime);
3797 buf->st_atime = convert_time (atime);
3798 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3799 buf->st_ctime = convert_time (ctime);
3800 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3802 /* determine rwx permissions */
3803 if (is_a_symlink && !follow_symlinks)
3804 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
3805 else
3807 if (fattrs & FILE_ATTRIBUTE_READONLY)
3808 permission = S_IREAD;
3809 else
3810 permission = S_IREAD | S_IWRITE;
3812 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
3813 permission |= S_IEXEC;
3814 else if (is_exec (name))
3815 permission |= S_IEXEC;
3818 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3820 return 0;
3824 stat (const char * path, struct stat * buf)
3826 return stat_worker (path, buf, 1);
3830 lstat (const char * path, struct stat * buf)
3832 return stat_worker (path, buf, 0);
3835 /* Provide fstat and utime as well as stat for consistent handling of
3836 file timestamps. */
3838 fstat (int desc, struct stat * buf)
3840 HANDLE fh = (HANDLE) _get_osfhandle (desc);
3841 BY_HANDLE_FILE_INFORMATION info;
3842 unsigned __int64 fake_inode;
3843 int permission;
3845 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
3847 case FILE_TYPE_DISK:
3848 buf->st_mode = S_IFREG;
3849 if (!GetFileInformationByHandle (fh, &info))
3851 errno = EACCES;
3852 return -1;
3854 break;
3855 case FILE_TYPE_PIPE:
3856 buf->st_mode = S_IFIFO;
3857 goto non_disk;
3858 case FILE_TYPE_CHAR:
3859 case FILE_TYPE_UNKNOWN:
3860 default:
3861 buf->st_mode = S_IFCHR;
3862 non_disk:
3863 memset (&info, 0, sizeof (info));
3864 info.dwFileAttributes = 0;
3865 info.ftCreationTime = utc_base_ft;
3866 info.ftLastAccessTime = utc_base_ft;
3867 info.ftLastWriteTime = utc_base_ft;
3870 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3871 buf->st_mode = S_IFDIR;
3873 buf->st_nlink = info.nNumberOfLinks;
3874 /* Might as well use file index to fake inode values, but this
3875 is not guaranteed to be unique unless we keep a handle open
3876 all the time (even then there are situations where it is
3877 not unique). Reputedly, there are at most 48 bits of info
3878 (on NTFS, presumably less on FAT). */
3879 fake_inode = info.nFileIndexHigh;
3880 fake_inode <<= 32;
3881 fake_inode += info.nFileIndexLow;
3883 /* MSVC defines _ino_t to be short; other libc's might not. */
3884 if (sizeof (buf->st_ino) == 2)
3885 buf->st_ino = fake_inode ^ (fake_inode >> 16);
3886 else
3887 buf->st_ino = fake_inode;
3889 /* Consider files to belong to current user.
3890 FIXME: this should use GetSecurityInfo API, but it is only
3891 available for _WIN32_WINNT >= 0x501. */
3892 buf->st_uid = dflt_passwd.pw_uid;
3893 buf->st_gid = dflt_passwd.pw_gid;
3894 strcpy (buf->st_uname, dflt_passwd.pw_name);
3895 strcpy (buf->st_gname, dflt_group.gr_name);
3897 buf->st_dev = info.dwVolumeSerialNumber;
3898 buf->st_rdev = info.dwVolumeSerialNumber;
3900 buf->st_size = info.nFileSizeHigh;
3901 buf->st_size <<= 32;
3902 buf->st_size += info.nFileSizeLow;
3904 /* Convert timestamps to Unix format. */
3905 buf->st_mtime = convert_time (info.ftLastWriteTime);
3906 buf->st_atime = convert_time (info.ftLastAccessTime);
3907 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3908 buf->st_ctime = convert_time (info.ftCreationTime);
3909 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3911 /* determine rwx permissions */
3912 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
3913 permission = S_IREAD;
3914 else
3915 permission = S_IREAD | S_IWRITE;
3917 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3918 permission |= S_IEXEC;
3919 else
3921 #if 0 /* no way of knowing the filename */
3922 char * p = strrchr (name, '.');
3923 if (p != NULL &&
3924 (xstrcasecmp (p, ".exe") == 0 ||
3925 xstrcasecmp (p, ".com") == 0 ||
3926 xstrcasecmp (p, ".bat") == 0 ||
3927 xstrcasecmp (p, ".cmd") == 0))
3928 permission |= S_IEXEC;
3929 #endif
3932 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3934 return 0;
3938 utime (const char *name, struct utimbuf *times)
3940 struct utimbuf deftime;
3941 HANDLE fh;
3942 FILETIME mtime;
3943 FILETIME atime;
3945 if (times == NULL)
3947 deftime.modtime = deftime.actime = time (NULL);
3948 times = &deftime;
3951 /* Need write access to set times. */
3952 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
3953 /* If NAME specifies a directory, FILE_SHARE_DELETE
3954 allows other processes to delete files inside it,
3955 while we have the directory open. */
3956 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3957 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
3958 if (fh != INVALID_HANDLE_VALUE)
3960 convert_from_time_t (times->actime, &atime);
3961 convert_from_time_t (times->modtime, &mtime);
3962 if (!SetFileTime (fh, NULL, &atime, &mtime))
3964 CloseHandle (fh);
3965 errno = EACCES;
3966 return -1;
3968 CloseHandle (fh);
3970 else
3972 errno = EINVAL;
3973 return -1;
3975 return 0;
3979 /* Symlink-related functions. */
3980 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
3981 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
3982 #endif
3985 symlink (char const *filename, char const *linkname)
3987 char linkfn[MAX_PATH], *tgtfn;
3988 DWORD flags = 0;
3989 int dir_access, filename_ends_in_slash;
3991 /* Diagnostics follows Posix as much as possible. */
3992 if (filename == NULL || linkname == NULL)
3994 errno = EFAULT;
3995 return -1;
3997 if (!*filename)
3999 errno = ENOENT;
4000 return -1;
4002 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4004 errno = ENAMETOOLONG;
4005 return -1;
4008 strcpy (linkfn, map_w32_filename (linkname, NULL));
4009 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4011 errno = EPERM;
4012 return -1;
4015 /* Note: since empty FILENAME was already rejected, we can safely
4016 refer to FILENAME[1]. */
4017 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4019 /* Non-absolute FILENAME is understood as being relative to
4020 LINKNAME's directory. We need to prepend that directory to
4021 FILENAME to get correct results from sys_access below, since
4022 otherwise it will interpret FILENAME relative to the
4023 directory where the Emacs process runs. Note that
4024 make-symbolic-link always makes sure LINKNAME is a fully
4025 expanded file name. */
4026 char tem[MAX_PATH];
4027 char *p = linkfn + strlen (linkfn);
4029 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4030 p--;
4031 if (p > linkfn)
4032 strncpy (tem, linkfn, p - linkfn);
4033 tem[p - linkfn] = '\0';
4034 strcat (tem, filename);
4035 dir_access = sys_access (tem, D_OK);
4037 else
4038 dir_access = sys_access (filename, D_OK);
4040 /* Since Windows distinguishes between symlinks to directories and
4041 to files, we provide a kludgy feature: if FILENAME doesn't
4042 exist, but ends in a slash, we create a symlink to directory. If
4043 FILENAME exists and is a directory, we always create a symlink to
4044 directory. */
4045 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4046 if (dir_access == 0 || filename_ends_in_slash)
4047 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4049 tgtfn = (char *)map_w32_filename (filename, NULL);
4050 if (filename_ends_in_slash)
4051 tgtfn[strlen (tgtfn) - 1] = '\0';
4053 errno = 0;
4054 if (!create_symbolic_link (linkfn, tgtfn, flags))
4056 /* ENOSYS is set by create_symbolic_link, when it detects that
4057 the OS doesn't support the CreateSymbolicLink API. */
4058 if (errno != ENOSYS)
4060 DWORD w32err = GetLastError ();
4062 switch (w32err)
4064 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4065 TGTFN point to the same file name, go figure. */
4066 case ERROR_SUCCESS:
4067 case ERROR_FILE_EXISTS:
4068 errno = EEXIST;
4069 break;
4070 case ERROR_ACCESS_DENIED:
4071 errno = EACCES;
4072 break;
4073 case ERROR_FILE_NOT_FOUND:
4074 case ERROR_PATH_NOT_FOUND:
4075 case ERROR_BAD_NETPATH:
4076 case ERROR_INVALID_REPARSE_DATA:
4077 errno = ENOENT;
4078 break;
4079 case ERROR_DIRECTORY:
4080 errno = EISDIR;
4081 break;
4082 case ERROR_PRIVILEGE_NOT_HELD:
4083 case ERROR_NOT_ALL_ASSIGNED:
4084 errno = EPERM;
4085 break;
4086 case ERROR_DISK_FULL:
4087 errno = ENOSPC;
4088 break;
4089 default:
4090 errno = EINVAL;
4091 break;
4094 return -1;
4096 return 0;
4099 /* A quick inexpensive test of whether FILENAME identifies a file that
4100 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4101 must already be in the normalized form returned by
4102 map_w32_filename.
4104 Note: for repeated operations on many files, it is best to test
4105 whether the underlying volume actually supports symlinks, by
4106 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4107 avoid the call to this function if it doesn't. That's because the
4108 call to GetFileAttributes takes a non-negligible time, especially
4109 on non-local or removable filesystems. See stat_worker for an
4110 example of how to do that. */
4111 static int
4112 is_symlink (const char *filename)
4114 DWORD attrs;
4115 WIN32_FIND_DATA wfd;
4116 HANDLE fh;
4118 attrs = GetFileAttributes (filename);
4119 if (attrs == -1)
4121 DWORD w32err = GetLastError ();
4123 switch (w32err)
4125 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4126 break;
4127 case ERROR_ACCESS_DENIED:
4128 errno = EACCES;
4129 break;
4130 case ERROR_FILE_NOT_FOUND:
4131 case ERROR_PATH_NOT_FOUND:
4132 default:
4133 errno = ENOENT;
4134 break;
4136 return 0;
4138 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4139 return 0;
4140 logon_network_drive (filename);
4141 fh = FindFirstFile (filename, &wfd);
4142 if (fh == INVALID_HANDLE_VALUE)
4143 return 0;
4144 FindClose (fh);
4145 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4146 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4149 /* If NAME identifies a symbolic link, copy into BUF the file name of
4150 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4151 null-terminate the target name, even if it fits. Return the number
4152 of bytes copied, or -1 if NAME is not a symlink or any error was
4153 encountered while resolving it. The file name copied into BUF is
4154 encoded in the current ANSI codepage. */
4155 ssize_t
4156 readlink (const char *name, char *buf, size_t buf_size)
4158 const char *path;
4159 TOKEN_PRIVILEGES privs;
4160 int restore_privs = 0;
4161 HANDLE sh;
4162 ssize_t retval;
4164 if (name == NULL)
4166 errno = EFAULT;
4167 return -1;
4169 if (!*name)
4171 errno = ENOENT;
4172 return -1;
4175 path = map_w32_filename (name, NULL);
4177 if (strlen (path) > MAX_PATH)
4179 errno = ENAMETOOLONG;
4180 return -1;
4183 errno = 0;
4184 if (is_windows_9x () == TRUE
4185 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4186 || !is_symlink (path))
4188 if (!errno)
4189 errno = EINVAL; /* not a symlink */
4190 return -1;
4193 /* Done with simple tests, now we're in for some _real_ work. */
4194 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4195 restore_privs = 1;
4196 /* Implementation note: From here and onward, don't return early,
4197 since that will fail to restore the original set of privileges of
4198 the calling thread. */
4200 retval = -1; /* not too optimistic, are we? */
4202 /* Note: In the next call to CreateFile, we use zero as the 2nd
4203 argument because, when the symlink is a hidden/system file,
4204 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4205 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4206 and directory symlinks. */
4207 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4208 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4209 NULL);
4210 if (sh != INVALID_HANDLE_VALUE)
4212 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4213 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4214 DWORD retbytes;
4216 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4217 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4218 &retbytes, NULL))
4219 errno = EIO;
4220 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4221 errno = EINVAL;
4222 else
4224 /* Copy the link target name, in wide characters, fro
4225 reparse_data, then convert it to multibyte encoding in
4226 the current locale's codepage. */
4227 WCHAR *lwname;
4228 BYTE lname[MAX_PATH];
4229 USHORT lname_len;
4230 USHORT lwname_len =
4231 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4232 WCHAR *lwname_src =
4233 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4234 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4236 /* According to MSDN, PrintNameLength does not include the
4237 terminating null character. */
4238 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4239 memcpy (lwname, lwname_src, lwname_len);
4240 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4242 /* FIXME: Should we use the current file-name coding system
4243 instead of the fixed value of the ANSI codepage? */
4244 lname_len = WideCharToMultiByte (w32_ansi_code_page, 0, lwname, -1,
4245 lname, MAX_PATH, NULL, NULL);
4246 if (!lname_len)
4248 /* WideCharToMultiByte failed. */
4249 DWORD w32err1 = GetLastError ();
4251 switch (w32err1)
4253 case ERROR_INSUFFICIENT_BUFFER:
4254 errno = ENAMETOOLONG;
4255 break;
4256 case ERROR_INVALID_PARAMETER:
4257 errno = EFAULT;
4258 break;
4259 case ERROR_NO_UNICODE_TRANSLATION:
4260 errno = ENOENT;
4261 break;
4262 default:
4263 errno = EINVAL;
4264 break;
4267 else
4269 size_t size_to_copy = buf_size;
4270 BYTE *p = lname;
4271 BYTE *pend = p + lname_len;
4273 /* Normalize like dostounix_filename does, but we don't
4274 want to assume that lname is null-terminated. */
4275 if (*p && p[1] == ':' && *p >= 'A' && *p <= 'Z')
4276 *p += 'a' - 'A';
4277 while (p <= pend)
4279 if (*p == '\\')
4280 *p = '/';
4281 ++p;
4283 /* Testing for null-terminated LNAME is paranoia:
4284 WideCharToMultiByte should always return a
4285 null-terminated string when its 4th argument is -1
4286 and its 3rd argument is null-terminated (which they
4287 are, see above). */
4288 if (lname[lname_len - 1] == '\0')
4289 lname_len--;
4290 if (lname_len <= buf_size)
4291 size_to_copy = lname_len;
4292 strncpy (buf, lname, size_to_copy);
4293 /* Success! */
4294 retval = size_to_copy;
4297 CloseHandle (sh);
4299 else
4301 /* CreateFile failed. */
4302 DWORD w32err2 = GetLastError ();
4304 switch (w32err2)
4306 case ERROR_FILE_NOT_FOUND:
4307 case ERROR_PATH_NOT_FOUND:
4308 errno = ENOENT;
4309 break;
4310 case ERROR_ACCESS_DENIED:
4311 case ERROR_TOO_MANY_OPEN_FILES:
4312 errno = EACCES;
4313 break;
4314 default:
4315 errno = EPERM;
4316 break;
4319 if (restore_privs)
4321 restore_privilege (&privs);
4322 revert_to_self ();
4325 return retval;
4328 /* If FILE is a symlink, return its target (stored in a static
4329 buffer); otherwise return FILE.
4331 This function repeatedly resolves symlinks in the last component of
4332 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4333 until it arrives at a file whose last component is not a symlink,
4334 or some error occurs. It returns the target of the last
4335 successfully resolved symlink in the chain. If it succeeds to
4336 resolve even a single symlink, the value returned is an absolute
4337 file name with backslashes (result of GetFullPathName). By
4338 contrast, if the original FILE is returned, it is unaltered.
4340 Note: This function can set errno even if it succeeds.
4342 Implementation note: we only resolve the last portion ("basename")
4343 of the argument FILE and of each following file in the chain,
4344 disregarding any possible symlinks in its leading directories.
4345 This is because Windows system calls and library functions
4346 transparently resolve symlinks in leading directories and return
4347 correct information, as long as the basename is not a symlink. */
4348 static char *
4349 chase_symlinks (const char *file)
4351 static char target[MAX_PATH];
4352 char link[MAX_PATH];
4353 ssize_t res, link_len;
4354 int loop_count = 0;
4356 if (is_windows_9x () == TRUE || !is_symlink (file))
4357 return (char *)file;
4359 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
4360 return (char *)file;
4362 target[0] = '\0';
4363 do {
4365 /* Remove trailing slashes, as we want to resolve the last
4366 non-trivial part of the link name. */
4367 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
4368 link[link_len--] = '\0';
4370 res = readlink (link, target, MAX_PATH);
4371 if (res > 0)
4373 target[res] = '\0';
4374 if (!(IS_DEVICE_SEP (target[1])
4375 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
4377 /* Target is relative. Append it to the directory part of
4378 the symlink, then copy the result back to target. */
4379 char *p = link + link_len;
4381 while (p > link && !IS_ANY_SEP (p[-1]))
4382 p--;
4383 strcpy (p, target);
4384 strcpy (target, link);
4386 /* Resolve any "." and ".." to get a fully-qualified file name
4387 in link[] again. */
4388 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
4390 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
4392 if (loop_count > 100)
4393 errno = ELOOP;
4395 if (target[0] == '\0') /* not a single call to readlink succeeded */
4396 return (char *)file;
4397 return target;
4400 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
4401 have a fixed max size for file names, so we don't need the kind of
4402 alloc/malloc/realloc dance the gnulib version does. We also don't
4403 support FD-relative symlinks. */
4404 char *
4405 careadlinkat (int fd, char const *filename,
4406 char *buffer, size_t buffer_size,
4407 struct allocator const *alloc,
4408 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
4410 char linkname[MAX_PATH];
4411 ssize_t link_size;
4413 if (fd != AT_FDCWD)
4415 errno = EINVAL;
4416 return NULL;
4419 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
4421 if (link_size > 0)
4423 char *retval = buffer;
4425 linkname[link_size++] = '\0';
4426 if (link_size > buffer_size)
4427 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
4428 if (retval)
4429 memcpy (retval, linkname, link_size);
4431 return retval;
4433 return NULL;
4436 ssize_t
4437 careadlinkatcwd (int fd, char const *filename, char *buffer,
4438 size_t buffer_size)
4440 (void) fd;
4441 return readlink (filename, buffer, buffer_size);
4445 /* Support for browsing other processes and their attributes. See
4446 process.c for the Lisp bindings. */
4448 /* Helper wrapper functions. */
4450 static HANDLE WINAPI
4451 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
4453 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
4455 if (g_b_init_create_toolhelp32_snapshot == 0)
4457 g_b_init_create_toolhelp32_snapshot = 1;
4458 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
4459 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4460 "CreateToolhelp32Snapshot");
4462 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
4464 return INVALID_HANDLE_VALUE;
4466 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
4469 static BOOL WINAPI
4470 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
4472 static Process32First_Proc s_pfn_Process32_First = NULL;
4474 if (g_b_init_process32_first == 0)
4476 g_b_init_process32_first = 1;
4477 s_pfn_Process32_First = (Process32First_Proc)
4478 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4479 "Process32First");
4481 if (s_pfn_Process32_First == NULL)
4483 return FALSE;
4485 return (s_pfn_Process32_First (hSnapshot, lppe));
4488 static BOOL WINAPI
4489 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
4491 static Process32Next_Proc s_pfn_Process32_Next = NULL;
4493 if (g_b_init_process32_next == 0)
4495 g_b_init_process32_next = 1;
4496 s_pfn_Process32_Next = (Process32Next_Proc)
4497 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4498 "Process32Next");
4500 if (s_pfn_Process32_Next == NULL)
4502 return FALSE;
4504 return (s_pfn_Process32_Next (hSnapshot, lppe));
4507 static BOOL WINAPI
4508 open_thread_token (HANDLE ThreadHandle,
4509 DWORD DesiredAccess,
4510 BOOL OpenAsSelf,
4511 PHANDLE TokenHandle)
4513 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
4514 HMODULE hm_advapi32 = NULL;
4515 if (is_windows_9x () == TRUE)
4517 SetLastError (ERROR_NOT_SUPPORTED);
4518 return FALSE;
4520 if (g_b_init_open_thread_token == 0)
4522 g_b_init_open_thread_token = 1;
4523 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4524 s_pfn_Open_Thread_Token =
4525 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
4527 if (s_pfn_Open_Thread_Token == NULL)
4529 SetLastError (ERROR_NOT_SUPPORTED);
4530 return FALSE;
4532 return (
4533 s_pfn_Open_Thread_Token (
4534 ThreadHandle,
4535 DesiredAccess,
4536 OpenAsSelf,
4537 TokenHandle)
4541 static BOOL WINAPI
4542 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
4544 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
4545 HMODULE hm_advapi32 = NULL;
4546 if (is_windows_9x () == TRUE)
4548 return FALSE;
4550 if (g_b_init_impersonate_self == 0)
4552 g_b_init_impersonate_self = 1;
4553 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4554 s_pfn_Impersonate_Self =
4555 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
4557 if (s_pfn_Impersonate_Self == NULL)
4559 return FALSE;
4561 return s_pfn_Impersonate_Self (ImpersonationLevel);
4564 static BOOL WINAPI
4565 revert_to_self (void)
4567 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
4568 HMODULE hm_advapi32 = NULL;
4569 if (is_windows_9x () == TRUE)
4571 return FALSE;
4573 if (g_b_init_revert_to_self == 0)
4575 g_b_init_revert_to_self = 1;
4576 hm_advapi32 = LoadLibrary ("Advapi32.dll");
4577 s_pfn_Revert_To_Self =
4578 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
4580 if (s_pfn_Revert_To_Self == NULL)
4582 return FALSE;
4584 return s_pfn_Revert_To_Self ();
4587 static BOOL WINAPI
4588 get_process_memory_info (HANDLE h_proc,
4589 PPROCESS_MEMORY_COUNTERS mem_counters,
4590 DWORD bufsize)
4592 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
4593 HMODULE hm_psapi = NULL;
4594 if (is_windows_9x () == TRUE)
4596 return FALSE;
4598 if (g_b_init_get_process_memory_info == 0)
4600 g_b_init_get_process_memory_info = 1;
4601 hm_psapi = LoadLibrary ("Psapi.dll");
4602 if (hm_psapi)
4603 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
4604 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
4606 if (s_pfn_Get_Process_Memory_Info == NULL)
4608 return FALSE;
4610 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
4613 static BOOL WINAPI
4614 get_process_working_set_size (HANDLE h_proc,
4615 DWORD *minrss,
4616 DWORD *maxrss)
4618 static GetProcessWorkingSetSize_Proc
4619 s_pfn_Get_Process_Working_Set_Size = NULL;
4621 if (is_windows_9x () == TRUE)
4623 return FALSE;
4625 if (g_b_init_get_process_working_set_size == 0)
4627 g_b_init_get_process_working_set_size = 1;
4628 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
4629 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4630 "GetProcessWorkingSetSize");
4632 if (s_pfn_Get_Process_Working_Set_Size == NULL)
4634 return FALSE;
4636 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
4639 static BOOL WINAPI
4640 global_memory_status (MEMORYSTATUS *buf)
4642 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
4644 if (is_windows_9x () == TRUE)
4646 return FALSE;
4648 if (g_b_init_global_memory_status == 0)
4650 g_b_init_global_memory_status = 1;
4651 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
4652 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4653 "GlobalMemoryStatus");
4655 if (s_pfn_Global_Memory_Status == NULL)
4657 return FALSE;
4659 return s_pfn_Global_Memory_Status (buf);
4662 static BOOL WINAPI
4663 global_memory_status_ex (MEMORY_STATUS_EX *buf)
4665 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
4667 if (is_windows_9x () == TRUE)
4669 return FALSE;
4671 if (g_b_init_global_memory_status_ex == 0)
4673 g_b_init_global_memory_status_ex = 1;
4674 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
4675 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4676 "GlobalMemoryStatusEx");
4678 if (s_pfn_Global_Memory_Status_Ex == NULL)
4680 return FALSE;
4682 return s_pfn_Global_Memory_Status_Ex (buf);
4685 Lisp_Object
4686 list_system_processes (void)
4688 struct gcpro gcpro1;
4689 Lisp_Object proclist = Qnil;
4690 HANDLE h_snapshot;
4692 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4694 if (h_snapshot != INVALID_HANDLE_VALUE)
4696 PROCESSENTRY32 proc_entry;
4697 DWORD proc_id;
4698 BOOL res;
4700 GCPRO1 (proclist);
4702 proc_entry.dwSize = sizeof (PROCESSENTRY32);
4703 for (res = process32_first (h_snapshot, &proc_entry); res;
4704 res = process32_next (h_snapshot, &proc_entry))
4706 proc_id = proc_entry.th32ProcessID;
4707 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
4710 CloseHandle (h_snapshot);
4711 UNGCPRO;
4712 proclist = Fnreverse (proclist);
4715 return proclist;
4718 static int
4719 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
4721 TOKEN_PRIVILEGES priv;
4722 DWORD priv_size = sizeof (priv);
4723 DWORD opriv_size = sizeof (*old_priv);
4724 HANDLE h_token = NULL;
4725 HANDLE h_thread = GetCurrentThread ();
4726 int ret_val = 0;
4727 BOOL res;
4729 res = open_thread_token (h_thread,
4730 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4731 FALSE, &h_token);
4732 if (!res && GetLastError () == ERROR_NO_TOKEN)
4734 if (impersonate_self (SecurityImpersonation))
4735 res = open_thread_token (h_thread,
4736 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4737 FALSE, &h_token);
4739 if (res)
4741 priv.PrivilegeCount = 1;
4742 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
4743 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
4744 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
4745 old_priv, &opriv_size)
4746 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4747 ret_val = 1;
4749 if (h_token)
4750 CloseHandle (h_token);
4752 return ret_val;
4755 static int
4756 restore_privilege (TOKEN_PRIVILEGES *priv)
4758 DWORD priv_size = sizeof (*priv);
4759 HANDLE h_token = NULL;
4760 int ret_val = 0;
4762 if (open_thread_token (GetCurrentThread (),
4763 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4764 FALSE, &h_token))
4766 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
4767 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4768 ret_val = 1;
4770 if (h_token)
4771 CloseHandle (h_token);
4773 return ret_val;
4776 static Lisp_Object
4777 ltime (ULONGLONG time_100ns)
4779 ULONGLONG time_sec = time_100ns / 10000000;
4780 int subsec = time_100ns % 10000000;
4781 return list4 (make_number (time_sec >> 16),
4782 make_number (time_sec & 0xffff),
4783 make_number (subsec / 10),
4784 make_number (subsec % 10 * 100000));
4787 #define U64_TO_LISP_TIME(time) ltime (time)
4789 static int
4790 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
4791 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
4792 double *pcpu)
4794 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
4795 ULONGLONG tem1, tem2, tem3, tem;
4797 if (!h_proc
4798 || !get_process_times_fn
4799 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
4800 &ft_kernel, &ft_user))
4801 return 0;
4803 GetSystemTimeAsFileTime (&ft_current);
4805 FILETIME_TO_U64 (tem1, ft_kernel);
4806 *stime = U64_TO_LISP_TIME (tem1);
4808 FILETIME_TO_U64 (tem2, ft_user);
4809 *utime = U64_TO_LISP_TIME (tem2);
4811 tem3 = tem1 + tem2;
4812 *ttime = U64_TO_LISP_TIME (tem3);
4814 FILETIME_TO_U64 (tem, ft_creation);
4815 /* Process no 4 (System) returns zero creation time. */
4816 if (tem)
4817 tem -= utc_base;
4818 *ctime = U64_TO_LISP_TIME (tem);
4820 if (tem)
4822 FILETIME_TO_U64 (tem3, ft_current);
4823 tem = (tem3 - utc_base) - tem;
4825 *etime = U64_TO_LISP_TIME (tem);
4827 if (tem)
4829 *pcpu = 100.0 * (tem1 + tem2) / tem;
4830 if (*pcpu > 100)
4831 *pcpu = 100.0;
4833 else
4834 *pcpu = 0;
4836 return 1;
4839 Lisp_Object
4840 system_process_attributes (Lisp_Object pid)
4842 struct gcpro gcpro1, gcpro2, gcpro3;
4843 Lisp_Object attrs = Qnil;
4844 Lisp_Object cmd_str, decoded_cmd, tem;
4845 HANDLE h_snapshot, h_proc;
4846 DWORD proc_id;
4847 int found_proc = 0;
4848 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
4849 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
4850 DWORD glength = sizeof (gname);
4851 HANDLE token = NULL;
4852 SID_NAME_USE user_type;
4853 unsigned char *buf = NULL;
4854 DWORD blen = 0;
4855 TOKEN_USER user_token;
4856 TOKEN_PRIMARY_GROUP group_token;
4857 unsigned euid;
4858 unsigned egid;
4859 PROCESS_MEMORY_COUNTERS mem;
4860 PROCESS_MEMORY_COUNTERS_EX mem_ex;
4861 DWORD minrss, maxrss;
4862 MEMORYSTATUS memst;
4863 MEMORY_STATUS_EX memstex;
4864 double totphys = 0.0;
4865 Lisp_Object ctime, stime, utime, etime, ttime;
4866 double pcpu;
4867 BOOL result = FALSE;
4869 CHECK_NUMBER_OR_FLOAT (pid);
4870 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
4872 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4874 GCPRO3 (attrs, decoded_cmd, tem);
4876 if (h_snapshot != INVALID_HANDLE_VALUE)
4878 PROCESSENTRY32 pe;
4879 BOOL res;
4881 pe.dwSize = sizeof (PROCESSENTRY32);
4882 for (res = process32_first (h_snapshot, &pe); res;
4883 res = process32_next (h_snapshot, &pe))
4885 if (proc_id == pe.th32ProcessID)
4887 if (proc_id == 0)
4888 decoded_cmd = build_string ("Idle");
4889 else
4891 /* Decode the command name from locale-specific
4892 encoding. */
4893 cmd_str = make_unibyte_string (pe.szExeFile,
4894 strlen (pe.szExeFile));
4895 decoded_cmd =
4896 code_convert_string_norecord (cmd_str,
4897 Vlocale_coding_system, 0);
4899 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
4900 attrs = Fcons (Fcons (Qppid,
4901 make_fixnum_or_float (pe.th32ParentProcessID)),
4902 attrs);
4903 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
4904 attrs);
4905 attrs = Fcons (Fcons (Qthcount,
4906 make_fixnum_or_float (pe.cntThreads)),
4907 attrs);
4908 found_proc = 1;
4909 break;
4913 CloseHandle (h_snapshot);
4916 if (!found_proc)
4918 UNGCPRO;
4919 return Qnil;
4922 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4923 FALSE, proc_id);
4924 /* If we were denied a handle to the process, try again after
4925 enabling the SeDebugPrivilege in our process. */
4926 if (!h_proc)
4928 TOKEN_PRIVILEGES priv_current;
4930 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
4932 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4933 FALSE, proc_id);
4934 restore_privilege (&priv_current);
4935 revert_to_self ();
4938 if (h_proc)
4940 result = open_process_token (h_proc, TOKEN_QUERY, &token);
4941 if (result)
4943 result = get_token_information (token, TokenUser, NULL, 0, &blen);
4944 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4946 buf = xmalloc (blen);
4947 result = get_token_information (token, TokenUser,
4948 (LPVOID)buf, blen, &needed);
4949 if (result)
4951 memcpy (&user_token, buf, sizeof (user_token));
4952 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
4954 euid = get_rid (user_token.User.Sid);
4955 result = lookup_account_sid (NULL, user_token.User.Sid,
4956 uname, &ulength,
4957 domain, &dlength,
4958 &user_type);
4959 if (result)
4960 w32_add_to_cache (user_token.User.Sid, euid, uname);
4961 else
4963 strcpy (uname, "unknown");
4964 result = TRUE;
4967 ulength = strlen (uname);
4971 if (result)
4973 /* Determine a reasonable euid and gid values. */
4974 if (xstrcasecmp ("administrator", uname) == 0)
4976 euid = 500; /* well-known Administrator uid */
4977 egid = 513; /* well-known None gid */
4979 else
4981 /* Get group id and name. */
4982 result = get_token_information (token, TokenPrimaryGroup,
4983 (LPVOID)buf, blen, &needed);
4984 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4986 buf = xrealloc (buf, blen = needed);
4987 result = get_token_information (token, TokenPrimaryGroup,
4988 (LPVOID)buf, blen, &needed);
4990 if (result)
4992 memcpy (&group_token, buf, sizeof (group_token));
4993 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
4995 egid = get_rid (group_token.PrimaryGroup);
4996 dlength = sizeof (domain);
4997 result =
4998 lookup_account_sid (NULL, group_token.PrimaryGroup,
4999 gname, &glength, NULL, &dlength,
5000 &user_type);
5001 if (result)
5002 w32_add_to_cache (group_token.PrimaryGroup,
5003 egid, gname);
5004 else
5006 strcpy (gname, "None");
5007 result = TRUE;
5010 glength = strlen (gname);
5014 xfree (buf);
5016 if (!result)
5018 if (!is_windows_9x ())
5020 /* We couldn't open the process token, presumably because of
5021 insufficient access rights. Assume this process is run
5022 by the system. */
5023 strcpy (uname, "SYSTEM");
5024 strcpy (gname, "None");
5025 euid = 18; /* SYSTEM */
5026 egid = 513; /* None */
5027 glength = strlen (gname);
5028 ulength = strlen (uname);
5030 /* If we are running under Windows 9X, where security calls are
5031 not supported, we assume all processes are run by the current
5032 user. */
5033 else if (GetUserName (uname, &ulength))
5035 if (xstrcasecmp ("administrator", uname) == 0)
5036 euid = 0;
5037 else
5038 euid = 123;
5039 egid = euid;
5040 strcpy (gname, "None");
5041 glength = strlen (gname);
5042 ulength = strlen (uname);
5044 else
5046 euid = 123;
5047 egid = 123;
5048 strcpy (uname, "administrator");
5049 ulength = strlen (uname);
5050 strcpy (gname, "None");
5051 glength = strlen (gname);
5053 if (token)
5054 CloseHandle (token);
5057 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5058 tem = make_unibyte_string (uname, ulength);
5059 attrs = Fcons (Fcons (Quser,
5060 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5061 attrs);
5062 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5063 tem = make_unibyte_string (gname, glength);
5064 attrs = Fcons (Fcons (Qgroup,
5065 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5066 attrs);
5068 if (global_memory_status_ex (&memstex))
5069 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5070 totphys = memstex.ullTotalPhys / 1024.0;
5071 #else
5072 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5073 double, so we need to do this for it... */
5075 DWORD tot_hi = memstex.ullTotalPhys >> 32;
5076 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
5077 DWORD tot_lo = memstex.ullTotalPhys % 1024;
5079 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
5081 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5082 else if (global_memory_status (&memst))
5083 totphys = memst.dwTotalPhys / 1024.0;
5085 if (h_proc
5086 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
5087 sizeof (mem_ex)))
5089 DWORD rss = mem_ex.WorkingSetSize / 1024;
5091 attrs = Fcons (Fcons (Qmajflt,
5092 make_fixnum_or_float (mem_ex.PageFaultCount)),
5093 attrs);
5094 attrs = Fcons (Fcons (Qvsize,
5095 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
5096 attrs);
5097 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5098 if (totphys)
5099 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5101 else if (h_proc
5102 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
5104 DWORD rss = mem_ex.WorkingSetSize / 1024;
5106 attrs = Fcons (Fcons (Qmajflt,
5107 make_fixnum_or_float (mem.PageFaultCount)),
5108 attrs);
5109 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5110 if (totphys)
5111 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5113 else if (h_proc
5114 && get_process_working_set_size (h_proc, &minrss, &maxrss))
5116 DWORD rss = maxrss / 1024;
5118 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
5119 if (totphys)
5120 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5123 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
5125 attrs = Fcons (Fcons (Qutime, utime), attrs);
5126 attrs = Fcons (Fcons (Qstime, stime), attrs);
5127 attrs = Fcons (Fcons (Qtime, ttime), attrs);
5128 attrs = Fcons (Fcons (Qstart, ctime), attrs);
5129 attrs = Fcons (Fcons (Qetime, etime), attrs);
5130 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
5133 /* FIXME: Retrieve command line by walking the PEB of the process. */
5135 if (h_proc)
5136 CloseHandle (h_proc);
5137 UNGCPRO;
5138 return attrs;
5142 /* Wrappers for winsock functions to map between our file descriptors
5143 and winsock's handles; also set h_errno for convenience.
5145 To allow Emacs to run on systems which don't have winsock support
5146 installed, we dynamically link to winsock on startup if present, and
5147 otherwise provide the minimum necessary functionality
5148 (eg. gethostname). */
5150 /* function pointers for relevant socket functions */
5151 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
5152 void (PASCAL *pfn_WSASetLastError) (int iError);
5153 int (PASCAL *pfn_WSAGetLastError) (void);
5154 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
5155 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
5156 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
5157 int (PASCAL *pfn_socket) (int af, int type, int protocol);
5158 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
5159 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
5160 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
5161 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
5162 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
5163 int (PASCAL *pfn_closesocket) (SOCKET s);
5164 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
5165 int (PASCAL *pfn_WSACleanup) (void);
5167 u_short (PASCAL *pfn_htons) (u_short hostshort);
5168 u_short (PASCAL *pfn_ntohs) (u_short netshort);
5169 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
5170 int (PASCAL *pfn_gethostname) (char * name, int namelen);
5171 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
5172 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
5173 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
5174 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
5175 const char * optval, int optlen);
5176 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
5177 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
5178 int * namelen);
5179 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
5180 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
5181 struct sockaddr * from, int * fromlen);
5182 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
5183 const struct sockaddr * to, int tolen);
5185 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5186 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
5187 #ifndef HANDLE_FLAG_INHERIT
5188 #define HANDLE_FLAG_INHERIT 1
5189 #endif
5191 HANDLE winsock_lib;
5192 static int winsock_inuse;
5194 BOOL
5195 term_winsock (void)
5197 if (winsock_lib != NULL && winsock_inuse == 0)
5199 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5200 after WSAStartup returns successfully, but it seems reasonable
5201 to allow unloading winsock anyway in that case. */
5202 if (pfn_WSACleanup () == 0 ||
5203 pfn_WSAGetLastError () == WSAENETDOWN)
5205 if (FreeLibrary (winsock_lib))
5206 winsock_lib = NULL;
5207 return TRUE;
5210 return FALSE;
5213 BOOL
5214 init_winsock (int load_now)
5216 WSADATA winsockData;
5218 if (winsock_lib != NULL)
5219 return TRUE;
5221 pfn_SetHandleInformation
5222 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
5223 "SetHandleInformation");
5225 winsock_lib = LoadLibrary ("Ws2_32.dll");
5227 if (winsock_lib != NULL)
5229 /* dynamically link to socket functions */
5231 #define LOAD_PROC(fn) \
5232 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
5233 goto fail;
5235 LOAD_PROC (WSAStartup);
5236 LOAD_PROC (WSASetLastError);
5237 LOAD_PROC (WSAGetLastError);
5238 LOAD_PROC (WSAEventSelect);
5239 LOAD_PROC (WSACreateEvent);
5240 LOAD_PROC (WSACloseEvent);
5241 LOAD_PROC (socket);
5242 LOAD_PROC (bind);
5243 LOAD_PROC (connect);
5244 LOAD_PROC (ioctlsocket);
5245 LOAD_PROC (recv);
5246 LOAD_PROC (send);
5247 LOAD_PROC (closesocket);
5248 LOAD_PROC (shutdown);
5249 LOAD_PROC (htons);
5250 LOAD_PROC (ntohs);
5251 LOAD_PROC (inet_addr);
5252 LOAD_PROC (gethostname);
5253 LOAD_PROC (gethostbyname);
5254 LOAD_PROC (getservbyname);
5255 LOAD_PROC (getpeername);
5256 LOAD_PROC (WSACleanup);
5257 LOAD_PROC (setsockopt);
5258 LOAD_PROC (listen);
5259 LOAD_PROC (getsockname);
5260 LOAD_PROC (accept);
5261 LOAD_PROC (recvfrom);
5262 LOAD_PROC (sendto);
5263 #undef LOAD_PROC
5265 /* specify version 1.1 of winsock */
5266 if (pfn_WSAStartup (0x101, &winsockData) == 0)
5268 if (winsockData.wVersion != 0x101)
5269 goto fail;
5271 if (!load_now)
5273 /* Report that winsock exists and is usable, but leave
5274 socket functions disabled. I am assuming that calling
5275 WSAStartup does not require any network interaction,
5276 and in particular does not cause or require a dial-up
5277 connection to be established. */
5279 pfn_WSACleanup ();
5280 FreeLibrary (winsock_lib);
5281 winsock_lib = NULL;
5283 winsock_inuse = 0;
5284 return TRUE;
5287 fail:
5288 FreeLibrary (winsock_lib);
5289 winsock_lib = NULL;
5292 return FALSE;
5296 int h_errno = 0;
5298 /* function to set h_errno for compatibility; map winsock error codes to
5299 normal system codes where they overlap (non-overlapping definitions
5300 are already in <sys/socket.h> */
5301 static void
5302 set_errno (void)
5304 if (winsock_lib == NULL)
5305 h_errno = EINVAL;
5306 else
5307 h_errno = pfn_WSAGetLastError ();
5309 switch (h_errno)
5311 case WSAEACCES: h_errno = EACCES; break;
5312 case WSAEBADF: h_errno = EBADF; break;
5313 case WSAEFAULT: h_errno = EFAULT; break;
5314 case WSAEINTR: h_errno = EINTR; break;
5315 case WSAEINVAL: h_errno = EINVAL; break;
5316 case WSAEMFILE: h_errno = EMFILE; break;
5317 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
5318 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
5320 errno = h_errno;
5323 static void
5324 check_errno (void)
5326 if (h_errno == 0 && winsock_lib != NULL)
5327 pfn_WSASetLastError (0);
5330 /* Extend strerror to handle the winsock-specific error codes. */
5331 struct {
5332 int errnum;
5333 char * msg;
5334 } _wsa_errlist[] = {
5335 {WSAEINTR , "Interrupted function call"},
5336 {WSAEBADF , "Bad file descriptor"},
5337 {WSAEACCES , "Permission denied"},
5338 {WSAEFAULT , "Bad address"},
5339 {WSAEINVAL , "Invalid argument"},
5340 {WSAEMFILE , "Too many open files"},
5342 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
5343 {WSAEINPROGRESS , "Operation now in progress"},
5344 {WSAEALREADY , "Operation already in progress"},
5345 {WSAENOTSOCK , "Socket operation on non-socket"},
5346 {WSAEDESTADDRREQ , "Destination address required"},
5347 {WSAEMSGSIZE , "Message too long"},
5348 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
5349 {WSAENOPROTOOPT , "Bad protocol option"},
5350 {WSAEPROTONOSUPPORT , "Protocol not supported"},
5351 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
5352 {WSAEOPNOTSUPP , "Operation not supported"},
5353 {WSAEPFNOSUPPORT , "Protocol family not supported"},
5354 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
5355 {WSAEADDRINUSE , "Address already in use"},
5356 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
5357 {WSAENETDOWN , "Network is down"},
5358 {WSAENETUNREACH , "Network is unreachable"},
5359 {WSAENETRESET , "Network dropped connection on reset"},
5360 {WSAECONNABORTED , "Software caused connection abort"},
5361 {WSAECONNRESET , "Connection reset by peer"},
5362 {WSAENOBUFS , "No buffer space available"},
5363 {WSAEISCONN , "Socket is already connected"},
5364 {WSAENOTCONN , "Socket is not connected"},
5365 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
5366 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
5367 {WSAETIMEDOUT , "Connection timed out"},
5368 {WSAECONNREFUSED , "Connection refused"},
5369 {WSAELOOP , "Network loop"}, /* not sure */
5370 {WSAENAMETOOLONG , "Name is too long"},
5371 {WSAEHOSTDOWN , "Host is down"},
5372 {WSAEHOSTUNREACH , "No route to host"},
5373 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
5374 {WSAEPROCLIM , "Too many processes"},
5375 {WSAEUSERS , "Too many users"}, /* not sure */
5376 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
5377 {WSAESTALE , "Data is stale"}, /* not sure */
5378 {WSAEREMOTE , "Remote error"}, /* not sure */
5380 {WSASYSNOTREADY , "Network subsystem is unavailable"},
5381 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
5382 {WSANOTINITIALISED , "Winsock not initialized successfully"},
5383 {WSAEDISCON , "Graceful shutdown in progress"},
5384 #ifdef WSAENOMORE
5385 {WSAENOMORE , "No more operations allowed"}, /* not sure */
5386 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
5387 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
5388 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
5389 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
5390 {WSASYSCALLFAILURE , "System call failure"},
5391 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
5392 {WSATYPE_NOT_FOUND , "Class type not found"},
5393 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
5394 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
5395 {WSAEREFUSED , "Operation refused"}, /* not sure */
5396 #endif
5398 {WSAHOST_NOT_FOUND , "Host not found"},
5399 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
5400 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
5401 {WSANO_DATA , "Valid name, no data record of requested type"},
5403 {-1, NULL}
5406 char *
5407 sys_strerror (int error_no)
5409 int i;
5410 static char unknown_msg[40];
5412 if (error_no >= 0 && error_no < sys_nerr)
5413 return sys_errlist[error_no];
5415 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
5416 if (_wsa_errlist[i].errnum == error_no)
5417 return _wsa_errlist[i].msg;
5419 sprintf (unknown_msg, "Unidentified error: %d", error_no);
5420 return unknown_msg;
5423 /* [andrewi 3-May-96] I've had conflicting results using both methods,
5424 but I believe the method of keeping the socket handle separate (and
5425 insuring it is not inheritable) is the correct one. */
5427 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
5429 static int socket_to_fd (SOCKET s);
5432 sys_socket (int af, int type, int protocol)
5434 SOCKET s;
5436 if (winsock_lib == NULL)
5438 h_errno = ENETDOWN;
5439 return INVALID_SOCKET;
5442 check_errno ();
5444 /* call the real socket function */
5445 s = pfn_socket (af, type, protocol);
5447 if (s != INVALID_SOCKET)
5448 return socket_to_fd (s);
5450 set_errno ();
5451 return -1;
5454 /* Convert a SOCKET to a file descriptor. */
5455 static int
5456 socket_to_fd (SOCKET s)
5458 int fd;
5459 child_process * cp;
5461 /* Although under NT 3.5 _open_osfhandle will accept a socket
5462 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
5463 that does not work under NT 3.1. However, we can get the same
5464 effect by using a backdoor function to replace an existing
5465 descriptor handle with the one we want. */
5467 /* allocate a file descriptor (with appropriate flags) */
5468 fd = _open ("NUL:", _O_RDWR);
5469 if (fd >= 0)
5471 /* Make a non-inheritable copy of the socket handle. Note
5472 that it is possible that sockets aren't actually kernel
5473 handles, which appears to be the case on Windows 9x when
5474 the MS Proxy winsock client is installed. */
5476 /* Apparently there is a bug in NT 3.51 with some service
5477 packs, which prevents using DuplicateHandle to make a
5478 socket handle non-inheritable (causes WSACleanup to
5479 hang). The work-around is to use SetHandleInformation
5480 instead if it is available and implemented. */
5481 if (pfn_SetHandleInformation)
5483 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
5485 else
5487 HANDLE parent = GetCurrentProcess ();
5488 HANDLE new_s = INVALID_HANDLE_VALUE;
5490 if (DuplicateHandle (parent,
5491 (HANDLE) s,
5492 parent,
5493 &new_s,
5495 FALSE,
5496 DUPLICATE_SAME_ACCESS))
5498 /* It is possible that DuplicateHandle succeeds even
5499 though the socket wasn't really a kernel handle,
5500 because a real handle has the same value. So
5501 test whether the new handle really is a socket. */
5502 long nonblocking = 0;
5503 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
5505 pfn_closesocket (s);
5506 s = (SOCKET) new_s;
5508 else
5510 CloseHandle (new_s);
5515 fd_info[fd].hnd = (HANDLE) s;
5517 /* set our own internal flags */
5518 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
5520 cp = new_child ();
5521 if (cp)
5523 cp->fd = fd;
5524 cp->status = STATUS_READ_ACKNOWLEDGED;
5526 /* attach child_process to fd_info */
5527 if (fd_info[ fd ].cp != NULL)
5529 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
5530 emacs_abort ();
5533 fd_info[ fd ].cp = cp;
5535 /* success! */
5536 winsock_inuse++; /* count open sockets */
5537 return fd;
5540 /* clean up */
5541 _close (fd);
5543 pfn_closesocket (s);
5544 h_errno = EMFILE;
5545 return -1;
5549 sys_bind (int s, const struct sockaddr * addr, int namelen)
5551 if (winsock_lib == NULL)
5553 h_errno = ENOTSOCK;
5554 return SOCKET_ERROR;
5557 check_errno ();
5558 if (fd_info[s].flags & FILE_SOCKET)
5560 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
5561 if (rc == SOCKET_ERROR)
5562 set_errno ();
5563 return rc;
5565 h_errno = ENOTSOCK;
5566 return SOCKET_ERROR;
5570 sys_connect (int s, const struct sockaddr * name, int namelen)
5572 if (winsock_lib == NULL)
5574 h_errno = ENOTSOCK;
5575 return SOCKET_ERROR;
5578 check_errno ();
5579 if (fd_info[s].flags & FILE_SOCKET)
5581 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
5582 if (rc == SOCKET_ERROR)
5583 set_errno ();
5584 return rc;
5586 h_errno = ENOTSOCK;
5587 return SOCKET_ERROR;
5590 u_short
5591 sys_htons (u_short hostshort)
5593 return (winsock_lib != NULL) ?
5594 pfn_htons (hostshort) : hostshort;
5597 u_short
5598 sys_ntohs (u_short netshort)
5600 return (winsock_lib != NULL) ?
5601 pfn_ntohs (netshort) : netshort;
5604 unsigned long
5605 sys_inet_addr (const char * cp)
5607 return (winsock_lib != NULL) ?
5608 pfn_inet_addr (cp) : INADDR_NONE;
5612 sys_gethostname (char * name, int namelen)
5614 if (winsock_lib != NULL)
5615 return pfn_gethostname (name, namelen);
5617 if (namelen > MAX_COMPUTERNAME_LENGTH)
5618 return !GetComputerName (name, (DWORD *)&namelen);
5620 h_errno = EFAULT;
5621 return SOCKET_ERROR;
5624 struct hostent *
5625 sys_gethostbyname (const char * name)
5627 struct hostent * host;
5629 if (winsock_lib == NULL)
5631 h_errno = ENETDOWN;
5632 return NULL;
5635 check_errno ();
5636 host = pfn_gethostbyname (name);
5637 if (!host)
5638 set_errno ();
5639 return host;
5642 struct servent *
5643 sys_getservbyname (const char * name, const char * proto)
5645 struct servent * serv;
5647 if (winsock_lib == NULL)
5649 h_errno = ENETDOWN;
5650 return NULL;
5653 check_errno ();
5654 serv = pfn_getservbyname (name, proto);
5655 if (!serv)
5656 set_errno ();
5657 return serv;
5661 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
5663 if (winsock_lib == NULL)
5665 h_errno = ENETDOWN;
5666 return SOCKET_ERROR;
5669 check_errno ();
5670 if (fd_info[s].flags & FILE_SOCKET)
5672 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
5673 if (rc == SOCKET_ERROR)
5674 set_errno ();
5675 return rc;
5677 h_errno = ENOTSOCK;
5678 return SOCKET_ERROR;
5682 sys_shutdown (int s, int how)
5684 if (winsock_lib == NULL)
5686 h_errno = ENETDOWN;
5687 return SOCKET_ERROR;
5690 check_errno ();
5691 if (fd_info[s].flags & FILE_SOCKET)
5693 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
5694 if (rc == SOCKET_ERROR)
5695 set_errno ();
5696 return rc;
5698 h_errno = ENOTSOCK;
5699 return SOCKET_ERROR;
5703 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
5705 if (winsock_lib == NULL)
5707 h_errno = ENETDOWN;
5708 return SOCKET_ERROR;
5711 check_errno ();
5712 if (fd_info[s].flags & FILE_SOCKET)
5714 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
5715 (const char *)optval, optlen);
5716 if (rc == SOCKET_ERROR)
5717 set_errno ();
5718 return rc;
5720 h_errno = ENOTSOCK;
5721 return SOCKET_ERROR;
5725 sys_listen (int s, int backlog)
5727 if (winsock_lib == NULL)
5729 h_errno = ENETDOWN;
5730 return SOCKET_ERROR;
5733 check_errno ();
5734 if (fd_info[s].flags & FILE_SOCKET)
5736 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
5737 if (rc == SOCKET_ERROR)
5738 set_errno ();
5739 else
5740 fd_info[s].flags |= FILE_LISTEN;
5741 return rc;
5743 h_errno = ENOTSOCK;
5744 return SOCKET_ERROR;
5748 sys_getsockname (int s, struct sockaddr * name, int * namelen)
5750 if (winsock_lib == NULL)
5752 h_errno = ENETDOWN;
5753 return SOCKET_ERROR;
5756 check_errno ();
5757 if (fd_info[s].flags & FILE_SOCKET)
5759 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
5760 if (rc == SOCKET_ERROR)
5761 set_errno ();
5762 return rc;
5764 h_errno = ENOTSOCK;
5765 return SOCKET_ERROR;
5769 sys_accept (int s, struct sockaddr * addr, int * addrlen)
5771 if (winsock_lib == NULL)
5773 h_errno = ENETDOWN;
5774 return -1;
5777 check_errno ();
5778 if (fd_info[s].flags & FILE_LISTEN)
5780 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
5781 int fd = -1;
5782 if (t == INVALID_SOCKET)
5783 set_errno ();
5784 else
5785 fd = socket_to_fd (t);
5787 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
5788 ResetEvent (fd_info[s].cp->char_avail);
5789 return fd;
5791 h_errno = ENOTSOCK;
5792 return -1;
5796 sys_recvfrom (int s, char * buf, int len, int flags,
5797 struct sockaddr * from, int * fromlen)
5799 if (winsock_lib == NULL)
5801 h_errno = ENETDOWN;
5802 return SOCKET_ERROR;
5805 check_errno ();
5806 if (fd_info[s].flags & FILE_SOCKET)
5808 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
5809 if (rc == SOCKET_ERROR)
5810 set_errno ();
5811 return rc;
5813 h_errno = ENOTSOCK;
5814 return SOCKET_ERROR;
5818 sys_sendto (int s, const char * buf, int len, int flags,
5819 const struct sockaddr * to, int tolen)
5821 if (winsock_lib == NULL)
5823 h_errno = ENETDOWN;
5824 return SOCKET_ERROR;
5827 check_errno ();
5828 if (fd_info[s].flags & FILE_SOCKET)
5830 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
5831 if (rc == SOCKET_ERROR)
5832 set_errno ();
5833 return rc;
5835 h_errno = ENOTSOCK;
5836 return SOCKET_ERROR;
5839 /* Windows does not have an fcntl function. Provide an implementation
5840 solely for making sockets non-blocking. */
5842 fcntl (int s, int cmd, int options)
5844 if (winsock_lib == NULL)
5846 h_errno = ENETDOWN;
5847 return -1;
5850 check_errno ();
5851 if (fd_info[s].flags & FILE_SOCKET)
5853 if (cmd == F_SETFL && options == O_NDELAY)
5855 unsigned long nblock = 1;
5856 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
5857 if (rc == SOCKET_ERROR)
5858 set_errno ();
5859 /* Keep track of the fact that we set this to non-blocking. */
5860 fd_info[s].flags |= FILE_NDELAY;
5861 return rc;
5863 else
5865 h_errno = EINVAL;
5866 return SOCKET_ERROR;
5869 h_errno = ENOTSOCK;
5870 return SOCKET_ERROR;
5874 /* Shadow main io functions: we need to handle pipes and sockets more
5875 intelligently, and implement non-blocking mode as well. */
5878 sys_close (int fd)
5880 int rc;
5882 if (fd < 0)
5884 errno = EBADF;
5885 return -1;
5888 if (fd < MAXDESC && fd_info[fd].cp)
5890 child_process * cp = fd_info[fd].cp;
5892 fd_info[fd].cp = NULL;
5894 if (CHILD_ACTIVE (cp))
5896 /* if last descriptor to active child_process then cleanup */
5897 int i;
5898 for (i = 0; i < MAXDESC; i++)
5900 if (i == fd)
5901 continue;
5902 if (fd_info[i].cp == cp)
5903 break;
5905 if (i == MAXDESC)
5907 if (fd_info[fd].flags & FILE_SOCKET)
5909 if (winsock_lib == NULL) emacs_abort ();
5911 pfn_shutdown (SOCK_HANDLE (fd), 2);
5912 rc = pfn_closesocket (SOCK_HANDLE (fd));
5914 winsock_inuse--; /* count open sockets */
5916 delete_child (cp);
5921 /* Note that sockets do not need special treatment here (at least on
5922 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5923 closesocket is equivalent to CloseHandle, which is to be expected
5924 because socket handles are fully fledged kernel handles. */
5925 rc = _close (fd);
5927 if (rc == 0 && fd < MAXDESC)
5928 fd_info[fd].flags = 0;
5930 return rc;
5934 sys_dup (int fd)
5936 int new_fd;
5938 new_fd = _dup (fd);
5939 if (new_fd >= 0 && new_fd < MAXDESC)
5941 /* duplicate our internal info as well */
5942 fd_info[new_fd] = fd_info[fd];
5944 return new_fd;
5948 sys_dup2 (int src, int dst)
5950 int rc;
5952 if (dst < 0 || dst >= MAXDESC)
5954 errno = EBADF;
5955 return -1;
5958 /* make sure we close the destination first if it's a pipe or socket */
5959 if (src != dst && fd_info[dst].flags != 0)
5960 sys_close (dst);
5962 rc = _dup2 (src, dst);
5963 if (rc == 0)
5965 /* duplicate our internal info as well */
5966 fd_info[dst] = fd_info[src];
5968 return rc;
5971 /* Unix pipe() has only one arg */
5973 sys_pipe (int * phandles)
5975 int rc;
5976 unsigned flags;
5978 /* make pipe handles non-inheritable; when we spawn a child, we
5979 replace the relevant handle with an inheritable one. Also put
5980 pipes into binary mode; we will do text mode translation ourselves
5981 if required. */
5982 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
5984 if (rc == 0)
5986 /* Protect against overflow, since Windows can open more handles than
5987 our fd_info array has room for. */
5988 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
5990 _close (phandles[0]);
5991 _close (phandles[1]);
5992 rc = -1;
5994 else
5996 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
5997 fd_info[phandles[0]].flags = flags;
5999 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6000 fd_info[phandles[1]].flags = flags;
6004 return rc;
6007 /* Function to do blocking read of one byte, needed to implement
6008 select. It is only allowed on sockets and pipes. */
6010 _sys_read_ahead (int fd)
6012 child_process * cp;
6013 int rc;
6015 if (fd < 0 || fd >= MAXDESC)
6016 return STATUS_READ_ERROR;
6018 cp = fd_info[fd].cp;
6020 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6021 return STATUS_READ_ERROR;
6023 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6024 || (fd_info[fd].flags & FILE_READ) == 0)
6026 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
6027 emacs_abort ();
6030 cp->status = STATUS_READ_IN_PROGRESS;
6032 if (fd_info[fd].flags & FILE_PIPE)
6034 rc = _read (fd, &cp->chr, sizeof (char));
6036 /* Give subprocess time to buffer some more output for us before
6037 reporting that input is available; we need this because Windows 95
6038 connects DOS programs to pipes by making the pipe appear to be
6039 the normal console stdout - as a result most DOS programs will
6040 write to stdout without buffering, ie. one character at a
6041 time. Even some W32 programs do this - "dir" in a command
6042 shell on NT is very slow if we don't do this. */
6043 if (rc > 0)
6045 int wait = w32_pipe_read_delay;
6047 if (wait > 0)
6048 Sleep (wait);
6049 else if (wait < 0)
6050 while (++wait <= 0)
6051 /* Yield remainder of our time slice, effectively giving a
6052 temporary priority boost to the child process. */
6053 Sleep (0);
6056 else if (fd_info[fd].flags & FILE_SERIAL)
6058 HANDLE hnd = fd_info[fd].hnd;
6059 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6060 COMMTIMEOUTS ct;
6062 /* Configure timeouts for blocking read. */
6063 if (!GetCommTimeouts (hnd, &ct))
6064 return STATUS_READ_ERROR;
6065 ct.ReadIntervalTimeout = 0;
6066 ct.ReadTotalTimeoutMultiplier = 0;
6067 ct.ReadTotalTimeoutConstant = 0;
6068 if (!SetCommTimeouts (hnd, &ct))
6069 return STATUS_READ_ERROR;
6071 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
6073 if (GetLastError () != ERROR_IO_PENDING)
6074 return STATUS_READ_ERROR;
6075 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6076 return STATUS_READ_ERROR;
6079 else if (fd_info[fd].flags & FILE_SOCKET)
6081 unsigned long nblock = 0;
6082 /* We always want this to block, so temporarily disable NDELAY. */
6083 if (fd_info[fd].flags & FILE_NDELAY)
6084 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6086 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
6088 if (fd_info[fd].flags & FILE_NDELAY)
6090 nblock = 1;
6091 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6095 if (rc == sizeof (char))
6096 cp->status = STATUS_READ_SUCCEEDED;
6097 else
6098 cp->status = STATUS_READ_FAILED;
6100 return cp->status;
6104 _sys_wait_accept (int fd)
6106 HANDLE hEv;
6107 child_process * cp;
6108 int rc;
6110 if (fd < 0 || fd >= MAXDESC)
6111 return STATUS_READ_ERROR;
6113 cp = fd_info[fd].cp;
6115 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6116 return STATUS_READ_ERROR;
6118 cp->status = STATUS_READ_FAILED;
6120 hEv = pfn_WSACreateEvent ();
6121 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
6122 if (rc != SOCKET_ERROR)
6124 rc = WaitForSingleObject (hEv, INFINITE);
6125 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
6126 if (rc == WAIT_OBJECT_0)
6127 cp->status = STATUS_READ_SUCCEEDED;
6129 pfn_WSACloseEvent (hEv);
6131 return cp->status;
6135 sys_read (int fd, char * buffer, unsigned int count)
6137 int nchars;
6138 int to_read;
6139 DWORD waiting;
6140 char * orig_buffer = buffer;
6142 if (fd < 0)
6144 errno = EBADF;
6145 return -1;
6148 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
6150 child_process *cp = fd_info[fd].cp;
6152 if ((fd_info[fd].flags & FILE_READ) == 0)
6154 errno = EBADF;
6155 return -1;
6158 nchars = 0;
6160 /* re-read CR carried over from last read */
6161 if (fd_info[fd].flags & FILE_LAST_CR)
6163 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
6164 *buffer++ = 0x0d;
6165 count--;
6166 nchars++;
6167 fd_info[fd].flags &= ~FILE_LAST_CR;
6170 /* presence of a child_process structure means we are operating in
6171 non-blocking mode - otherwise we just call _read directly.
6172 Note that the child_process structure might be missing because
6173 reap_subprocess has been called; in this case the pipe is
6174 already broken, so calling _read on it is okay. */
6175 if (cp)
6177 int current_status = cp->status;
6179 switch (current_status)
6181 case STATUS_READ_FAILED:
6182 case STATUS_READ_ERROR:
6183 /* report normal EOF if nothing in buffer */
6184 if (nchars <= 0)
6185 fd_info[fd].flags |= FILE_AT_EOF;
6186 return nchars;
6188 case STATUS_READ_READY:
6189 case STATUS_READ_IN_PROGRESS:
6190 DebPrint (("sys_read called when read is in progress\n"));
6191 errno = EWOULDBLOCK;
6192 return -1;
6194 case STATUS_READ_SUCCEEDED:
6195 /* consume read-ahead char */
6196 *buffer++ = cp->chr;
6197 count--;
6198 nchars++;
6199 cp->status = STATUS_READ_ACKNOWLEDGED;
6200 ResetEvent (cp->char_avail);
6202 case STATUS_READ_ACKNOWLEDGED:
6203 break;
6205 default:
6206 DebPrint (("sys_read: bad status %d\n", current_status));
6207 errno = EBADF;
6208 return -1;
6211 if (fd_info[fd].flags & FILE_PIPE)
6213 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
6214 to_read = min (waiting, (DWORD) count);
6216 if (to_read > 0)
6217 nchars += _read (fd, buffer, to_read);
6219 else if (fd_info[fd].flags & FILE_SERIAL)
6221 HANDLE hnd = fd_info[fd].hnd;
6222 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6223 int rc = 0;
6224 COMMTIMEOUTS ct;
6226 if (count > 0)
6228 /* Configure timeouts for non-blocking read. */
6229 if (!GetCommTimeouts (hnd, &ct))
6231 errno = EIO;
6232 return -1;
6234 ct.ReadIntervalTimeout = MAXDWORD;
6235 ct.ReadTotalTimeoutMultiplier = 0;
6236 ct.ReadTotalTimeoutConstant = 0;
6237 if (!SetCommTimeouts (hnd, &ct))
6239 errno = EIO;
6240 return -1;
6243 if (!ResetEvent (ovl->hEvent))
6245 errno = EIO;
6246 return -1;
6248 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
6250 if (GetLastError () != ERROR_IO_PENDING)
6252 errno = EIO;
6253 return -1;
6255 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6257 errno = EIO;
6258 return -1;
6261 nchars += rc;
6264 else /* FILE_SOCKET */
6266 if (winsock_lib == NULL) emacs_abort ();
6268 /* do the equivalent of a non-blocking read */
6269 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
6270 if (waiting == 0 && nchars == 0)
6272 h_errno = errno = EWOULDBLOCK;
6273 return -1;
6276 if (waiting)
6278 /* always use binary mode for sockets */
6279 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
6280 if (res == SOCKET_ERROR)
6282 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
6283 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
6284 set_errno ();
6285 return -1;
6287 nchars += res;
6291 else
6293 int nread = _read (fd, buffer, count);
6294 if (nread >= 0)
6295 nchars += nread;
6296 else if (nchars == 0)
6297 nchars = nread;
6300 if (nchars <= 0)
6301 fd_info[fd].flags |= FILE_AT_EOF;
6302 /* Perform text mode translation if required. */
6303 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
6305 nchars = crlf_to_lf (nchars, orig_buffer);
6306 /* If buffer contains only CR, return that. To be absolutely
6307 sure we should attempt to read the next char, but in
6308 practice a CR to be followed by LF would not appear by
6309 itself in the buffer. */
6310 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
6312 fd_info[fd].flags |= FILE_LAST_CR;
6313 nchars--;
6317 else
6318 nchars = _read (fd, buffer, count);
6320 return nchars;
6323 /* From w32xfns.c */
6324 extern HANDLE interrupt_handle;
6326 /* For now, don't bother with a non-blocking mode */
6328 sys_write (int fd, const void * buffer, unsigned int count)
6330 int nchars;
6332 if (fd < 0)
6334 errno = EBADF;
6335 return -1;
6338 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
6340 if ((fd_info[fd].flags & FILE_WRITE) == 0)
6342 errno = EBADF;
6343 return -1;
6346 /* Perform text mode translation if required. */
6347 if ((fd_info[fd].flags & FILE_BINARY) == 0)
6349 char * tmpbuf = alloca (count * 2);
6350 unsigned char * src = (void *)buffer;
6351 unsigned char * dst = tmpbuf;
6352 int nbytes = count;
6354 while (1)
6356 unsigned char *next;
6357 /* copy next line or remaining bytes */
6358 next = _memccpy (dst, src, '\n', nbytes);
6359 if (next)
6361 /* copied one line ending with '\n' */
6362 int copied = next - dst;
6363 nbytes -= copied;
6364 src += copied;
6365 /* insert '\r' before '\n' */
6366 next[-1] = '\r';
6367 next[0] = '\n';
6368 dst = next + 1;
6369 count++;
6371 else
6372 /* copied remaining partial line -> now finished */
6373 break;
6375 buffer = tmpbuf;
6379 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
6381 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
6382 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
6383 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
6384 DWORD active = 0;
6386 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
6388 if (GetLastError () != ERROR_IO_PENDING)
6390 errno = EIO;
6391 return -1;
6393 if (detect_input_pending ())
6394 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
6395 QS_ALLINPUT);
6396 else
6397 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
6398 if (active == WAIT_OBJECT_0)
6399 { /* User pressed C-g, cancel write, then leave. Don't bother
6400 cleaning up as we may only get stuck in buggy drivers. */
6401 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
6402 CancelIo (hnd);
6403 errno = EIO;
6404 return -1;
6406 if (active == WAIT_OBJECT_0 + 1
6407 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
6409 errno = EIO;
6410 return -1;
6414 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
6416 unsigned long nblock = 0;
6417 if (winsock_lib == NULL) emacs_abort ();
6419 /* TODO: implement select() properly so non-blocking I/O works. */
6420 /* For now, make sure the write blocks. */
6421 if (fd_info[fd].flags & FILE_NDELAY)
6422 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6424 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
6426 /* Set the socket back to non-blocking if it was before,
6427 for other operations that support it. */
6428 if (fd_info[fd].flags & FILE_NDELAY)
6430 nblock = 1;
6431 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6434 if (nchars == SOCKET_ERROR)
6436 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
6437 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
6438 set_errno ();
6441 else
6443 /* Some networked filesystems don't like too large writes, so
6444 break them into smaller chunks. See the Comments section of
6445 the MSDN documentation of WriteFile for details behind the
6446 choice of the value of CHUNK below. See also the thread
6447 http://thread.gmane.org/gmane.comp.version-control.git/145294
6448 in the git mailing list. */
6449 const unsigned char *p = buffer;
6450 const unsigned chunk = 30 * 1024 * 1024;
6452 nchars = 0;
6453 while (count > 0)
6455 unsigned this_chunk = count < chunk ? count : chunk;
6456 int n = _write (fd, p, this_chunk);
6458 nchars += n;
6459 if (n < 0)
6461 nchars = n;
6462 break;
6464 else if (n < this_chunk)
6465 break;
6466 count -= n;
6467 p += n;
6471 return nchars;
6474 /* The Windows CRT functions are "optimized for speed", so they don't
6475 check for timezone and DST changes if they were last called less
6476 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
6477 all Emacs features that repeatedly call time functions (e.g.,
6478 display-time) are in real danger of missing timezone and DST
6479 changes. Calling tzset before each localtime call fixes that. */
6480 struct tm *
6481 sys_localtime (const time_t *t)
6483 tzset ();
6484 return localtime (t);
6489 /* Try loading LIBRARY_ID from the file(s) specified in
6490 Vdynamic_library_alist. If the library is loaded successfully,
6491 return the handle of the DLL, and record the filename in the
6492 property :loaded-from of LIBRARY_ID. If the library could not be
6493 found, or when it was already loaded (because the handle is not
6494 recorded anywhere, and so is lost after use), return NULL.
6496 We could also save the handle in :loaded-from, but currently
6497 there's no use case for it. */
6498 HMODULE
6499 w32_delayed_load (Lisp_Object library_id)
6501 HMODULE library_dll = NULL;
6503 CHECK_SYMBOL (library_id);
6505 if (CONSP (Vdynamic_library_alist)
6506 && NILP (Fassq (library_id, Vlibrary_cache)))
6508 Lisp_Object found = Qnil;
6509 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
6511 if (CONSP (dlls))
6512 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
6514 CHECK_STRING_CAR (dlls);
6515 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
6517 char name[MAX_PATH];
6518 DWORD len;
6520 len = GetModuleFileNameA (library_dll, name, sizeof (name));
6521 found = Fcons (XCAR (dlls),
6522 (len > 0)
6523 /* Possibly truncated */
6524 ? make_specified_string (name, -1, len, 1)
6525 : Qnil);
6526 break;
6530 Fput (library_id, QCloaded_from, found);
6533 return library_dll;
6537 void
6538 check_windows_init_file (void)
6540 /* A common indication that Emacs is not installed properly is when
6541 it cannot find the Windows installation file. If this file does
6542 not exist in the expected place, tell the user. */
6544 if (!noninteractive && !inhibit_window_system
6545 /* Vload_path is not yet initialized when we are loading
6546 loadup.el. */
6547 && NILP (Vpurify_flag))
6549 Lisp_Object init_file;
6550 int fd;
6552 init_file = build_string ("term/w32-win");
6553 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
6554 if (fd < 0)
6556 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
6557 char *init_file_name = SDATA (init_file);
6558 char *load_path = SDATA (load_path_print);
6559 char *buffer = alloca (1024
6560 + strlen (init_file_name)
6561 + strlen (load_path));
6563 sprintf (buffer,
6564 "The Emacs Windows initialization file \"%s.el\" "
6565 "could not be found in your Emacs installation. "
6566 "Emacs checked the following directories for this file:\n"
6567 "\n%s\n\n"
6568 "When Emacs cannot find this file, it usually means that it "
6569 "was not installed properly, or its distribution file was "
6570 "not unpacked properly.\nSee the README.W32 file in the "
6571 "top-level Emacs directory for more information.",
6572 init_file_name, load_path);
6573 MessageBox (NULL,
6574 buffer,
6575 "Emacs Abort Dialog",
6576 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
6577 /* Use the low-level system abort. */
6578 abort ();
6580 else
6582 _close (fd);
6587 void
6588 term_ntproc (int ignored)
6590 (void)ignored;
6592 term_timers ();
6594 /* shutdown the socket interface if necessary */
6595 term_winsock ();
6597 term_w32select ();
6600 void
6601 init_ntproc (int dumping)
6603 sigset_t initial_mask = 0;
6605 /* Initialize the socket interface now if available and requested by
6606 the user by defining PRELOAD_WINSOCK; otherwise loading will be
6607 delayed until open-network-stream is called (w32-has-winsock can
6608 also be used to dynamically load or reload winsock).
6610 Conveniently, init_environment is called before us, so
6611 PRELOAD_WINSOCK can be set in the registry. */
6613 /* Always initialize this correctly. */
6614 winsock_lib = NULL;
6616 if (getenv ("PRELOAD_WINSOCK") != NULL)
6617 init_winsock (TRUE);
6619 /* Initial preparation for subprocess support: replace our standard
6620 handles with non-inheritable versions. */
6622 HANDLE parent;
6623 HANDLE stdin_save = INVALID_HANDLE_VALUE;
6624 HANDLE stdout_save = INVALID_HANDLE_VALUE;
6625 HANDLE stderr_save = INVALID_HANDLE_VALUE;
6627 parent = GetCurrentProcess ();
6629 /* ignore errors when duplicating and closing; typically the
6630 handles will be invalid when running as a gui program. */
6631 DuplicateHandle (parent,
6632 GetStdHandle (STD_INPUT_HANDLE),
6633 parent,
6634 &stdin_save,
6636 FALSE,
6637 DUPLICATE_SAME_ACCESS);
6639 DuplicateHandle (parent,
6640 GetStdHandle (STD_OUTPUT_HANDLE),
6641 parent,
6642 &stdout_save,
6644 FALSE,
6645 DUPLICATE_SAME_ACCESS);
6647 DuplicateHandle (parent,
6648 GetStdHandle (STD_ERROR_HANDLE),
6649 parent,
6650 &stderr_save,
6652 FALSE,
6653 DUPLICATE_SAME_ACCESS);
6655 fclose (stdin);
6656 fclose (stdout);
6657 fclose (stderr);
6659 if (stdin_save != INVALID_HANDLE_VALUE)
6660 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
6661 else
6662 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
6663 _fdopen (0, "r");
6665 if (stdout_save != INVALID_HANDLE_VALUE)
6666 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
6667 else
6668 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
6669 _fdopen (1, "w");
6671 if (stderr_save != INVALID_HANDLE_VALUE)
6672 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
6673 else
6674 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
6675 _fdopen (2, "w");
6678 /* unfortunately, atexit depends on implementation of malloc */
6679 /* atexit (term_ntproc); */
6680 if (!dumping)
6682 /* Make sure we start with all signals unblocked. */
6683 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
6684 signal (SIGABRT, term_ntproc);
6686 init_timers ();
6688 /* determine which drives are fixed, for GetCachedVolumeInformation */
6690 /* GetDriveType must have trailing backslash. */
6691 char drive[] = "A:\\";
6693 /* Loop over all possible drive letters */
6694 while (*drive <= 'Z')
6696 /* Record if this drive letter refers to a fixed drive. */
6697 fixed_drives[DRIVE_INDEX (*drive)] =
6698 (GetDriveType (drive) == DRIVE_FIXED);
6700 (*drive)++;
6703 /* Reset the volume info cache. */
6704 volume_cache = NULL;
6709 shutdown_handler ensures that buffers' autosave files are
6710 up to date when the user logs off, or the system shuts down.
6712 static BOOL WINAPI
6713 shutdown_handler (DWORD type)
6715 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6716 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
6717 || type == CTRL_LOGOFF_EVENT /* User logs off. */
6718 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
6720 /* Shut down cleanly, making sure autosave files are up to date. */
6721 shut_down_emacs (0, Qnil);
6724 /* Allow other handlers to handle this signal. */
6725 return FALSE;
6729 globals_of_w32 is used to initialize those global variables that
6730 must always be initialized on startup even when the global variable
6731 initialized is non zero (see the function main in emacs.c).
6733 void
6734 globals_of_w32 (void)
6736 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
6738 get_process_times_fn = (GetProcessTimes_Proc)
6739 GetProcAddress (kernel32, "GetProcessTimes");
6741 DEFSYM (QCloaded_from, ":loaded-from");
6743 g_b_init_is_windows_9x = 0;
6744 g_b_init_open_process_token = 0;
6745 g_b_init_get_token_information = 0;
6746 g_b_init_lookup_account_sid = 0;
6747 g_b_init_get_sid_sub_authority = 0;
6748 g_b_init_get_sid_sub_authority_count = 0;
6749 g_b_init_get_security_info = 0;
6750 g_b_init_get_file_security = 0;
6751 g_b_init_get_security_descriptor_owner = 0;
6752 g_b_init_get_security_descriptor_group = 0;
6753 g_b_init_is_valid_sid = 0;
6754 g_b_init_create_toolhelp32_snapshot = 0;
6755 g_b_init_process32_first = 0;
6756 g_b_init_process32_next = 0;
6757 g_b_init_open_thread_token = 0;
6758 g_b_init_impersonate_self = 0;
6759 g_b_init_revert_to_self = 0;
6760 g_b_init_get_process_memory_info = 0;
6761 g_b_init_get_process_working_set_size = 0;
6762 g_b_init_global_memory_status = 0;
6763 g_b_init_global_memory_status_ex = 0;
6764 g_b_init_equal_sid = 0;
6765 g_b_init_copy_sid = 0;
6766 g_b_init_get_length_sid = 0;
6767 g_b_init_get_native_system_info = 0;
6768 g_b_init_get_system_times = 0;
6769 g_b_init_create_symbolic_link = 0;
6770 num_of_processors = 0;
6771 /* The following sets a handler for shutdown notifications for
6772 console apps. This actually applies to Emacs in both console and
6773 GUI modes, since we had to fool windows into thinking emacs is a
6774 console application to get console mode to work. */
6775 SetConsoleCtrlHandler (shutdown_handler, TRUE);
6777 /* "None" is the default group name on standalone workstations. */
6778 strcpy (dflt_group_name, "None");
6781 /* For make-serial-process */
6783 serial_open (char *port)
6785 HANDLE hnd;
6786 child_process *cp;
6787 int fd = -1;
6789 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
6790 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
6791 if (hnd == INVALID_HANDLE_VALUE)
6792 error ("Could not open %s", port);
6793 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
6794 if (fd == -1)
6795 error ("Could not open %s", port);
6797 cp = new_child ();
6798 if (!cp)
6799 error ("Could not create child process");
6800 cp->fd = fd;
6801 cp->status = STATUS_READ_ACKNOWLEDGED;
6802 fd_info[ fd ].hnd = hnd;
6803 fd_info[ fd ].flags |=
6804 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
6805 if (fd_info[ fd ].cp != NULL)
6807 error ("fd_info[fd = %d] is already in use", fd);
6809 fd_info[ fd ].cp = cp;
6810 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6811 if (cp->ovl_read.hEvent == NULL)
6812 error ("Could not create read event");
6813 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6814 if (cp->ovl_write.hEvent == NULL)
6815 error ("Could not create write event");
6817 return fd;
6820 /* For serial-process-configure */
6821 void
6822 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
6824 Lisp_Object childp2 = Qnil;
6825 Lisp_Object tem = Qnil;
6826 HANDLE hnd;
6827 DCB dcb;
6828 COMMTIMEOUTS ct;
6829 char summary[4] = "???"; /* This usually becomes "8N1". */
6831 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
6832 error ("Not a serial process");
6833 hnd = fd_info[ p->outfd ].hnd;
6835 childp2 = Fcopy_sequence (p->childp);
6837 /* Initialize timeouts for blocking read and blocking write. */
6838 if (!GetCommTimeouts (hnd, &ct))
6839 error ("GetCommTimeouts() failed");
6840 ct.ReadIntervalTimeout = 0;
6841 ct.ReadTotalTimeoutMultiplier = 0;
6842 ct.ReadTotalTimeoutConstant = 0;
6843 ct.WriteTotalTimeoutMultiplier = 0;
6844 ct.WriteTotalTimeoutConstant = 0;
6845 if (!SetCommTimeouts (hnd, &ct))
6846 error ("SetCommTimeouts() failed");
6847 /* Read port attributes and prepare default configuration. */
6848 memset (&dcb, 0, sizeof (dcb));
6849 dcb.DCBlength = sizeof (DCB);
6850 if (!GetCommState (hnd, &dcb))
6851 error ("GetCommState() failed");
6852 dcb.fBinary = TRUE;
6853 dcb.fNull = FALSE;
6854 dcb.fAbortOnError = FALSE;
6855 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6856 dcb.ErrorChar = 0;
6857 dcb.EofChar = 0;
6858 dcb.EvtChar = 0;
6860 /* Configure speed. */
6861 if (!NILP (Fplist_member (contact, QCspeed)))
6862 tem = Fplist_get (contact, QCspeed);
6863 else
6864 tem = Fplist_get (p->childp, QCspeed);
6865 CHECK_NUMBER (tem);
6866 dcb.BaudRate = XINT (tem);
6867 childp2 = Fplist_put (childp2, QCspeed, tem);
6869 /* Configure bytesize. */
6870 if (!NILP (Fplist_member (contact, QCbytesize)))
6871 tem = Fplist_get (contact, QCbytesize);
6872 else
6873 tem = Fplist_get (p->childp, QCbytesize);
6874 if (NILP (tem))
6875 tem = make_number (8);
6876 CHECK_NUMBER (tem);
6877 if (XINT (tem) != 7 && XINT (tem) != 8)
6878 error (":bytesize must be nil (8), 7, or 8");
6879 dcb.ByteSize = XINT (tem);
6880 summary[0] = XINT (tem) + '0';
6881 childp2 = Fplist_put (childp2, QCbytesize, tem);
6883 /* Configure parity. */
6884 if (!NILP (Fplist_member (contact, QCparity)))
6885 tem = Fplist_get (contact, QCparity);
6886 else
6887 tem = Fplist_get (p->childp, QCparity);
6888 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
6889 error (":parity must be nil (no parity), `even', or `odd'");
6890 dcb.fParity = FALSE;
6891 dcb.Parity = NOPARITY;
6892 dcb.fErrorChar = FALSE;
6893 if (NILP (tem))
6895 summary[1] = 'N';
6897 else if (EQ (tem, Qeven))
6899 summary[1] = 'E';
6900 dcb.fParity = TRUE;
6901 dcb.Parity = EVENPARITY;
6902 dcb.fErrorChar = TRUE;
6904 else if (EQ (tem, Qodd))
6906 summary[1] = 'O';
6907 dcb.fParity = TRUE;
6908 dcb.Parity = ODDPARITY;
6909 dcb.fErrorChar = TRUE;
6911 childp2 = Fplist_put (childp2, QCparity, tem);
6913 /* Configure stopbits. */
6914 if (!NILP (Fplist_member (contact, QCstopbits)))
6915 tem = Fplist_get (contact, QCstopbits);
6916 else
6917 tem = Fplist_get (p->childp, QCstopbits);
6918 if (NILP (tem))
6919 tem = make_number (1);
6920 CHECK_NUMBER (tem);
6921 if (XINT (tem) != 1 && XINT (tem) != 2)
6922 error (":stopbits must be nil (1 stopbit), 1, or 2");
6923 summary[2] = XINT (tem) + '0';
6924 if (XINT (tem) == 1)
6925 dcb.StopBits = ONESTOPBIT;
6926 else if (XINT (tem) == 2)
6927 dcb.StopBits = TWOSTOPBITS;
6928 childp2 = Fplist_put (childp2, QCstopbits, tem);
6930 /* Configure flowcontrol. */
6931 if (!NILP (Fplist_member (contact, QCflowcontrol)))
6932 tem = Fplist_get (contact, QCflowcontrol);
6933 else
6934 tem = Fplist_get (p->childp, QCflowcontrol);
6935 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
6936 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6937 dcb.fOutxCtsFlow = FALSE;
6938 dcb.fOutxDsrFlow = FALSE;
6939 dcb.fDtrControl = DTR_CONTROL_DISABLE;
6940 dcb.fDsrSensitivity = FALSE;
6941 dcb.fTXContinueOnXoff = FALSE;
6942 dcb.fOutX = FALSE;
6943 dcb.fInX = FALSE;
6944 dcb.fRtsControl = RTS_CONTROL_DISABLE;
6945 dcb.XonChar = 17; /* Control-Q */
6946 dcb.XoffChar = 19; /* Control-S */
6947 if (NILP (tem))
6949 /* Already configured. */
6951 else if (EQ (tem, Qhw))
6953 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
6954 dcb.fOutxCtsFlow = TRUE;
6956 else if (EQ (tem, Qsw))
6958 dcb.fOutX = TRUE;
6959 dcb.fInX = TRUE;
6961 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
6963 /* Activate configuration. */
6964 if (!SetCommState (hnd, &dcb))
6965 error ("SetCommState() failed");
6967 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
6968 pset_childp (p, childp2);
6971 #ifdef HAVE_GNUTLS
6973 ssize_t
6974 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
6976 int n, sc, err;
6977 SELECT_TYPE fdset;
6978 EMACS_TIME timeout;
6979 struct Lisp_Process *process = (struct Lisp_Process *)p;
6980 int fd = process->infd;
6982 for (;;)
6984 n = sys_read (fd, (char*)buf, sz);
6986 if (n >= 0)
6987 return n;
6989 err = errno;
6991 if (err == EWOULDBLOCK)
6993 /* Set a small timeout. */
6994 timeout = make_emacs_time (1, 0);
6995 FD_ZERO (&fdset);
6996 FD_SET ((int)fd, &fdset);
6998 /* Use select with the timeout to poll the selector. */
6999 sc = select (fd + 1, &fdset, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7000 &timeout, NULL);
7002 if (sc > 0)
7003 continue; /* Try again. */
7005 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
7006 Also accept select return 0 as an indicator to EAGAIN. */
7007 if (sc == 0 || errno == EWOULDBLOCK)
7008 err = EAGAIN;
7009 else
7010 err = errno; /* Other errors are just passed on. */
7013 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
7015 return -1;
7019 ssize_t
7020 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
7022 struct Lisp_Process *process = (struct Lisp_Process *)p;
7023 int fd = process->outfd;
7024 ssize_t n = sys_write (fd, buf, sz);
7026 /* 0 or more bytes written means everything went fine. */
7027 if (n >= 0)
7028 return n;
7030 /* Negative bytes written means we got an error in errno.
7031 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7032 emacs_gnutls_transport_set_errno (process->gnutls_state,
7033 errno == EWOULDBLOCK ? EAGAIN : errno);
7035 return -1;
7037 #endif /* HAVE_GNUTLS */
7039 /* end of w32.c */