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