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