1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
23 #include <stddef.h> /* for offsetof */
33 #include <sys/utime.h>
34 #include <mbstring.h> /* for _mbspbrk */
36 /* must include CRT headers *before* config.h */
71 #define _ANONYMOUS_UNION
72 #define _ANONYMOUS_STRUCT
78 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
79 #include <sys/socket.h>
104 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
105 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
107 void globals_of_w32 ();
108 static DWORD
get_rid (PSID
);
110 extern Lisp_Object Vw32_downcase_file_names
;
111 extern Lisp_Object Vw32_generate_fake_inodes
;
112 extern Lisp_Object Vw32_get_true_file_attributes
;
113 /* Defined in process.c for its own purpose. */
114 extern Lisp_Object Qlocal
;
116 extern int w32_num_mouse_buttons
;
119 /* Initialization states.
121 WARNING: If you add any more such variables for additional APIs,
122 you MUST add initialization for them to globals_of_w32
123 below. This is because these variables might get set
124 to non-NULL values during dumping, but the dumped Emacs
125 cannot reuse those values, because it could be run on a
126 different version of the OS, where API addresses are
128 static BOOL g_b_init_is_windows_9x
;
129 static BOOL g_b_init_open_process_token
;
130 static BOOL g_b_init_get_token_information
;
131 static BOOL g_b_init_lookup_account_sid
;
132 static BOOL g_b_init_get_sid_identifier_authority
;
133 static BOOL g_b_init_get_sid_sub_authority
;
134 static BOOL g_b_init_get_sid_sub_authority_count
;
135 static BOOL g_b_init_get_file_security
;
136 static BOOL g_b_init_get_security_descriptor_owner
;
137 static BOOL g_b_init_get_security_descriptor_group
;
138 static BOOL g_b_init_is_valid_sid
;
141 BEGIN: Wrapper functions around OpenProcessToken
142 and other functions in advapi32.dll that are only
143 supported in Windows NT / 2k / XP
145 /* ** Function pointer typedefs ** */
146 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
147 HANDLE ProcessHandle
,
149 PHANDLE TokenHandle
);
150 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
152 TOKEN_INFORMATION_CLASS TokenInformationClass
,
153 LPVOID TokenInformation
,
154 DWORD TokenInformationLength
,
155 PDWORD ReturnLength
);
156 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
157 HANDLE process_handle
,
158 LPFILETIME creation_time
,
159 LPFILETIME exit_time
,
160 LPFILETIME kernel_time
,
161 LPFILETIME user_time
);
163 GetProcessTimes_Proc get_process_times_fn
= NULL
;
166 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
167 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
169 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
170 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
172 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
173 LPCTSTR lpSystemName
,
178 LPDWORD cbDomainName
,
179 PSID_NAME_USE peUse
);
180 typedef PSID_IDENTIFIER_AUTHORITY (WINAPI
* GetSidIdentifierAuthority_Proc
) (
182 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
185 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
187 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
189 SECURITY_INFORMATION RequestedInformation
,
190 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
192 LPDWORD lpnLengthNeeded
);
193 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
194 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
196 LPBOOL lpbOwnerDefaulted
);
197 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
198 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
200 LPBOOL lpbGroupDefaulted
);
201 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
204 /* ** A utility function ** */
208 static BOOL s_b_ret
=0;
209 OSVERSIONINFO os_ver
;
210 if (g_b_init_is_windows_9x
== 0)
212 g_b_init_is_windows_9x
= 1;
213 ZeroMemory(&os_ver
, sizeof(OSVERSIONINFO
));
214 os_ver
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
215 if (GetVersionEx (&os_ver
))
217 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
223 /* Get total user and system times for get-internal-run-time.
224 Returns a list of three integers if the times are provided by the OS
225 (NT derivatives), otherwise it returns the result of current-time. */
227 w32_get_internal_run_time ()
229 if (get_process_times_fn
)
231 FILETIME create
, exit
, kernel
, user
;
232 HANDLE proc
= GetCurrentProcess();
233 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
235 LARGE_INTEGER user_int
, kernel_int
, total
;
237 user_int
.LowPart
= user
.dwLowDateTime
;
238 user_int
.HighPart
= user
.dwHighDateTime
;
239 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
240 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
241 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
242 /* FILETIME is 100 nanosecond increments, Emacs only wants
243 microsecond resolution. */
244 total
.QuadPart
/= 10;
245 microseconds
= total
.QuadPart
% 1000000;
246 total
.QuadPart
/= 1000000;
248 /* Sanity check to make sure we can represent the result. */
249 if (total
.HighPart
== 0)
251 int secs
= total
.LowPart
;
253 return list3 (make_number ((secs
>> 16) & 0xffff),
254 make_number (secs
& 0xffff),
255 make_number (microseconds
));
260 return Fcurrent_time ();
263 /* ** The wrapper functions ** */
265 BOOL WINAPI
open_process_token (
266 HANDLE ProcessHandle
,
270 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
271 HMODULE hm_advapi32
= NULL
;
272 if (is_windows_9x () == TRUE
)
276 if (g_b_init_open_process_token
== 0)
278 g_b_init_open_process_token
= 1;
279 hm_advapi32
= LoadLibrary ("Advapi32.dll");
280 s_pfn_Open_Process_Token
=
281 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
283 if (s_pfn_Open_Process_Token
== NULL
)
288 s_pfn_Open_Process_Token (
295 BOOL WINAPI
get_token_information (
297 TOKEN_INFORMATION_CLASS TokenInformationClass
,
298 LPVOID TokenInformation
,
299 DWORD TokenInformationLength
,
302 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
303 HMODULE hm_advapi32
= NULL
;
304 if (is_windows_9x () == TRUE
)
308 if (g_b_init_get_token_information
== 0)
310 g_b_init_get_token_information
= 1;
311 hm_advapi32
= LoadLibrary ("Advapi32.dll");
312 s_pfn_Get_Token_Information
=
313 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
315 if (s_pfn_Get_Token_Information
== NULL
)
320 s_pfn_Get_Token_Information (
322 TokenInformationClass
,
324 TokenInformationLength
,
329 BOOL WINAPI
lookup_account_sid (
330 LPCTSTR lpSystemName
,
335 LPDWORD cbDomainName
,
338 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
339 HMODULE hm_advapi32
= NULL
;
340 if (is_windows_9x () == TRUE
)
344 if (g_b_init_lookup_account_sid
== 0)
346 g_b_init_lookup_account_sid
= 1;
347 hm_advapi32
= LoadLibrary ("Advapi32.dll");
348 s_pfn_Lookup_Account_Sid
=
349 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
351 if (s_pfn_Lookup_Account_Sid
== NULL
)
356 s_pfn_Lookup_Account_Sid (
367 PSID_IDENTIFIER_AUTHORITY WINAPI
get_sid_identifier_authority (
370 static GetSidIdentifierAuthority_Proc s_pfn_Get_Sid_Identifier_Authority
= NULL
;
371 HMODULE hm_advapi32
= NULL
;
372 if (is_windows_9x () == TRUE
)
376 if (g_b_init_get_sid_identifier_authority
== 0)
378 g_b_init_get_sid_identifier_authority
= 1;
379 hm_advapi32
= LoadLibrary ("Advapi32.dll");
380 s_pfn_Get_Sid_Identifier_Authority
=
381 (GetSidIdentifierAuthority_Proc
) GetProcAddress (
382 hm_advapi32
, "GetSidIdentifierAuthority");
384 if (s_pfn_Get_Sid_Identifier_Authority
== NULL
)
388 return (s_pfn_Get_Sid_Identifier_Authority (pSid
));
391 PDWORD WINAPI
get_sid_sub_authority (
395 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
396 static DWORD zero
= 0U;
397 HMODULE hm_advapi32
= NULL
;
398 if (is_windows_9x () == TRUE
)
402 if (g_b_init_get_sid_sub_authority
== 0)
404 g_b_init_get_sid_sub_authority
= 1;
405 hm_advapi32
= LoadLibrary ("Advapi32.dll");
406 s_pfn_Get_Sid_Sub_Authority
=
407 (GetSidSubAuthority_Proc
) GetProcAddress (
408 hm_advapi32
, "GetSidSubAuthority");
410 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
414 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
417 PUCHAR WINAPI
get_sid_sub_authority_count (
420 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
421 static UCHAR zero
= 0U;
422 HMODULE hm_advapi32
= NULL
;
423 if (is_windows_9x () == TRUE
)
427 if (g_b_init_get_sid_sub_authority_count
== 0)
429 g_b_init_get_sid_sub_authority_count
= 1;
430 hm_advapi32
= LoadLibrary ("Advapi32.dll");
431 s_pfn_Get_Sid_Sub_Authority_Count
=
432 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
433 hm_advapi32
, "GetSidSubAuthorityCount");
435 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
439 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
442 BOOL WINAPI
get_file_security (
444 SECURITY_INFORMATION RequestedInformation
,
445 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
447 LPDWORD lpnLengthNeeded
)
449 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
450 HMODULE hm_advapi32
= NULL
;
451 if (is_windows_9x () == TRUE
)
455 if (g_b_init_get_file_security
== 0)
457 g_b_init_get_file_security
= 1;
458 hm_advapi32
= LoadLibrary ("Advapi32.dll");
459 s_pfn_Get_File_Security
=
460 (GetFileSecurity_Proc
) GetProcAddress (
461 hm_advapi32
, GetFileSecurity_Name
);
463 if (s_pfn_Get_File_Security
== NULL
)
467 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
468 pSecurityDescriptor
, nLength
,
472 BOOL WINAPI
get_security_descriptor_owner (
473 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
475 LPBOOL lpbOwnerDefaulted
)
477 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
478 HMODULE hm_advapi32
= NULL
;
479 if (is_windows_9x () == TRUE
)
483 if (g_b_init_get_security_descriptor_owner
== 0)
485 g_b_init_get_security_descriptor_owner
= 1;
486 hm_advapi32
= LoadLibrary ("Advapi32.dll");
487 s_pfn_Get_Security_Descriptor_Owner
=
488 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
489 hm_advapi32
, "GetSecurityDescriptorOwner");
491 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
495 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
499 BOOL WINAPI
get_security_descriptor_group (
500 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
502 LPBOOL lpbGroupDefaulted
)
504 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
505 HMODULE hm_advapi32
= NULL
;
506 if (is_windows_9x () == TRUE
)
510 if (g_b_init_get_security_descriptor_group
== 0)
512 g_b_init_get_security_descriptor_group
= 1;
513 hm_advapi32
= LoadLibrary ("Advapi32.dll");
514 s_pfn_Get_Security_Descriptor_Group
=
515 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
516 hm_advapi32
, "GetSecurityDescriptorGroup");
518 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
522 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
526 BOOL WINAPI
is_valid_sid (
529 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
530 HMODULE hm_advapi32
= NULL
;
531 if (is_windows_9x () == TRUE
)
535 if (g_b_init_is_valid_sid
== 0)
537 g_b_init_is_valid_sid
= 1;
538 hm_advapi32
= LoadLibrary ("Advapi32.dll");
540 (IsValidSid_Proc
) GetProcAddress (
541 hm_advapi32
, "IsValidSid");
543 if (s_pfn_Is_Valid_Sid
== NULL
)
547 return (s_pfn_Is_Valid_Sid (sid
));
551 END: Wrapper functions around OpenProcessToken
552 and other functions in advapi32.dll that are only
553 supported in Windows NT / 2k / XP
557 /* Equivalent of strerror for W32 error codes. */
559 w32_strerror (int error_no
)
561 static char buf
[500];
564 error_no
= GetLastError ();
567 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
, NULL
,
569 0, /* choose most suitable language */
570 buf
, sizeof (buf
), NULL
))
571 sprintf (buf
, "w32 error %u", error_no
);
575 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
576 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
578 This is called from alloc.c:valid_pointer_p. */
580 w32_valid_pointer_p (void *p
, int size
)
583 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
587 unsigned char *buf
= alloca (size
);
588 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
597 static char startup_dir
[MAXPATHLEN
];
599 /* Get the current working directory. */
604 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
608 /* Emacs doesn't actually change directory itself, and we want to
609 force our real wd to be where emacs.exe is to avoid unnecessary
610 conflicts when trying to rename or delete directories. */
611 strcpy (dir
, startup_dir
);
617 /* Emulate gethostname. */
619 gethostname (char *buffer
, int size
)
621 /* NT only allows small host names, so the buffer is
622 certainly large enough. */
623 return !GetComputerName (buffer
, &size
);
625 #endif /* HAVE_SOCKETS */
627 /* Emulate getloadavg. */
629 getloadavg (double loadavg
[], int nelem
)
633 /* A faithful emulation is going to have to be saved for a rainy day. */
634 for (i
= 0; i
< nelem
; i
++)
641 /* Emulate getpwuid, getpwnam and others. */
643 #define PASSWD_FIELD_SIZE 256
645 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
646 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
647 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
648 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
649 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
651 static struct passwd dflt_passwd
=
663 static char dflt_group_name
[GNLEN
+1];
665 static struct group dflt_group
=
667 /* When group information is not available, we return this as the
668 group for all files. */
676 return dflt_passwd
.pw_uid
;
682 /* I could imagine arguing for checking to see whether the user is
683 in the Administrators group and returning a UID of 0 for that
684 case, but I don't know how wise that would be in the long run. */
691 return dflt_passwd
.pw_gid
;
703 if (uid
== dflt_passwd
.pw_uid
)
715 getpwnam (char *name
)
719 pw
= getpwuid (getuid ());
723 if (stricmp (name
, pw
->pw_name
))
732 /* Find the user's real name by opening the process token and
733 looking up the name associated with the user-sid in that token.
735 Use the relative portion of the identifier authority value from
736 the user-sid as the user id value (same for group id using the
737 primary group sid from the process token). */
739 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
740 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), trash
;
741 DWORD glength
= sizeof (gname
);
743 SID_NAME_USE user_type
;
744 unsigned char buf
[1024];
745 TOKEN_USER user_token
;
746 TOKEN_PRIMARY_GROUP group_token
;
748 if (open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
)
749 && get_token_information (token
, TokenUser
,
750 (PVOID
)buf
, sizeof (buf
), &trash
)
751 && (memcpy (&user_token
, buf
, sizeof (user_token
)),
752 lookup_account_sid (NULL
, user_token
.User
.Sid
, uname
, &ulength
,
753 domain
, &dlength
, &user_type
)))
755 strcpy (dflt_passwd
.pw_name
, uname
);
756 /* Determine a reasonable uid value. */
757 if (stricmp ("administrator", uname
) == 0)
759 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
760 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
764 /* Use the last sub-authority value of the RID, the relative
765 portion of the SID, as user/group ID. */
766 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
768 /* Get group id and name. */
769 if (get_token_information (token
, TokenPrimaryGroup
,
770 (PVOID
)buf
, sizeof (buf
), &trash
))
772 memcpy (&group_token
, buf
, sizeof (group_token
));
773 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
774 dlength
= sizeof (domain
);
775 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
776 gname
, &glength
, NULL
, &dlength
,
778 strcpy (dflt_group_name
, gname
);
781 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
784 /* If security calls are not supported (presumably because we
785 are running under Windows 95), fallback to this. */
786 else if (GetUserName (uname
, &ulength
))
788 strcpy (dflt_passwd
.pw_name
, uname
);
789 if (stricmp ("administrator", uname
) == 0)
790 dflt_passwd
.pw_uid
= 0;
792 dflt_passwd
.pw_uid
= 123;
793 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
797 strcpy (dflt_passwd
.pw_name
, "unknown");
798 dflt_passwd
.pw_uid
= 123;
799 dflt_passwd
.pw_gid
= 123;
801 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
803 /* Ensure HOME and SHELL are defined. */
804 if (getenv ("HOME") == NULL
)
806 if (getenv ("SHELL") == NULL
)
809 /* Set dir and shell from environment variables. */
810 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
811 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
820 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
821 return ((rand () << 15) | rand ());
831 /* Normalize filename by converting all path separators to
832 the specified separator. Also conditionally convert upper
833 case path name components to lower case. */
836 normalize_filename (fp
, path_sep
)
843 /* Always lower-case drive letters a-z, even if the filesystem
844 preserves case in filenames.
845 This is so filenames can be compared by string comparison
846 functions that are case-sensitive. Even case-preserving filesystems
847 do not distinguish case in drive letters. */
848 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
854 if (NILP (Vw32_downcase_file_names
))
858 if (*fp
== '/' || *fp
== '\\')
865 sep
= path_sep
; /* convert to this path separator */
866 elem
= fp
; /* start of current path element */
869 if (*fp
>= 'a' && *fp
<= 'z')
870 elem
= 0; /* don't convert this element */
872 if (*fp
== 0 || *fp
== ':')
874 sep
= *fp
; /* restore current separator (or 0) */
875 *fp
= '/'; /* after conversion of this element */
878 if (*fp
== '/' || *fp
== '\\')
880 if (elem
&& elem
!= fp
)
882 *fp
= 0; /* temporary end of string */
883 _strlwr (elem
); /* while we convert to lower case */
885 *fp
= sep
; /* convert (or restore) path separator */
886 elem
= fp
+ 1; /* next element starts after separator */
892 /* Destructively turn backslashes into slashes. */
894 dostounix_filename (p
)
897 normalize_filename (p
, '/');
900 /* Destructively turn slashes into backslashes. */
902 unixtodos_filename (p
)
905 normalize_filename (p
, '\\');
908 /* Remove all CR's that are followed by a LF.
909 (From msdos.c...probably should figure out a way to share it,
910 although this code isn't going to ever change.) */
914 register unsigned char *buf
;
916 unsigned char *np
= buf
;
917 unsigned char *startp
= buf
;
918 unsigned char *endp
= buf
+ n
;
922 while (buf
< endp
- 1)
926 if (*(++buf
) != 0x0a)
937 /* Parse the root part of file name, if present. Return length and
938 optionally store pointer to char after root. */
940 parse_root (char * name
, char ** pPath
)
947 /* find the root name of the volume if given */
948 if (isalpha (name
[0]) && name
[1] == ':')
950 /* skip past drive specifier */
952 if (IS_DIRECTORY_SEP (name
[0]))
955 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
961 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
966 if (IS_DIRECTORY_SEP (name
[0]))
976 /* Get long base name for name; name is assumed to be absolute. */
978 get_long_basename (char * name
, char * buf
, int size
)
980 WIN32_FIND_DATA find_data
;
984 /* must be valid filename, no wild cards or other invalid characters */
985 if (_mbspbrk (name
, "*?|<>\""))
988 dir_handle
= FindFirstFile (name
, &find_data
);
989 if (dir_handle
!= INVALID_HANDLE_VALUE
)
991 if ((len
= strlen (find_data
.cFileName
)) < size
)
992 memcpy (buf
, find_data
.cFileName
, len
+ 1);
995 FindClose (dir_handle
);
1000 /* Get long name for file, if possible (assumed to be absolute). */
1002 w32_get_long_filename (char * name
, char * buf
, int size
)
1007 char full
[ MAX_PATH
];
1010 len
= strlen (name
);
1011 if (len
>= MAX_PATH
)
1014 /* Use local copy for destructive modification. */
1015 memcpy (full
, name
, len
+1);
1016 unixtodos_filename (full
);
1018 /* Copy root part verbatim. */
1019 len
= parse_root (full
, &p
);
1020 memcpy (o
, full
, len
);
1025 while (p
!= NULL
&& *p
)
1028 p
= strchr (q
, '\\');
1030 len
= get_long_basename (full
, o
, size
);
1053 is_unc_volume (const char *filename
)
1055 const char *ptr
= filename
;
1057 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1060 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1066 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
1069 sigsetmask (int signal_mask
)
1087 sigunblock (int sig
)
1093 setpgrp (int pid
, int gid
)
1104 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1107 w32_get_resource (key
, lpdwtype
)
1112 HKEY hrootkey
= NULL
;
1115 /* Check both the current user and the local machine to see if
1116 we have any resources. */
1118 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1122 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1123 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
1124 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1126 RegCloseKey (hrootkey
);
1130 if (lpvalue
) xfree (lpvalue
);
1132 RegCloseKey (hrootkey
);
1135 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1139 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1140 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
1141 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1143 RegCloseKey (hrootkey
);
1147 if (lpvalue
) xfree (lpvalue
);
1149 RegCloseKey (hrootkey
);
1155 char *get_emacs_configuration (void);
1156 extern Lisp_Object Vsystem_configuration
;
1159 init_environment (char ** argv
)
1161 static const char * const tempdirs
[] = {
1162 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1167 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1169 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1170 temporary files and assume "/tmp" if $TMPDIR is unset, which
1171 will break on DOS/Windows. Refuse to work if we cannot find
1172 a directory, not even "c:/", usable for that purpose. */
1173 for (i
= 0; i
< imax
; i
++)
1175 const char *tmp
= tempdirs
[i
];
1178 tmp
= getenv (tmp
+ 1);
1179 /* Note that `access' can lie to us if the directory resides on a
1180 read-only filesystem, like CD-ROM or a write-protected floppy.
1181 The only way to be really sure is to actually create a file and
1182 see if it succeeds. But I think that's too much to ask. */
1183 if (tmp
&& _access (tmp
, D_OK
) == 0)
1185 char * var
= alloca (strlen (tmp
) + 8);
1186 sprintf (var
, "TMPDIR=%s", tmp
);
1187 _putenv (strdup (var
));
1194 Fcons (build_string ("no usable temporary directories found!!"),
1196 "While setting TMPDIR: ");
1198 /* Check for environment variables and use registry settings if they
1199 don't exist. Fallback on default values where applicable. */
1204 char locale_name
[32];
1205 struct stat ignored
;
1206 char default_home
[MAX_PATH
];
1208 static const struct env_entry
1215 {"PRELOAD_WINSOCK", NULL
},
1216 {"emacs_dir", "C:/emacs"},
1217 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/../site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
1218 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1219 {"EMACSDATA", "%emacs_dir%/etc"},
1220 {"EMACSPATH", "%emacs_dir%/bin"},
1221 /* We no longer set INFOPATH because Info-default-directory-list
1223 /* {"INFOPATH", "%emacs_dir%/info"}, */
1224 {"EMACSDOC", "%emacs_dir%/etc"},
1229 #define N_ENV_VARS sizeof(dflt_envvars)/sizeof(dflt_envvars[0])
1231 /* We need to copy dflt_envvars[] and work on the copy because we
1232 don't want the dumped Emacs to inherit the values of
1233 environment variables we saw during dumping (which could be on
1234 a different system). The defaults above must be left intact. */
1235 struct env_entry env_vars
[N_ENV_VARS
];
1237 for (i
= 0; i
< N_ENV_VARS
; i
++)
1238 env_vars
[i
] = dflt_envvars
[i
];
1240 /* For backwards compatibility, check if a .emacs file exists in C:/
1241 If not, then we can try to default to the appdata directory under the
1242 user's profile, which is more likely to be writable. */
1243 if (stat ("C:/.emacs", &ignored
) < 0)
1245 HRESULT profile_result
;
1246 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1247 of Windows 95 and NT4 that have not been updated to include
1248 MSIE 5. Also we don't link with shell32.dll by default. */
1249 HMODULE shell32_dll
;
1250 ShGetFolderPath_fn get_folder_path
;
1251 shell32_dll
= GetModuleHandle ("shell32.dll");
1252 get_folder_path
= (ShGetFolderPath_fn
)
1253 GetProcAddress (shell32_dll
, "SHGetFolderPathA");
1255 if (get_folder_path
!= NULL
)
1257 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
1260 /* If we can't get the appdata dir, revert to old behaviour. */
1261 if (profile_result
== S_OK
)
1262 env_vars
[0].def_value
= default_home
;
1265 /* Unload shell32.dll, it is not needed anymore. */
1266 FreeLibrary (shell32_dll
);
1269 /* Get default locale info and use it for LANG. */
1270 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
1271 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1272 locale_name
, sizeof (locale_name
)))
1274 for (i
= 0; i
< N_ENV_VARS
; i
++)
1276 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
1278 env_vars
[i
].def_value
= locale_name
;
1284 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1286 /* Treat emacs_dir specially: set it unconditionally based on our
1287 location, if it appears that we are running from the bin subdir
1288 of a standard installation. */
1291 char modname
[MAX_PATH
];
1293 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1295 if ((p
= strrchr (modname
, '\\')) == NULL
)
1299 if ((p
= strrchr (modname
, '\\')) && stricmp (p
, "\\bin") == 0)
1301 char buf
[SET_ENV_BUF_SIZE
];
1304 for (p
= modname
; *p
; p
++)
1305 if (*p
== '\\') *p
= '/';
1307 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
1308 _putenv (strdup (buf
));
1310 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1312 /* FIXME: should use substring of get_emacs_configuration ().
1313 But I don't think the Windows build supports alpha, mips etc
1314 anymore, so have taken the easy option for now. */
1315 else if (p
&& stricmp (p
, "\\i386") == 0)
1318 p
= strrchr (modname
, '\\');
1322 p
= strrchr (modname
, '\\');
1323 if (p
&& stricmp (p
, "\\src") == 0)
1325 char buf
[SET_ENV_BUF_SIZE
];
1328 for (p
= modname
; *p
; p
++)
1329 if (*p
== '\\') *p
= '/';
1331 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
1332 _putenv (strdup (buf
));
1338 for (i
= 0; i
< N_ENV_VARS
; i
++)
1340 if (!getenv (env_vars
[i
].name
))
1344 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
1345 /* Also ignore empty environment variables. */
1348 if (lpval
) xfree (lpval
);
1349 lpval
= env_vars
[i
].def_value
;
1350 dwType
= REG_EXPAND_SZ
;
1356 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
1358 if (dwType
== REG_EXPAND_SZ
)
1359 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof(buf1
));
1360 else if (dwType
== REG_SZ
)
1361 strcpy (buf1
, lpval
);
1362 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
1364 _snprintf (buf2
, sizeof(buf2
)-1, "%s=%s", env_vars
[i
].name
,
1366 _putenv (strdup (buf2
));
1376 /* Rebuild system configuration to reflect invoking system. */
1377 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
1379 /* Another special case: on NT, the PATH variable is actually named
1380 "Path" although cmd.exe (perhaps NT itself) arranges for
1381 environment variable lookup and setting to be case insensitive.
1382 However, Emacs assumes a fully case sensitive environment, so we
1383 need to change "Path" to "PATH" to match the expectations of
1384 various elisp packages. We do this by the sneaky method of
1385 modifying the string in the C runtime environ entry.
1387 The same applies to COMSPEC. */
1391 for (envp
= environ
; *envp
; envp
++)
1392 if (_strnicmp (*envp
, "PATH=", 5) == 0)
1393 memcpy (*envp
, "PATH=", 5);
1394 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
1395 memcpy (*envp
, "COMSPEC=", 8);
1398 /* Remember the initial working directory for getwd, then make the
1399 real wd be the location of emacs.exe to avoid conflicts when
1400 renaming or deleting directories. (We also don't call chdir when
1401 running subprocesses for the same reason.) */
1402 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
1407 static char modname
[MAX_PATH
];
1409 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1411 if ((p
= strrchr (modname
, '\\')) == NULL
)
1415 SetCurrentDirectory (modname
);
1417 /* Ensure argv[0] has the full path to Emacs. */
1422 /* Determine if there is a middle mouse button, to allow parse_button
1423 to decide whether right mouse events should be mouse-2 or
1425 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
1431 emacs_root_dir (void)
1433 static char root_dir
[FILENAME_MAX
];
1436 p
= getenv ("emacs_dir");
1439 strcpy (root_dir
, p
);
1440 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
1441 dostounix_filename (root_dir
);
1445 /* We don't have scripts to automatically determine the system configuration
1446 for Emacs before it's compiled, and we don't want to have to make the
1447 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1451 get_emacs_configuration (void)
1453 char *arch
, *oem
, *os
;
1455 static char configuration_buffer
[32];
1457 /* Determine the processor type. */
1458 switch (get_processor_type ())
1461 #ifdef PROCESSOR_INTEL_386
1462 case PROCESSOR_INTEL_386
:
1463 case PROCESSOR_INTEL_486
:
1464 case PROCESSOR_INTEL_PENTIUM
:
1469 #ifdef PROCESSOR_MIPS_R2000
1470 case PROCESSOR_MIPS_R2000
:
1471 case PROCESSOR_MIPS_R3000
:
1472 case PROCESSOR_MIPS_R4000
:
1477 #ifdef PROCESSOR_ALPHA_21064
1478 case PROCESSOR_ALPHA_21064
:
1488 /* Use the OEM field to reflect the compiler/library combination. */
1490 #define COMPILER_NAME "msvc"
1493 #define COMPILER_NAME "mingw"
1495 #define COMPILER_NAME "unknown"
1498 oem
= COMPILER_NAME
;
1500 switch (osinfo_cache
.dwPlatformId
) {
1501 case VER_PLATFORM_WIN32_NT
:
1503 build_num
= osinfo_cache
.dwBuildNumber
;
1505 case VER_PLATFORM_WIN32_WINDOWS
:
1506 if (osinfo_cache
.dwMinorVersion
== 0) {
1511 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1513 case VER_PLATFORM_WIN32s
:
1514 /* Not supported, should not happen. */
1516 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1524 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
1525 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
1526 get_w32_major_version (), get_w32_minor_version (), build_num
);
1528 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
1531 return configuration_buffer
;
1535 get_emacs_configuration_options (void)
1537 static char options_buffer
[256];
1539 /* Work out the effective configure options for this build. */
1541 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1544 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1546 #define COMPILER_VERSION ""
1550 sprintf (options_buffer
, COMPILER_VERSION
);
1552 strcat (options_buffer
, " --no-opt");
1555 strcat (options_buffer
, " --cflags");
1556 strcat (options_buffer
, USER_CFLAGS
);
1559 strcat (options_buffer
, " --ldflags");
1560 strcat (options_buffer
, USER_LDFLAGS
);
1562 return options_buffer
;
1566 #include <sys/timeb.h>
1568 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1570 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
1575 tv
->tv_sec
= tb
.time
;
1576 tv
->tv_usec
= tb
.millitm
* 1000L;
1579 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
1580 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
1584 /* ------------------------------------------------------------------------- */
1585 /* IO support and wrapper functions for W32 API. */
1586 /* ------------------------------------------------------------------------- */
1588 /* Place a wrapper around the MSVC version of ctime. It returns NULL
1589 on network directories, so we handle that case here.
1590 (Ulrich Leodolter, 1/11/95). */
1592 sys_ctime (const time_t *t
)
1594 char *str
= (char *) ctime (t
);
1595 return (str
? str
: "Sun Jan 01 00:00:00 1970");
1598 /* Emulate sleep...we could have done this with a define, but that
1599 would necessitate including windows.h in the files that used it.
1600 This is much easier. */
1602 sys_sleep (int seconds
)
1604 Sleep (seconds
* 1000);
1607 /* Internal MSVC functions for low-level descriptor munging */
1608 extern int __cdecl
_set_osfhnd (int fd
, long h
);
1609 extern int __cdecl
_free_osfhnd (int fd
);
1611 /* parallel array of private info on file handles */
1612 filedesc fd_info
[ MAXDESC
];
1614 typedef struct volume_info_data
{
1615 struct volume_info_data
* next
;
1617 /* time when info was obtained */
1620 /* actual volume info */
1629 /* Global referenced by various functions. */
1630 static volume_info_data volume_info
;
1632 /* Vector to indicate which drives are local and fixed (for which cached
1633 data never expires). */
1634 static BOOL fixed_drives
[26];
1636 /* Consider cached volume information to be stale if older than 10s,
1637 at least for non-local drives. Info for fixed drives is never stale. */
1638 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
1639 #define VOLINFO_STILL_VALID( root_dir, info ) \
1640 ( ( isalpha (root_dir[0]) && \
1641 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
1642 || GetTickCount () - info->timestamp < 10000 )
1644 /* Cache support functions. */
1646 /* Simple linked list with linear search is sufficient. */
1647 static volume_info_data
*volume_cache
= NULL
;
1649 static volume_info_data
*
1650 lookup_volume_info (char * root_dir
)
1652 volume_info_data
* info
;
1654 for (info
= volume_cache
; info
; info
= info
->next
)
1655 if (stricmp (info
->root_dir
, root_dir
) == 0)
1661 add_volume_info (char * root_dir
, volume_info_data
* info
)
1663 info
->root_dir
= xstrdup (root_dir
);
1664 info
->next
= volume_cache
;
1665 volume_cache
= info
;
1669 /* Wrapper for GetVolumeInformation, which uses caching to avoid
1670 performance penalty (~2ms on 486 for local drives, 7.5ms for local
1671 cdrom drive, ~5-10ms or more for remote drives on LAN). */
1673 GetCachedVolumeInformation (char * root_dir
)
1675 volume_info_data
* info
;
1676 char default_root
[ MAX_PATH
];
1678 /* NULL for root_dir means use root from current directory. */
1679 if (root_dir
== NULL
)
1681 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
1683 parse_root (default_root
, &root_dir
);
1685 root_dir
= default_root
;
1688 /* Local fixed drives can be cached permanently. Removable drives
1689 cannot be cached permanently, since the volume name and serial
1690 number (if nothing else) can change. Remote drives should be
1691 treated as if they are removable, since there is no sure way to
1692 tell whether they are or not. Also, the UNC association of drive
1693 letters mapped to remote volumes can be changed at any time (even
1694 by other processes) without notice.
1696 As a compromise, so we can benefit from caching info for remote
1697 volumes, we use a simple expiry mechanism to invalidate cache
1698 entries that are more than ten seconds old. */
1701 /* No point doing this, because WNetGetConnection is even slower than
1702 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
1703 GetDriveType is about the only call of this type which does not
1704 involve network access, and so is extremely quick). */
1706 /* Map drive letter to UNC if remote. */
1707 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
1709 char remote_name
[ 256 ];
1710 char drive
[3] = { root_dir
[0], ':' };
1712 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
1714 /* do something */ ;
1718 info
= lookup_volume_info (root_dir
);
1720 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
1728 /* Info is not cached, or is stale. */
1729 if (!GetVolumeInformation (root_dir
,
1730 name
, sizeof (name
),
1734 type
, sizeof (type
)))
1737 /* Cache the volume information for future use, overwriting existing
1738 entry if present. */
1741 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
1742 add_volume_info (root_dir
, info
);
1750 info
->name
= xstrdup (name
);
1751 info
->serialnum
= serialnum
;
1752 info
->maxcomp
= maxcomp
;
1753 info
->flags
= flags
;
1754 info
->type
= xstrdup (type
);
1755 info
->timestamp
= GetTickCount ();
1761 /* Get information on the volume where name is held; set path pointer to
1762 start of pathname in name (past UNC header\volume header if present). */
1764 get_volume_info (const char * name
, const char ** pPath
)
1766 char temp
[MAX_PATH
];
1767 char *rootname
= NULL
; /* default to current volume */
1768 volume_info_data
* info
;
1773 /* find the root name of the volume if given */
1774 if (isalpha (name
[0]) && name
[1] == ':')
1782 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1789 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1802 info
= GetCachedVolumeInformation (rootname
);
1805 /* Set global referenced by other functions. */
1806 volume_info
= *info
;
1812 /* Determine if volume is FAT format (ie. only supports short 8.3
1813 names); also set path pointer to start of pathname in name. */
1815 is_fat_volume (const char * name
, const char ** pPath
)
1817 if (get_volume_info (name
, pPath
))
1818 return (volume_info
.maxcomp
== 12);
1822 /* Map filename to a valid 8.3 name if necessary. */
1824 map_w32_filename (const char * name
, const char ** pPath
)
1826 static char shortname
[MAX_PATH
];
1827 char * str
= shortname
;
1830 const char * save_name
= name
;
1832 if (strlen (name
) >= MAX_PATH
)
1834 /* Return a filename which will cause callers to fail. */
1835 strcpy (shortname
, "?");
1839 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
1841 register int left
= 8; /* maximum number of chars in part */
1842 register int extn
= 0; /* extension added? */
1843 register int dots
= 2; /* maximum number of dots allowed */
1846 *str
++ = *name
++; /* skip past UNC header */
1848 while ((c
= *name
++))
1855 extn
= 0; /* reset extension flags */
1856 dots
= 2; /* max 2 dots */
1857 left
= 8; /* max length 8 for main part */
1861 extn
= 0; /* reset extension flags */
1862 dots
= 2; /* max 2 dots */
1863 left
= 8; /* max length 8 for main part */
1868 /* Convert path components of the form .xxx to _xxx,
1869 but leave . and .. as they are. This allows .emacs
1870 to be read as _emacs, for example. */
1874 IS_DIRECTORY_SEP (*name
))
1889 extn
= 1; /* we've got an extension */
1890 left
= 3; /* 3 chars in extension */
1894 /* any embedded dots after the first are converted to _ */
1899 case '#': /* don't lose these, they're important */
1901 str
[-1] = c
; /* replace last character of part */
1906 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1908 dots
= 0; /* started a path component */
1917 strcpy (shortname
, name
);
1918 unixtodos_filename (shortname
);
1922 *pPath
= shortname
+ (path
- save_name
);
1928 is_exec (const char * name
)
1930 char * p
= strrchr (name
, '.');
1933 && (stricmp (p
, ".exe") == 0 ||
1934 stricmp (p
, ".com") == 0 ||
1935 stricmp (p
, ".bat") == 0 ||
1936 stricmp (p
, ".cmd") == 0));
1939 /* Emulate the Unix directory procedures opendir, closedir,
1940 and readdir. We can't use the procedures supplied in sysdep.c,
1941 so we provide them here. */
1943 struct direct dir_static
; /* simulated directory contents */
1944 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1945 static int dir_is_fat
;
1946 static char dir_pathname
[MAXPATHLEN
+1];
1947 static WIN32_FIND_DATA dir_find_data
;
1949 /* Support shares on a network resource as subdirectories of a read-only
1951 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1952 HANDLE
open_unc_volume (const char *);
1953 char *read_unc_volume (HANDLE
, char *, int);
1954 void close_unc_volume (HANDLE
);
1957 opendir (char *filename
)
1961 /* Opening is done by FindFirstFile. However, a read is inherent to
1962 this operation, so we defer the open until read time. */
1964 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1966 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1969 if (is_unc_volume (filename
))
1971 wnet_enum_handle
= open_unc_volume (filename
);
1972 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
1976 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1983 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1984 dir_pathname
[MAXPATHLEN
] = '\0';
1985 dir_is_fat
= is_fat_volume (filename
, NULL
);
1991 closedir (DIR *dirp
)
1993 /* If we have a find-handle open, close it. */
1994 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1996 FindClose (dir_find_handle
);
1997 dir_find_handle
= INVALID_HANDLE_VALUE
;
1999 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2001 close_unc_volume (wnet_enum_handle
);
2002 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2004 xfree ((char *) dirp
);
2010 int downcase
= !NILP (Vw32_downcase_file_names
);
2012 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2014 if (!read_unc_volume (wnet_enum_handle
,
2015 dir_find_data
.cFileName
,
2019 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2020 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2022 char filename
[MAXNAMLEN
+ 3];
2025 strcpy (filename
, dir_pathname
);
2026 ln
= strlen (filename
) - 1;
2027 if (!IS_DIRECTORY_SEP (filename
[ln
]))
2028 strcat (filename
, "\\");
2029 strcat (filename
, "*");
2031 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
2033 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2038 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
2042 /* Emacs never uses this value, so don't bother making it match
2043 value returned by stat(). */
2044 dir_static
.d_ino
= 1;
2046 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2048 /* If the file name in cFileName[] includes `?' characters, it means
2049 the original file name used characters that cannot be represented
2050 by the current ANSI codepage. To avoid total lossage, retrieve
2051 the short 8+3 alias of the long file name. */
2052 if (_mbspbrk (dir_static
.d_name
, "?"))
2054 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2055 downcase
= 1; /* 8+3 aliases are returned in all caps */
2057 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2058 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
2059 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
2061 /* If the file name in cFileName[] includes `?' characters, it means
2062 the original file name used characters that cannot be represented
2063 by the current ANSI codepage. To avoid total lossage, retrieve
2064 the short 8+3 alias of the long file name. */
2065 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
2067 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2068 /* 8+3 aliases are returned in all caps, which could break
2069 various alists that look at filenames' extensions. */
2073 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2074 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2076 _strlwr (dir_static
.d_name
);
2080 for (p
= dir_static
.d_name
; *p
; p
++)
2081 if (*p
>= 'a' && *p
<= 'z')
2084 _strlwr (dir_static
.d_name
);
2091 open_unc_volume (const char *path
)
2097 nr
.dwScope
= RESOURCE_GLOBALNET
;
2098 nr
.dwType
= RESOURCETYPE_DISK
;
2099 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
2100 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
2101 nr
.lpLocalName
= NULL
;
2102 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
2103 nr
.lpComment
= NULL
;
2104 nr
.lpProvider
= NULL
;
2106 result
= WNetOpenEnum(RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
2107 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
2109 if (result
== NO_ERROR
)
2112 return INVALID_HANDLE_VALUE
;
2116 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
2120 DWORD bufsize
= 512;
2125 buffer
= alloca (bufsize
);
2126 result
= WNetEnumResource (wnet_enum_handle
, &count
, buffer
, &bufsize
);
2127 if (result
!= NO_ERROR
)
2130 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2131 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
2133 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
2136 strncpy (readbuf
, ptr
, size
);
2141 close_unc_volume (HANDLE henum
)
2143 if (henum
!= INVALID_HANDLE_VALUE
)
2144 WNetCloseEnum (henum
);
2148 unc_volume_file_attributes (const char *path
)
2153 henum
= open_unc_volume (path
);
2154 if (henum
== INVALID_HANDLE_VALUE
)
2157 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
2159 close_unc_volume (henum
);
2164 /* Ensure a network connection is authenticated. */
2166 logon_network_drive (const char *path
)
2168 NETRESOURCE resource
;
2169 char share
[MAX_PATH
];
2173 sprintf (drive
, "%c:\\", path
[0]);
2175 /* Only logon to networked drives. */
2176 if ((!IS_DIRECTORY_SEP (path
[0]) || !IS_DIRECTORY_SEP (path
[1]))
2177 && GetDriveType (drive
) != DRIVE_REMOTE
)
2181 strncpy (share
, path
, MAX_PATH
);
2182 /* Truncate to just server and share name. */
2183 for (i
= 2; i
< MAX_PATH
; i
++)
2185 if (IS_DIRECTORY_SEP (share
[i
]) && ++n_slashes
> 3)
2192 resource
.dwType
= RESOURCETYPE_DISK
;
2193 resource
.lpLocalName
= NULL
;
2194 resource
.lpRemoteName
= share
;
2195 resource
.lpProvider
= NULL
;
2197 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
2200 /* Shadow some MSVC runtime functions to map requests for long filenames
2201 to reasonable short names if necessary. This was originally added to
2202 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2206 sys_access (const char * path
, int mode
)
2210 /* MSVC implementation doesn't recognize D_OK. */
2211 path
= map_w32_filename (path
, NULL
);
2212 if (is_unc_volume (path
))
2214 attributes
= unc_volume_file_attributes (path
);
2215 if (attributes
== -1) {
2220 else if ((attributes
= GetFileAttributes (path
)) == -1)
2222 /* Should try mapping GetLastError to errno; for now just indicate
2223 that path doesn't exist. */
2227 if ((mode
& X_OK
) != 0 && !is_exec (path
))
2232 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
2237 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
2246 sys_chdir (const char * path
)
2248 return _chdir (map_w32_filename (path
, NULL
));
2252 sys_chmod (const char * path
, int mode
)
2254 return _chmod (map_w32_filename (path
, NULL
), mode
);
2258 sys_chown (const char *path
, uid_t owner
, gid_t group
)
2260 if (sys_chmod (path
, S_IREAD
) == -1) /* check if file exists */
2266 sys_creat (const char * path
, int mode
)
2268 return _creat (map_w32_filename (path
, NULL
), mode
);
2272 sys_fopen(const char * path
, const char * mode
)
2276 const char * mode_save
= mode
;
2278 /* Force all file handles to be non-inheritable. This is necessary to
2279 ensure child processes don't unwittingly inherit handles that might
2280 prevent future file access. */
2284 else if (mode
[0] == 'w' || mode
[0] == 'a')
2285 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
2289 /* Only do simplistic option parsing. */
2293 oflag
&= ~(O_RDONLY
| O_WRONLY
);
2296 else if (mode
[0] == 'b')
2301 else if (mode
[0] == 't')
2308 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
2312 return _fdopen (fd
, mode_save
);
2315 /* This only works on NTFS volumes, but is useful to have. */
2317 sys_link (const char * old
, const char * new)
2321 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
2323 if (old
== NULL
|| new == NULL
)
2329 strcpy (oldname
, map_w32_filename (old
, NULL
));
2330 strcpy (newname
, map_w32_filename (new, NULL
));
2332 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
2333 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2334 if (fileh
!= INVALID_HANDLE_VALUE
)
2338 /* Confusingly, the "alternate" stream name field does not apply
2339 when restoring a hard link, and instead contains the actual
2340 stream data for the link (ie. the name of the link to create).
2341 The WIN32_STREAM_ID structure before the cStreamName field is
2342 the stream header, which is then immediately followed by the
2346 WIN32_STREAM_ID wid
;
2347 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
2350 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
2351 data
.wid
.cStreamName
, MAX_PATH
);
2354 LPVOID context
= NULL
;
2357 data
.wid
.dwStreamId
= BACKUP_LINK
;
2358 data
.wid
.dwStreamAttributes
= 0;
2359 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
2360 data
.wid
.Size
.HighPart
= 0;
2361 data
.wid
.dwStreamNameSize
= 0;
2363 if (BackupWrite (fileh
, (LPBYTE
)&data
,
2364 offsetof (WIN32_STREAM_ID
, cStreamName
)
2365 + data
.wid
.Size
.LowPart
,
2366 &wbytes
, FALSE
, FALSE
, &context
)
2367 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
2374 /* Should try mapping GetLastError to errno; for now just
2375 indicate a general error (eg. links not supported). */
2376 errno
= EINVAL
; // perhaps EMLINK?
2380 CloseHandle (fileh
);
2389 sys_mkdir (const char * path
)
2391 return _mkdir (map_w32_filename (path
, NULL
));
2394 /* Because of long name mapping issues, we need to implement this
2395 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2396 a unique name, instead of setting the input template to an empty
2399 Standard algorithm seems to be use pid or tid with a letter on the
2400 front (in place of the 6 X's) and cycle through the letters to find a
2401 unique name. We extend that to allow any reasonable character as the
2402 first of the 6 X's. */
2404 sys_mktemp (char * template)
2408 unsigned uid
= GetCurrentThreadId ();
2409 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2411 if (template == NULL
)
2413 p
= template + strlen (template);
2415 /* replace up to the last 5 X's with uid in decimal */
2416 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
2418 p
[0] = '0' + uid
% 10;
2422 if (i
< 0 && p
[0] == 'X')
2427 int save_errno
= errno
;
2428 p
[0] = first_char
[i
];
2429 if (sys_access (template, 0) < 0)
2435 while (++i
< sizeof (first_char
));
2438 /* Template is badly formed or else we can't generate a unique name,
2439 so return empty string */
2445 sys_open (const char * path
, int oflag
, int mode
)
2447 const char* mpath
= map_w32_filename (path
, NULL
);
2448 /* Try to open file without _O_CREAT, to be able to write to hidden
2449 and system files. Force all file handles to be
2451 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
2454 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
2458 sys_rename (const char * oldname
, const char * newname
)
2461 char temp
[MAX_PATH
];
2463 /* MoveFile on Windows 95 doesn't correctly change the short file name
2464 alias in a number of circumstances (it is not easy to predict when
2465 just by looking at oldname and newname, unfortunately). In these
2466 cases, renaming through a temporary name avoids the problem.
2468 A second problem on Windows 95 is that renaming through a temp name when
2469 newname is uppercase fails (the final long name ends up in
2470 lowercase, although the short alias might be uppercase) UNLESS the
2471 long temp name is not 8.3.
2473 So, on Windows 95 we always rename through a temp name, and we make sure
2474 the temp name has a long extension to ensure correct renaming. */
2476 strcpy (temp
, map_w32_filename (oldname
, NULL
));
2478 if (os_subtype
== OS_WIN95
)
2484 oldname
= map_w32_filename (oldname
, NULL
);
2485 if (o
= strrchr (oldname
, '\\'))
2488 o
= (char *) oldname
;
2490 if (p
= strrchr (temp
, '\\'))
2497 /* Force temp name to require a manufactured 8.3 alias - this
2498 seems to make the second rename work properly. */
2499 sprintf (p
, "_.%s.%u", o
, i
);
2501 result
= rename (oldname
, temp
);
2503 /* This loop must surely terminate! */
2504 while (result
< 0 && errno
== EEXIST
);
2509 /* Emulate Unix behaviour - newname is deleted if it already exists
2510 (at least if it is a file; don't do this for directories).
2512 Since we mustn't do this if we are just changing the case of the
2513 file name (we would end up deleting the file we are trying to
2514 rename!), we let rename detect if the destination file already
2515 exists - that way we avoid the possible pitfalls of trying to
2516 determine ourselves whether two names really refer to the same
2517 file, which is not always possible in the general case. (Consider
2518 all the permutations of shared or subst'd drives, etc.) */
2520 newname
= map_w32_filename (newname
, NULL
);
2521 result
= rename (temp
, newname
);
2525 && _chmod (newname
, 0666) == 0
2526 && _unlink (newname
) == 0)
2527 result
= rename (temp
, newname
);
2533 sys_rmdir (const char * path
)
2535 return _rmdir (map_w32_filename (path
, NULL
));
2539 sys_unlink (const char * path
)
2541 path
= map_w32_filename (path
, NULL
);
2543 /* On Unix, unlink works without write permission. */
2544 _chmod (path
, 0666);
2545 return _unlink (path
);
2548 static FILETIME utc_base_ft
;
2549 static long double utc_base
;
2550 static int init
= 0;
2553 convert_time (FILETIME ft
)
2559 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
2568 st
.wMilliseconds
= 0;
2570 SystemTimeToFileTime (&st
, &utc_base_ft
);
2571 utc_base
= (long double) utc_base_ft
.dwHighDateTime
2572 * 4096.0L * 1024.0L * 1024.0L + utc_base_ft
.dwLowDateTime
;
2576 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
2579 ret
= (long double) ft
.dwHighDateTime
2580 * 4096.0L * 1024.0L * 1024.0L + ft
.dwLowDateTime
;
2582 return (time_t) (ret
* 1e-7L);
2586 convert_from_time_t (time_t time
, FILETIME
* pft
)
2592 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
2601 st
.wMilliseconds
= 0;
2603 SystemTimeToFileTime (&st
, &utc_base_ft
);
2604 utc_base
= (long double) utc_base_ft
.dwHighDateTime
2605 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
2609 /* time in 100ns units since 1-Jan-1601 */
2610 tmp
= (long double) time
* 1e7
+ utc_base
;
2611 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
2612 pft
->dwLowDateTime
= (DWORD
) (tmp
- (4096.0 * 1024 * 1024) * pft
->dwHighDateTime
);
2616 /* No reason to keep this; faking inode values either by hashing or even
2617 using the file index from GetInformationByHandle, is not perfect and
2618 so by default Emacs doesn't use the inode values on Windows.
2619 Instead, we now determine file-truename correctly (except for
2620 possible drive aliasing etc). */
2622 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
2624 hashval (const unsigned char * str
)
2629 h
= (h
<< 4) + *str
++;
2635 /* Return the hash value of the canonical pathname, excluding the
2636 drive/UNC header, to get a hopefully unique inode number. */
2638 generate_inode_val (const char * name
)
2640 char fullname
[ MAX_PATH
];
2644 /* Get the truly canonical filename, if it exists. (Note: this
2645 doesn't resolve aliasing due to subst commands, or recognise hard
2647 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
2650 parse_root (fullname
, &p
);
2651 /* Normal W32 filesystems are still case insensitive. */
2658 static PSECURITY_DESCRIPTOR
2659 get_file_security_desc (const char *fname
)
2661 PSECURITY_DESCRIPTOR psd
= NULL
;
2663 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
2664 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
2666 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
2668 err
= GetLastError ();
2669 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
2673 psd
= xmalloc (sd_len
);
2674 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
2686 unsigned n_subauthorities
;
2688 /* Use the last sub-authority value of the RID, the relative
2689 portion of the SID, as user/group ID. */
2690 n_subauthorities
= *get_sid_sub_authority_count (sid
);
2691 if (n_subauthorities
< 1)
2692 return 0; /* the "World" RID */
2693 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
2700 get_name_and_id (PSECURITY_DESCRIPTOR psd
, const char *fname
,
2701 int *id
, char *nm
, int what
)
2704 char machine
[MAX_COMPUTERNAME_LENGTH
+1];
2706 SID_NAME_USE ignore
;
2708 DWORD name_len
= sizeof (name
);
2710 DWORD domain_len
= sizeof(domain
);
2716 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
2717 else if (what
== GID
)
2718 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
2722 if (!result
|| !is_valid_sid (sid
))
2726 /* If FNAME is a UNC, we need to lookup account on the
2727 specified machine. */
2728 if (IS_DIRECTORY_SEP (fname
[0]) && IS_DIRECTORY_SEP (fname
[1])
2729 && fname
[2] != '\0')
2734 for (s
= fname
+ 2, p
= machine
;
2735 *s
&& !IS_DIRECTORY_SEP (*s
); s
++, p
++)
2741 if (!lookup_account_sid (mp
, sid
, name
, &name_len
,
2742 domain
, &domain_len
, &ignore
)
2743 || name_len
> UNLEN
+1)
2747 *id
= get_rid (sid
);
2755 get_file_owner_and_group (
2756 PSECURITY_DESCRIPTOR psd
,
2760 int dflt_usr
= 0, dflt_grp
= 0;
2769 if (get_name_and_id (psd
, fname
, &st
->st_uid
, st
->st_uname
, UID
))
2771 if (get_name_and_id (psd
, fname
, &st
->st_gid
, st
->st_gname
, GID
))
2774 /* Consider files to belong to current user/group, if we cannot get
2775 more accurate information. */
2778 st
->st_uid
= dflt_passwd
.pw_uid
;
2779 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
2783 st
->st_gid
= dflt_passwd
.pw_gid
;
2784 strcpy (st
->st_gname
, dflt_group
.gr_name
);
2788 /* MSVC stat function can't cope with UNC names and has other bugs, so
2789 replace it with our own. This also allows us to calculate consistent
2790 inode values without hacks in the main Emacs code. */
2792 stat (const char * path
, struct stat
* buf
)
2795 WIN32_FIND_DATA wfd
;
2797 unsigned __int64 fake_inode
;
2800 int rootdir
= FALSE
;
2801 PSECURITY_DESCRIPTOR psd
= NULL
;
2803 if (path
== NULL
|| buf
== NULL
)
2809 name
= (char *) map_w32_filename (path
, &path
);
2810 /* Must be valid filename, no wild cards or other invalid
2811 characters. We use _mbspbrk to support multibyte strings that
2812 might look to strpbrk as if they included literal *, ?, and other
2813 characters mentioned below that are disallowed by Windows
2815 if (_mbspbrk (name
, "*?|<>\""))
2821 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
2822 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
2823 if (IS_DIRECTORY_SEP (r
[0]) && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
2828 /* Remove trailing directory separator, unless name is the root
2829 directory of a drive or UNC volume in which case ensure there
2830 is a trailing separator. */
2831 len
= strlen (name
);
2832 rootdir
= (path
>= name
+ len
- 1
2833 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
2834 name
= strcpy (alloca (len
+ 2), name
);
2836 if (is_unc_volume (name
))
2838 DWORD attrs
= unc_volume_file_attributes (name
);
2843 memset (&wfd
, 0, sizeof (wfd
));
2844 wfd
.dwFileAttributes
= attrs
;
2845 wfd
.ftCreationTime
= utc_base_ft
;
2846 wfd
.ftLastAccessTime
= utc_base_ft
;
2847 wfd
.ftLastWriteTime
= utc_base_ft
;
2848 strcpy (wfd
.cFileName
, name
);
2852 if (!IS_DIRECTORY_SEP (name
[len
-1]))
2853 strcat (name
, "\\");
2854 if (GetDriveType (name
) < 2)
2859 memset (&wfd
, 0, sizeof (wfd
));
2860 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
2861 wfd
.ftCreationTime
= utc_base_ft
;
2862 wfd
.ftLastAccessTime
= utc_base_ft
;
2863 wfd
.ftLastWriteTime
= utc_base_ft
;
2864 strcpy (wfd
.cFileName
, name
);
2868 if (IS_DIRECTORY_SEP (name
[len
-1]))
2871 /* (This is hacky, but helps when doing file completions on
2872 network drives.) Optimize by using information available from
2873 active readdir if possible. */
2874 len
= strlen (dir_pathname
);
2875 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
2877 if (dir_find_handle
!= INVALID_HANDLE_VALUE
2878 && strnicmp (name
, dir_pathname
, len
) == 0
2879 && IS_DIRECTORY_SEP (name
[len
])
2880 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
2882 /* This was the last entry returned by readdir. */
2883 wfd
= dir_find_data
;
2887 logon_network_drive (name
);
2889 fh
= FindFirstFile (name
, &wfd
);
2890 if (fh
== INVALID_HANDLE_VALUE
)
2899 if (!(NILP (Vw32_get_true_file_attributes
)
2900 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) &&
2901 GetDriveType (name
) != DRIVE_FIXED
))
2902 /* No access rights required to get info. */
2903 && (fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
2904 FILE_FLAG_BACKUP_SEMANTICS
, NULL
))
2905 != INVALID_HANDLE_VALUE
)
2907 /* This is more accurate in terms of gettting the correct number
2908 of links, but is quite slow (it is noticeable when Emacs is
2909 making a list of file name completions). */
2910 BY_HANDLE_FILE_INFORMATION info
;
2912 if (GetFileInformationByHandle (fh
, &info
))
2914 buf
->st_nlink
= info
.nNumberOfLinks
;
2915 /* Might as well use file index to fake inode values, but this
2916 is not guaranteed to be unique unless we keep a handle open
2917 all the time (even then there are situations where it is
2918 not unique). Reputedly, there are at most 48 bits of info
2919 (on NTFS, presumably less on FAT). */
2920 fake_inode
= info
.nFileIndexHigh
;
2922 fake_inode
+= info
.nFileIndexLow
;
2930 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2932 buf
->st_mode
= S_IFDIR
;
2936 switch (GetFileType (fh
))
2938 case FILE_TYPE_DISK
:
2939 buf
->st_mode
= S_IFREG
;
2941 case FILE_TYPE_PIPE
:
2942 buf
->st_mode
= S_IFIFO
;
2944 case FILE_TYPE_CHAR
:
2945 case FILE_TYPE_UNKNOWN
:
2947 buf
->st_mode
= S_IFCHR
;
2951 psd
= get_file_security_desc (name
);
2952 get_file_owner_and_group (psd
, name
, buf
);
2956 /* Don't bother to make this information more accurate. */
2957 buf
->st_mode
= (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ?
2962 get_file_owner_and_group (NULL
, name
, buf
);
2968 /* Not sure if there is any point in this. */
2969 if (!NILP (Vw32_generate_fake_inodes
))
2970 fake_inode
= generate_inode_val (name
);
2971 else if (fake_inode
== 0)
2973 /* For want of something better, try to make everything unique. */
2974 static DWORD gen_num
= 0;
2975 fake_inode
= ++gen_num
;
2979 /* MSVC defines _ino_t to be short; other libc's might not. */
2980 if (sizeof (buf
->st_ino
) == 2)
2981 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
2983 buf
->st_ino
= fake_inode
;
2985 /* volume_info is set indirectly by map_w32_filename */
2986 buf
->st_dev
= volume_info
.serialnum
;
2987 buf
->st_rdev
= volume_info
.serialnum
;
2990 buf
->st_size
= wfd
.nFileSizeHigh
;
2991 buf
->st_size
<<= 32;
2992 buf
->st_size
+= wfd
.nFileSizeLow
;
2994 /* Convert timestamps to Unix format. */
2995 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
2996 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
2997 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
2998 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
2999 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3001 /* determine rwx permissions */
3002 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3003 permission
= S_IREAD
;
3005 permission
= S_IREAD
| S_IWRITE
;
3007 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3008 permission
|= S_IEXEC
;
3009 else if (is_exec (name
))
3010 permission
|= S_IEXEC
;
3012 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3017 /* Provide fstat and utime as well as stat for consistent handling of
3020 fstat (int desc
, struct stat
* buf
)
3022 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
3023 BY_HANDLE_FILE_INFORMATION info
;
3024 unsigned __int64 fake_inode
;
3027 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
3029 case FILE_TYPE_DISK
:
3030 buf
->st_mode
= S_IFREG
;
3031 if (!GetFileInformationByHandle (fh
, &info
))
3037 case FILE_TYPE_PIPE
:
3038 buf
->st_mode
= S_IFIFO
;
3040 case FILE_TYPE_CHAR
:
3041 case FILE_TYPE_UNKNOWN
:
3043 buf
->st_mode
= S_IFCHR
;
3045 memset (&info
, 0, sizeof (info
));
3046 info
.dwFileAttributes
= 0;
3047 info
.ftCreationTime
= utc_base_ft
;
3048 info
.ftLastAccessTime
= utc_base_ft
;
3049 info
.ftLastWriteTime
= utc_base_ft
;
3052 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3053 buf
->st_mode
= S_IFDIR
;
3055 buf
->st_nlink
= info
.nNumberOfLinks
;
3056 /* Might as well use file index to fake inode values, but this
3057 is not guaranteed to be unique unless we keep a handle open
3058 all the time (even then there are situations where it is
3059 not unique). Reputedly, there are at most 48 bits of info
3060 (on NTFS, presumably less on FAT). */
3061 fake_inode
= info
.nFileIndexHigh
;
3063 fake_inode
+= info
.nFileIndexLow
;
3065 /* MSVC defines _ino_t to be short; other libc's might not. */
3066 if (sizeof (buf
->st_ino
) == 2)
3067 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
3069 buf
->st_ino
= fake_inode
;
3071 /* Consider files to belong to current user.
3072 FIXME: this should use GetSecurityInfo API, but it is only
3073 available for _WIN32_WINNT >= 0x501. */
3074 buf
->st_uid
= dflt_passwd
.pw_uid
;
3075 buf
->st_gid
= dflt_passwd
.pw_gid
;
3076 strcpy (buf
->st_uname
, dflt_passwd
.pw_name
);
3077 strcpy (buf
->st_gname
, dflt_group
.gr_name
);
3079 buf
->st_dev
= info
.dwVolumeSerialNumber
;
3080 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
3082 buf
->st_size
= info
.nFileSizeHigh
;
3083 buf
->st_size
<<= 32;
3084 buf
->st_size
+= info
.nFileSizeLow
;
3086 /* Convert timestamps to Unix format. */
3087 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
3088 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
3089 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3090 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
3091 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3093 /* determine rwx permissions */
3094 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3095 permission
= S_IREAD
;
3097 permission
= S_IREAD
| S_IWRITE
;
3099 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3100 permission
|= S_IEXEC
;
3103 #if 0 /* no way of knowing the filename */
3104 char * p
= strrchr (name
, '.');
3106 (stricmp (p
, ".exe") == 0 ||
3107 stricmp (p
, ".com") == 0 ||
3108 stricmp (p
, ".bat") == 0 ||
3109 stricmp (p
, ".cmd") == 0))
3110 permission
|= S_IEXEC
;
3114 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3120 utime (const char *name
, struct utimbuf
*times
)
3122 struct utimbuf deftime
;
3129 deftime
.modtime
= deftime
.actime
= time (NULL
);
3133 /* Need write access to set times. */
3134 fh
= CreateFile (name
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
3135 0, OPEN_EXISTING
, 0, NULL
);
3138 convert_from_time_t (times
->actime
, &atime
);
3139 convert_from_time_t (times
->modtime
, &mtime
);
3140 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
3158 /* Wrappers for winsock functions to map between our file descriptors
3159 and winsock's handles; also set h_errno for convenience.
3161 To allow Emacs to run on systems which don't have winsock support
3162 installed, we dynamically link to winsock on startup if present, and
3163 otherwise provide the minimum necessary functionality
3164 (eg. gethostname). */
3166 /* function pointers for relevant socket functions */
3167 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
3168 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
3169 int (PASCAL
*pfn_WSAGetLastError
) (void);
3170 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
3171 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
3172 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
3173 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
3174 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
3175 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
3176 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
3177 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
3178 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
3179 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
3180 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
3181 int (PASCAL
*pfn_WSACleanup
) (void);
3183 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
3184 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
3185 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
3186 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
3187 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
3188 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
3189 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
3190 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
3191 const char * optval
, int optlen
);
3192 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
3193 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
3195 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
3196 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
3197 struct sockaddr
* from
, int * fromlen
);
3198 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
3199 const struct sockaddr
* to
, int tolen
);
3201 /* SetHandleInformation is only needed to make sockets non-inheritable. */
3202 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
3203 #ifndef HANDLE_FLAG_INHERIT
3204 #define HANDLE_FLAG_INHERIT 1
3208 static int winsock_inuse
;
3213 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
3215 /* Not sure what would cause WSAENETDOWN, or even if it can happen
3216 after WSAStartup returns successfully, but it seems reasonable
3217 to allow unloading winsock anyway in that case. */
3218 if (pfn_WSACleanup () == 0 ||
3219 pfn_WSAGetLastError () == WSAENETDOWN
)
3221 if (FreeLibrary (winsock_lib
))
3230 init_winsock (int load_now
)
3232 WSADATA winsockData
;
3234 if (winsock_lib
!= NULL
)
3237 pfn_SetHandleInformation
= NULL
;
3238 pfn_SetHandleInformation
3239 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
3240 "SetHandleInformation");
3242 winsock_lib
= LoadLibrary ("Ws2_32.dll");
3244 if (winsock_lib
!= NULL
)
3246 /* dynamically link to socket functions */
3248 #define LOAD_PROC(fn) \
3249 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
3252 LOAD_PROC( WSAStartup
);
3253 LOAD_PROC( WSASetLastError
);
3254 LOAD_PROC( WSAGetLastError
);
3255 LOAD_PROC( WSAEventSelect
);
3256 LOAD_PROC( WSACreateEvent
);
3257 LOAD_PROC( WSACloseEvent
);
3258 LOAD_PROC( socket
);
3260 LOAD_PROC( connect
);
3261 LOAD_PROC( ioctlsocket
);
3264 LOAD_PROC( closesocket
);
3265 LOAD_PROC( shutdown
);
3268 LOAD_PROC( inet_addr
);
3269 LOAD_PROC( gethostname
);
3270 LOAD_PROC( gethostbyname
);
3271 LOAD_PROC( getservbyname
);
3272 LOAD_PROC( getpeername
);
3273 LOAD_PROC( WSACleanup
);
3274 LOAD_PROC( setsockopt
);
3275 LOAD_PROC( listen
);
3276 LOAD_PROC( getsockname
);
3277 LOAD_PROC( accept
);
3278 LOAD_PROC( recvfrom
);
3279 LOAD_PROC( sendto
);
3282 /* specify version 1.1 of winsock */
3283 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
3285 if (winsockData
.wVersion
!= 0x101)
3290 /* Report that winsock exists and is usable, but leave
3291 socket functions disabled. I am assuming that calling
3292 WSAStartup does not require any network interaction,
3293 and in particular does not cause or require a dial-up
3294 connection to be established. */
3297 FreeLibrary (winsock_lib
);
3305 FreeLibrary (winsock_lib
);
3315 /* function to set h_errno for compatability; map winsock error codes to
3316 normal system codes where they overlap (non-overlapping definitions
3317 are already in <sys/socket.h> */
3321 if (winsock_lib
== NULL
)
3324 h_errno
= pfn_WSAGetLastError ();
3328 case WSAEACCES
: h_errno
= EACCES
; break;
3329 case WSAEBADF
: h_errno
= EBADF
; break;
3330 case WSAEFAULT
: h_errno
= EFAULT
; break;
3331 case WSAEINTR
: h_errno
= EINTR
; break;
3332 case WSAEINVAL
: h_errno
= EINVAL
; break;
3333 case WSAEMFILE
: h_errno
= EMFILE
; break;
3334 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
3335 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
3343 if (h_errno
== 0 && winsock_lib
!= NULL
)
3344 pfn_WSASetLastError (0);
3347 /* Extend strerror to handle the winsock-specific error codes. */
3351 } _wsa_errlist
[] = {
3352 WSAEINTR
, "Interrupted function call",
3353 WSAEBADF
, "Bad file descriptor",
3354 WSAEACCES
, "Permission denied",
3355 WSAEFAULT
, "Bad address",
3356 WSAEINVAL
, "Invalid argument",
3357 WSAEMFILE
, "Too many open files",
3359 WSAEWOULDBLOCK
, "Resource temporarily unavailable",
3360 WSAEINPROGRESS
, "Operation now in progress",
3361 WSAEALREADY
, "Operation already in progress",
3362 WSAENOTSOCK
, "Socket operation on non-socket",
3363 WSAEDESTADDRREQ
, "Destination address required",
3364 WSAEMSGSIZE
, "Message too long",
3365 WSAEPROTOTYPE
, "Protocol wrong type for socket",
3366 WSAENOPROTOOPT
, "Bad protocol option",
3367 WSAEPROTONOSUPPORT
, "Protocol not supported",
3368 WSAESOCKTNOSUPPORT
, "Socket type not supported",
3369 WSAEOPNOTSUPP
, "Operation not supported",
3370 WSAEPFNOSUPPORT
, "Protocol family not supported",
3371 WSAEAFNOSUPPORT
, "Address family not supported by protocol family",
3372 WSAEADDRINUSE
, "Address already in use",
3373 WSAEADDRNOTAVAIL
, "Cannot assign requested address",
3374 WSAENETDOWN
, "Network is down",
3375 WSAENETUNREACH
, "Network is unreachable",
3376 WSAENETRESET
, "Network dropped connection on reset",
3377 WSAECONNABORTED
, "Software caused connection abort",
3378 WSAECONNRESET
, "Connection reset by peer",
3379 WSAENOBUFS
, "No buffer space available",
3380 WSAEISCONN
, "Socket is already connected",
3381 WSAENOTCONN
, "Socket is not connected",
3382 WSAESHUTDOWN
, "Cannot send after socket shutdown",
3383 WSAETOOMANYREFS
, "Too many references", /* not sure */
3384 WSAETIMEDOUT
, "Connection timed out",
3385 WSAECONNREFUSED
, "Connection refused",
3386 WSAELOOP
, "Network loop", /* not sure */
3387 WSAENAMETOOLONG
, "Name is too long",
3388 WSAEHOSTDOWN
, "Host is down",
3389 WSAEHOSTUNREACH
, "No route to host",
3390 WSAENOTEMPTY
, "Buffer not empty", /* not sure */
3391 WSAEPROCLIM
, "Too many processes",
3392 WSAEUSERS
, "Too many users", /* not sure */
3393 WSAEDQUOT
, "Double quote in host name", /* really not sure */
3394 WSAESTALE
, "Data is stale", /* not sure */
3395 WSAEREMOTE
, "Remote error", /* not sure */
3397 WSASYSNOTREADY
, "Network subsystem is unavailable",
3398 WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range",
3399 WSANOTINITIALISED
, "Winsock not initialized successfully",
3400 WSAEDISCON
, "Graceful shutdown in progress",
3402 WSAENOMORE
, "No more operations allowed", /* not sure */
3403 WSAECANCELLED
, "Operation cancelled", /* not sure */
3404 WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider",
3405 WSAEINVALIDPROVIDER
, "Invalid service provider version number",
3406 WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider",
3407 WSASYSCALLFAILURE
, "System call failure",
3408 WSASERVICE_NOT_FOUND
, "Service not found", /* not sure */
3409 WSATYPE_NOT_FOUND
, "Class type not found",
3410 WSA_E_NO_MORE
, "No more resources available", /* really not sure */
3411 WSA_E_CANCELLED
, "Operation already cancelled", /* really not sure */
3412 WSAEREFUSED
, "Operation refused", /* not sure */
3415 WSAHOST_NOT_FOUND
, "Host not found",
3416 WSATRY_AGAIN
, "Authoritative host not found during name lookup",
3417 WSANO_RECOVERY
, "Non-recoverable error during name lookup",
3418 WSANO_DATA
, "Valid name, no data record of requested type",
3424 sys_strerror(int error_no
)
3427 static char unknown_msg
[40];
3429 if (error_no
>= 0 && error_no
< sys_nerr
)
3430 return sys_errlist
[error_no
];
3432 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
3433 if (_wsa_errlist
[i
].errnum
== error_no
)
3434 return _wsa_errlist
[i
].msg
;
3436 sprintf(unknown_msg
, "Unidentified error: %d", error_no
);
3440 /* [andrewi 3-May-96] I've had conflicting results using both methods,
3441 but I believe the method of keeping the socket handle separate (and
3442 insuring it is not inheritable) is the correct one. */
3444 //#define SOCK_REPLACE_HANDLE
3446 #ifdef SOCK_REPLACE_HANDLE
3447 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
3449 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
3452 int socket_to_fd (SOCKET s
);
3455 sys_socket(int af
, int type
, int protocol
)
3459 if (winsock_lib
== NULL
)
3462 return INVALID_SOCKET
;
3467 /* call the real socket function */
3468 s
= pfn_socket (af
, type
, protocol
);
3470 if (s
!= INVALID_SOCKET
)
3471 return socket_to_fd (s
);
3477 /* Convert a SOCKET to a file descriptor. */
3479 socket_to_fd (SOCKET s
)
3484 /* Although under NT 3.5 _open_osfhandle will accept a socket
3485 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
3486 that does not work under NT 3.1. However, we can get the same
3487 effect by using a backdoor function to replace an existing
3488 descriptor handle with the one we want. */
3490 /* allocate a file descriptor (with appropriate flags) */
3491 fd
= _open ("NUL:", _O_RDWR
);
3494 #ifdef SOCK_REPLACE_HANDLE
3495 /* now replace handle to NUL with our socket handle */
3496 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
3498 _set_osfhnd (fd
, s
);
3499 /* setmode (fd, _O_BINARY); */
3501 /* Make a non-inheritable copy of the socket handle. Note
3502 that it is possible that sockets aren't actually kernel
3503 handles, which appears to be the case on Windows 9x when
3504 the MS Proxy winsock client is installed. */
3506 /* Apparently there is a bug in NT 3.51 with some service
3507 packs, which prevents using DuplicateHandle to make a
3508 socket handle non-inheritable (causes WSACleanup to
3509 hang). The work-around is to use SetHandleInformation
3510 instead if it is available and implemented. */
3511 if (pfn_SetHandleInformation
)
3513 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
3517 HANDLE parent
= GetCurrentProcess ();
3518 HANDLE new_s
= INVALID_HANDLE_VALUE
;
3520 if (DuplicateHandle (parent
,
3526 DUPLICATE_SAME_ACCESS
))
3528 /* It is possible that DuplicateHandle succeeds even
3529 though the socket wasn't really a kernel handle,
3530 because a real handle has the same value. So
3531 test whether the new handle really is a socket. */
3532 long nonblocking
= 0;
3533 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
3535 pfn_closesocket (s
);
3540 CloseHandle (new_s
);
3545 fd_info
[fd
].hnd
= (HANDLE
) s
;
3548 /* set our own internal flags */
3549 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
3555 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3557 /* attach child_process to fd_info */
3558 if (fd_info
[ fd
].cp
!= NULL
)
3560 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
3564 fd_info
[ fd
].cp
= cp
;
3567 winsock_inuse
++; /* count open sockets */
3574 pfn_closesocket (s
);
3581 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
3583 if (winsock_lib
== NULL
)
3586 return SOCKET_ERROR
;
3590 if (fd_info
[s
].flags
& FILE_SOCKET
)
3592 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
3593 if (rc
== SOCKET_ERROR
)
3598 return SOCKET_ERROR
;
3603 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
3605 if (winsock_lib
== NULL
)
3608 return SOCKET_ERROR
;
3612 if (fd_info
[s
].flags
& FILE_SOCKET
)
3614 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
3615 if (rc
== SOCKET_ERROR
)
3620 return SOCKET_ERROR
;
3624 sys_htons (u_short hostshort
)
3626 return (winsock_lib
!= NULL
) ?
3627 pfn_htons (hostshort
) : hostshort
;
3631 sys_ntohs (u_short netshort
)
3633 return (winsock_lib
!= NULL
) ?
3634 pfn_ntohs (netshort
) : netshort
;
3638 sys_inet_addr (const char * cp
)
3640 return (winsock_lib
!= NULL
) ?
3641 pfn_inet_addr (cp
) : INADDR_NONE
;
3645 sys_gethostname (char * name
, int namelen
)
3647 if (winsock_lib
!= NULL
)
3648 return pfn_gethostname (name
, namelen
);
3650 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
3651 return !GetComputerName (name
, (DWORD
*)&namelen
);
3654 return SOCKET_ERROR
;
3658 sys_gethostbyname(const char * name
)
3660 struct hostent
* host
;
3662 if (winsock_lib
== NULL
)
3669 host
= pfn_gethostbyname (name
);
3676 sys_getservbyname(const char * name
, const char * proto
)
3678 struct servent
* serv
;
3680 if (winsock_lib
== NULL
)
3687 serv
= pfn_getservbyname (name
, proto
);
3694 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
3696 if (winsock_lib
== NULL
)
3699 return SOCKET_ERROR
;
3703 if (fd_info
[s
].flags
& FILE_SOCKET
)
3705 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
3706 if (rc
== SOCKET_ERROR
)
3711 return SOCKET_ERROR
;
3716 sys_shutdown (int s
, int how
)
3718 if (winsock_lib
== NULL
)
3721 return SOCKET_ERROR
;
3725 if (fd_info
[s
].flags
& FILE_SOCKET
)
3727 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
3728 if (rc
== SOCKET_ERROR
)
3733 return SOCKET_ERROR
;
3737 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
3739 if (winsock_lib
== NULL
)
3742 return SOCKET_ERROR
;
3746 if (fd_info
[s
].flags
& FILE_SOCKET
)
3748 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
3749 (const char *)optval
, optlen
);
3750 if (rc
== SOCKET_ERROR
)
3755 return SOCKET_ERROR
;
3759 sys_listen (int s
, int backlog
)
3761 if (winsock_lib
== NULL
)
3764 return SOCKET_ERROR
;
3768 if (fd_info
[s
].flags
& FILE_SOCKET
)
3770 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
3771 if (rc
== SOCKET_ERROR
)
3774 fd_info
[s
].flags
|= FILE_LISTEN
;
3778 return SOCKET_ERROR
;
3782 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
3784 if (winsock_lib
== NULL
)
3787 return SOCKET_ERROR
;
3791 if (fd_info
[s
].flags
& FILE_SOCKET
)
3793 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
3794 if (rc
== SOCKET_ERROR
)
3799 return SOCKET_ERROR
;
3803 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
3805 if (winsock_lib
== NULL
)
3812 if (fd_info
[s
].flags
& FILE_LISTEN
)
3814 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
3816 if (t
== INVALID_SOCKET
)
3819 fd
= socket_to_fd (t
);
3821 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3822 ResetEvent (fd_info
[s
].cp
->char_avail
);
3830 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
3831 struct sockaddr
* from
, int * fromlen
)
3833 if (winsock_lib
== NULL
)
3836 return SOCKET_ERROR
;
3840 if (fd_info
[s
].flags
& FILE_SOCKET
)
3842 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
3843 if (rc
== SOCKET_ERROR
)
3848 return SOCKET_ERROR
;
3852 sys_sendto (int s
, const char * buf
, int len
, int flags
,
3853 const struct sockaddr
* to
, int tolen
)
3855 if (winsock_lib
== NULL
)
3858 return SOCKET_ERROR
;
3862 if (fd_info
[s
].flags
& FILE_SOCKET
)
3864 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
3865 if (rc
== SOCKET_ERROR
)
3870 return SOCKET_ERROR
;
3873 /* Windows does not have an fcntl function. Provide an implementation
3874 solely for making sockets non-blocking. */
3876 fcntl (int s
, int cmd
, int options
)
3878 if (winsock_lib
== NULL
)
3885 if (fd_info
[s
].flags
& FILE_SOCKET
)
3887 if (cmd
== F_SETFL
&& options
== O_NDELAY
)
3889 unsigned long nblock
= 1;
3890 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
3891 if (rc
== SOCKET_ERROR
)
3893 /* Keep track of the fact that we set this to non-blocking. */
3894 fd_info
[s
].flags
|= FILE_NDELAY
;
3900 return SOCKET_ERROR
;
3904 return SOCKET_ERROR
;
3907 #endif /* HAVE_SOCKETS */
3910 /* Shadow main io functions: we need to handle pipes and sockets more
3911 intelligently, and implement non-blocking mode as well. */
3924 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
3926 child_process
* cp
= fd_info
[fd
].cp
;
3928 fd_info
[fd
].cp
= NULL
;
3930 if (CHILD_ACTIVE (cp
))
3932 /* if last descriptor to active child_process then cleanup */
3934 for (i
= 0; i
< MAXDESC
; i
++)
3938 if (fd_info
[i
].cp
== cp
)
3944 if (fd_info
[fd
].flags
& FILE_SOCKET
)
3946 #ifndef SOCK_REPLACE_HANDLE
3947 if (winsock_lib
== NULL
) abort ();
3949 pfn_shutdown (SOCK_HANDLE (fd
), 2);
3950 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
3952 winsock_inuse
--; /* count open sockets */
3960 /* Note that sockets do not need special treatment here (at least on
3961 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
3962 closesocket is equivalent to CloseHandle, which is to be expected
3963 because socket handles are fully fledged kernel handles. */
3966 if (rc
== 0 && fd
< MAXDESC
)
3967 fd_info
[fd
].flags
= 0;
3978 if (new_fd
>= 0 && new_fd
< MAXDESC
)
3980 /* duplicate our internal info as well */
3981 fd_info
[new_fd
] = fd_info
[fd
];
3988 sys_dup2 (int src
, int dst
)
3992 if (dst
< 0 || dst
>= MAXDESC
)
3998 /* make sure we close the destination first if it's a pipe or socket */
3999 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
4002 rc
= _dup2 (src
, dst
);
4005 /* duplicate our internal info as well */
4006 fd_info
[dst
] = fd_info
[src
];
4011 /* Unix pipe() has only one arg */
4013 sys_pipe (int * phandles
)
4018 /* make pipe handles non-inheritable; when we spawn a child, we
4019 replace the relevant handle with an inheritable one. Also put
4020 pipes into binary mode; we will do text mode translation ourselves
4022 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
4026 /* Protect against overflow, since Windows can open more handles than
4027 our fd_info array has room for. */
4028 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
4030 _close (phandles
[0]);
4031 _close (phandles
[1]);
4036 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
4037 fd_info
[phandles
[0]].flags
= flags
;
4039 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
4040 fd_info
[phandles
[1]].flags
= flags
;
4048 extern int w32_pipe_read_delay
;
4050 /* Function to do blocking read of one byte, needed to implement
4051 select. It is only allowed on sockets and pipes. */
4053 _sys_read_ahead (int fd
)
4058 if (fd
< 0 || fd
>= MAXDESC
)
4059 return STATUS_READ_ERROR
;
4061 cp
= fd_info
[fd
].cp
;
4063 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
4064 return STATUS_READ_ERROR
;
4066 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
4067 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
4069 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
4073 cp
->status
= STATUS_READ_IN_PROGRESS
;
4075 if (fd_info
[fd
].flags
& FILE_PIPE
)
4077 rc
= _read (fd
, &cp
->chr
, sizeof (char));
4079 /* Give subprocess time to buffer some more output for us before
4080 reporting that input is available; we need this because Windows 95
4081 connects DOS programs to pipes by making the pipe appear to be
4082 the normal console stdout - as a result most DOS programs will
4083 write to stdout without buffering, ie. one character at a
4084 time. Even some W32 programs do this - "dir" in a command
4085 shell on NT is very slow if we don't do this. */
4088 int wait
= w32_pipe_read_delay
;
4094 /* Yield remainder of our time slice, effectively giving a
4095 temporary priority boost to the child process. */
4100 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
4102 unsigned long nblock
= 0;
4103 /* We always want this to block, so temporarily disable NDELAY. */
4104 if (fd_info
[fd
].flags
& FILE_NDELAY
)
4105 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
4107 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
4109 if (fd_info
[fd
].flags
& FILE_NDELAY
)
4112 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
4117 if (rc
== sizeof (char))
4118 cp
->status
= STATUS_READ_SUCCEEDED
;
4120 cp
->status
= STATUS_READ_FAILED
;
4126 _sys_wait_accept (int fd
)
4132 if (fd
< 0 || fd
>= MAXDESC
)
4133 return STATUS_READ_ERROR
;
4135 cp
= fd_info
[fd
].cp
;
4137 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
4138 return STATUS_READ_ERROR
;
4140 cp
->status
= STATUS_READ_FAILED
;
4142 hEv
= pfn_WSACreateEvent ();
4143 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
4144 if (rc
!= SOCKET_ERROR
)
4146 rc
= WaitForSingleObject (hEv
, INFINITE
);
4147 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
4148 if (rc
== WAIT_OBJECT_0
)
4149 cp
->status
= STATUS_READ_SUCCEEDED
;
4151 pfn_WSACloseEvent (hEv
);
4157 sys_read (int fd
, char * buffer
, unsigned int count
)
4162 char * orig_buffer
= buffer
;
4170 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
4172 child_process
*cp
= fd_info
[fd
].cp
;
4174 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
4182 /* re-read CR carried over from last read */
4183 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
4185 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
4189 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
4192 /* presence of a child_process structure means we are operating in
4193 non-blocking mode - otherwise we just call _read directly.
4194 Note that the child_process structure might be missing because
4195 reap_subprocess has been called; in this case the pipe is
4196 already broken, so calling _read on it is okay. */
4199 int current_status
= cp
->status
;
4201 switch (current_status
)
4203 case STATUS_READ_FAILED
:
4204 case STATUS_READ_ERROR
:
4205 /* report normal EOF if nothing in buffer */
4207 fd_info
[fd
].flags
|= FILE_AT_EOF
;
4210 case STATUS_READ_READY
:
4211 case STATUS_READ_IN_PROGRESS
:
4212 DebPrint (("sys_read called when read is in progress\n"));
4213 errno
= EWOULDBLOCK
;
4216 case STATUS_READ_SUCCEEDED
:
4217 /* consume read-ahead char */
4218 *buffer
++ = cp
->chr
;
4221 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
4222 ResetEvent (cp
->char_avail
);
4224 case STATUS_READ_ACKNOWLEDGED
:
4228 DebPrint (("sys_read: bad status %d\n", current_status
));
4233 if (fd_info
[fd
].flags
& FILE_PIPE
)
4235 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
4236 to_read
= min (waiting
, (DWORD
) count
);
4239 nchars
+= _read (fd
, buffer
, to_read
);
4242 else /* FILE_SOCKET */
4244 if (winsock_lib
== NULL
) abort ();
4246 /* do the equivalent of a non-blocking read */
4247 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
4248 if (waiting
== 0 && nchars
== 0)
4250 h_errno
= errno
= EWOULDBLOCK
;
4256 /* always use binary mode for sockets */
4257 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
4258 if (res
== SOCKET_ERROR
)
4260 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
4261 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
4272 int nread
= _read (fd
, buffer
, count
);
4275 else if (nchars
== 0)
4280 fd_info
[fd
].flags
|= FILE_AT_EOF
;
4281 /* Perform text mode translation if required. */
4282 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
4284 nchars
= crlf_to_lf (nchars
, orig_buffer
);
4285 /* If buffer contains only CR, return that. To be absolutely
4286 sure we should attempt to read the next char, but in
4287 practice a CR to be followed by LF would not appear by
4288 itself in the buffer. */
4289 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
4291 fd_info
[fd
].flags
|= FILE_LAST_CR
;
4297 nchars
= _read (fd
, buffer
, count
);
4302 /* For now, don't bother with a non-blocking mode */
4304 sys_write (int fd
, const void * buffer
, unsigned int count
)
4314 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
4316 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
4322 /* Perform text mode translation if required. */
4323 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
4325 char * tmpbuf
= alloca (count
* 2);
4326 unsigned char * src
= (void *)buffer
;
4327 unsigned char * dst
= tmpbuf
;
4332 unsigned char *next
;
4333 /* copy next line or remaining bytes */
4334 next
= _memccpy (dst
, src
, '\n', nbytes
);
4337 /* copied one line ending with '\n' */
4338 int copied
= next
- dst
;
4341 /* insert '\r' before '\n' */
4348 /* copied remaining partial line -> now finished */
4356 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
4358 unsigned long nblock
= 0;
4359 if (winsock_lib
== NULL
) abort ();
4361 /* TODO: implement select() properly so non-blocking I/O works. */
4362 /* For now, make sure the write blocks. */
4363 if (fd_info
[fd
].flags
& FILE_NDELAY
)
4364 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
4366 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
4368 /* Set the socket back to non-blocking if it was before,
4369 for other operations that support it. */
4370 if (fd_info
[fd
].flags
& FILE_NDELAY
)
4373 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
4376 if (nchars
== SOCKET_ERROR
)
4378 DebPrint(("sys_write.send failed with error %d on socket %ld\n",
4379 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
4385 nchars
= _write (fd
, buffer
, count
);
4391 check_windows_init_file ()
4393 extern int noninteractive
, inhibit_window_system
;
4395 /* A common indication that Emacs is not installed properly is when
4396 it cannot find the Windows installation file. If this file does
4397 not exist in the expected place, tell the user. */
4399 if (!noninteractive
&& !inhibit_window_system
)
4401 extern Lisp_Object Vwindow_system
, Vload_path
, Qfile_exists_p
;
4402 Lisp_Object objs
[2];
4403 Lisp_Object full_load_path
;
4404 Lisp_Object init_file
;
4407 objs
[0] = Vload_path
;
4408 objs
[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
4409 full_load_path
= Fappend (2, objs
);
4410 init_file
= build_string ("term/w32-win");
4411 fd
= openp (full_load_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
4414 Lisp_Object load_path_print
= Fprin1_to_string (full_load_path
, Qnil
);
4415 char *init_file_name
= SDATA (init_file
);
4416 char *load_path
= SDATA (load_path_print
);
4417 char *buffer
= alloca (1024
4418 + strlen (init_file_name
)
4419 + strlen (load_path
));
4422 "The Emacs Windows initialization file \"%s.el\" "
4423 "could not be found in your Emacs installation. "
4424 "Emacs checked the following directories for this file:\n"
4426 "When Emacs cannot find this file, it usually means that it "
4427 "was not installed properly, or its distribution file was "
4428 "not unpacked properly.\nSee the README.W32 file in the "
4429 "top-level Emacs directory for more information.",
4430 init_file_name
, load_path
);
4433 "Emacs Abort Dialog",
4434 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
4435 /* Use the low-level Emacs abort. */
4450 /* shutdown the socket interface if necessary */
4461 /* Initialise the socket interface now if available and requested by
4462 the user by defining PRELOAD_WINSOCK; otherwise loading will be
4463 delayed until open-network-stream is called (w32-has-winsock can
4464 also be used to dynamically load or reload winsock).
4466 Conveniently, init_environment is called before us, so
4467 PRELOAD_WINSOCK can be set in the registry. */
4469 /* Always initialize this correctly. */
4472 if (getenv ("PRELOAD_WINSOCK") != NULL
)
4473 init_winsock (TRUE
);
4476 /* Initial preparation for subprocess support: replace our standard
4477 handles with non-inheritable versions. */
4480 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
4481 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
4482 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
4484 parent
= GetCurrentProcess ();
4486 /* ignore errors when duplicating and closing; typically the
4487 handles will be invalid when running as a gui program. */
4488 DuplicateHandle (parent
,
4489 GetStdHandle (STD_INPUT_HANDLE
),
4494 DUPLICATE_SAME_ACCESS
);
4496 DuplicateHandle (parent
,
4497 GetStdHandle (STD_OUTPUT_HANDLE
),
4502 DUPLICATE_SAME_ACCESS
);
4504 DuplicateHandle (parent
,
4505 GetStdHandle (STD_ERROR_HANDLE
),
4510 DUPLICATE_SAME_ACCESS
);
4516 if (stdin_save
!= INVALID_HANDLE_VALUE
)
4517 _open_osfhandle ((long) stdin_save
, O_TEXT
);
4519 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
4522 if (stdout_save
!= INVALID_HANDLE_VALUE
)
4523 _open_osfhandle ((long) stdout_save
, O_TEXT
);
4525 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
4528 if (stderr_save
!= INVALID_HANDLE_VALUE
)
4529 _open_osfhandle ((long) stderr_save
, O_TEXT
);
4531 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
4535 /* unfortunately, atexit depends on implementation of malloc */
4536 /* atexit (term_ntproc); */
4537 signal (SIGABRT
, term_ntproc
);
4539 /* determine which drives are fixed, for GetCachedVolumeInformation */
4541 /* GetDriveType must have trailing backslash. */
4542 char drive
[] = "A:\\";
4544 /* Loop over all possible drive letters */
4545 while (*drive
<= 'Z')
4547 /* Record if this drive letter refers to a fixed drive. */
4548 fixed_drives
[DRIVE_INDEX (*drive
)] =
4549 (GetDriveType (drive
) == DRIVE_FIXED
);
4554 /* Reset the volume info cache. */
4555 volume_cache
= NULL
;
4558 /* Check to see if Emacs has been installed correctly. */
4559 check_windows_init_file ();
4563 shutdown_handler ensures that buffers' autosave files are
4564 up to date when the user logs off, or the system shuts down.
4566 BOOL WINAPI
shutdown_handler(DWORD type
)
4568 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
4569 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
4570 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
4571 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
4573 /* Shut down cleanly, making sure autosave files are up to date. */
4574 shut_down_emacs (0, 0, Qnil
);
4577 /* Allow other handlers to handle this signal. */
4582 globals_of_w32 is used to initialize those global variables that
4583 must always be initialized on startup even when the global variable
4584 initialized is non zero (see the function main in emacs.c).
4589 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
4591 get_process_times_fn
= (GetProcessTimes_Proc
)
4592 GetProcAddress (kernel32
, "GetProcessTimes");
4594 g_b_init_is_windows_9x
= 0;
4595 g_b_init_open_process_token
= 0;
4596 g_b_init_get_token_information
= 0;
4597 g_b_init_lookup_account_sid
= 0;
4598 g_b_init_get_sid_identifier_authority
= 0;
4599 g_b_init_get_sid_sub_authority
= 0;
4600 g_b_init_get_sid_sub_authority_count
= 0;
4601 g_b_init_get_file_security
= 0;
4602 g_b_init_get_security_descriptor_owner
= 0;
4603 g_b_init_get_security_descriptor_group
= 0;
4604 g_b_init_is_valid_sid
= 0;
4605 /* The following sets a handler for shutdown notifications for
4606 console apps. This actually applies to Emacs in both console and
4607 GUI modes, since we had to fool windows into thinking emacs is a
4608 console application to get console mode to work. */
4609 SetConsoleCtrlHandler(shutdown_handler
, TRUE
);
4611 /* "None" is the default group name on standalone workstations. */
4612 strcpy (dflt_group_name
, "None");
4617 /* arch-tag: 90442dd3-37be-482b-b272-ac752e3049f1
4618 (do not change this comment) */