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