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