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