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