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