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