1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995, 2000, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
25 #include <stddef.h> /* for offsetof */
35 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
71 #define _ANONYMOUS_UNION
72 #define _ANONYMOUS_STRUCT
76 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
77 #include <sys/socket.h>
95 extern Lisp_Object Vw32_downcase_file_names
;
96 extern Lisp_Object Vw32_generate_fake_inodes
;
97 extern Lisp_Object Vw32_get_true_file_attributes
;
98 extern Lisp_Object Vw32_num_mouse_buttons
;
101 /* Equivalent of strerror for W32 error codes. */
103 w32_strerror (int error_no
)
105 static char buf
[500];
108 error_no
= GetLastError ();
111 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
, NULL
,
113 0, /* choose most suitable language */
114 buf
, sizeof (buf
), NULL
))
115 sprintf (buf
, "w32 error %u", error_no
);
119 static char startup_dir
[MAXPATHLEN
];
121 /* Get the current working directory. */
126 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
130 /* Emacs doesn't actually change directory itself, and we want to
131 force our real wd to be where emacs.exe is to avoid unnecessary
132 conflicts when trying to rename or delete directories. */
133 strcpy (dir
, startup_dir
);
139 /* Emulate gethostname. */
141 gethostname (char *buffer
, int size
)
143 /* NT only allows small host names, so the buffer is
144 certainly large enough. */
145 return !GetComputerName (buffer
, &size
);
147 #endif /* HAVE_SOCKETS */
149 /* Emulate getloadavg. */
151 getloadavg (double loadavg
[], int nelem
)
155 /* A faithful emulation is going to have to be saved for a rainy day. */
156 for (i
= 0; i
< nelem
; i
++)
163 /* Emulate getpwuid, getpwnam and others. */
165 #define PASSWD_FIELD_SIZE 256
167 static char the_passwd_name
[PASSWD_FIELD_SIZE
];
168 static char the_passwd_passwd
[PASSWD_FIELD_SIZE
];
169 static char the_passwd_gecos
[PASSWD_FIELD_SIZE
];
170 static char the_passwd_dir
[PASSWD_FIELD_SIZE
];
171 static char the_passwd_shell
[PASSWD_FIELD_SIZE
];
173 static struct passwd the_passwd
=
188 return the_passwd
.pw_uid
;
194 /* I could imagine arguing for checking to see whether the user is
195 in the Administrators group and returning a UID of 0 for that
196 case, but I don't know how wise that would be in the long run. */
203 return the_passwd
.pw_gid
;
215 if (uid
== the_passwd
.pw_uid
)
221 getpwnam (char *name
)
225 pw
= getpwuid (getuid ());
229 if (stricmp (name
, pw
->pw_name
))
238 /* Find the user's real name by opening the process token and
239 looking up the name associated with the user-sid in that token.
241 Use the relative portion of the identifier authority value from
242 the user-sid as the user id value (same for group id using the
243 primary group sid from the process token). */
245 char user_sid
[256], name
[256], domain
[256];
246 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
248 SID_NAME_USE user_type
;
250 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &token
)
251 && GetTokenInformation (token
, TokenUser
,
252 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
253 && LookupAccountSid (NULL
, *((PSID
*) user_sid
), name
, &length
,
254 domain
, &dlength
, &user_type
))
256 strcpy (the_passwd
.pw_name
, name
);
257 /* Determine a reasonable uid value. */
258 if (stricmp ("administrator", name
) == 0)
260 the_passwd
.pw_uid
= 0;
261 the_passwd
.pw_gid
= 0;
265 SID_IDENTIFIER_AUTHORITY
* pSIA
;
267 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
268 /* I believe the relative portion is the last 4 bytes (of 6)
270 the_passwd
.pw_uid
= ((pSIA
->Value
[2] << 24) +
271 (pSIA
->Value
[3] << 16) +
272 (pSIA
->Value
[4] << 8) +
273 (pSIA
->Value
[5] << 0));
274 /* restrict to conventional uid range for normal users */
275 the_passwd
.pw_uid
= the_passwd
.pw_uid
% 60001;
278 if (GetTokenInformation (token
, TokenPrimaryGroup
,
279 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
281 SID_IDENTIFIER_AUTHORITY
* pSIA
;
283 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
284 the_passwd
.pw_gid
= ((pSIA
->Value
[2] << 24) +
285 (pSIA
->Value
[3] << 16) +
286 (pSIA
->Value
[4] << 8) +
287 (pSIA
->Value
[5] << 0));
288 /* I don't know if this is necessary, but for safety... */
289 the_passwd
.pw_gid
= the_passwd
.pw_gid
% 60001;
292 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
295 /* If security calls are not supported (presumably because we
296 are running under Windows 95), fallback to this. */
297 else if (GetUserName (name
, &length
))
299 strcpy (the_passwd
.pw_name
, name
);
300 if (stricmp ("administrator", name
) == 0)
301 the_passwd
.pw_uid
= 0;
303 the_passwd
.pw_uid
= 123;
304 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
308 strcpy (the_passwd
.pw_name
, "unknown");
309 the_passwd
.pw_uid
= 123;
310 the_passwd
.pw_gid
= 123;
313 /* Ensure HOME and SHELL are defined. */
314 if (getenv ("HOME") == NULL
)
316 if (getenv ("SHELL") == NULL
)
319 /* Set dir and shell from environment variables. */
320 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
321 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
330 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
331 return ((rand () << 15) | rand ());
341 /* Normalize filename by converting all path separators to
342 the specified separator. Also conditionally convert upper
343 case path name components to lower case. */
346 normalize_filename (fp
, path_sep
)
353 /* Always lower-case drive letters a-z, even if the filesystem
354 preserves case in filenames.
355 This is so filenames can be compared by string comparison
356 functions that are case-sensitive. Even case-preserving filesystems
357 do not distinguish case in drive letters. */
358 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
364 if (NILP (Vw32_downcase_file_names
))
368 if (*fp
== '/' || *fp
== '\\')
375 sep
= path_sep
; /* convert to this path separator */
376 elem
= fp
; /* start of current path element */
379 if (*fp
>= 'a' && *fp
<= 'z')
380 elem
= 0; /* don't convert this element */
382 if (*fp
== 0 || *fp
== ':')
384 sep
= *fp
; /* restore current separator (or 0) */
385 *fp
= '/'; /* after conversion of this element */
388 if (*fp
== '/' || *fp
== '\\')
390 if (elem
&& elem
!= fp
)
392 *fp
= 0; /* temporary end of string */
393 _strlwr (elem
); /* while we convert to lower case */
395 *fp
= sep
; /* convert (or restore) path separator */
396 elem
= fp
+ 1; /* next element starts after separator */
402 /* Destructively turn backslashes into slashes. */
404 dostounix_filename (p
)
407 normalize_filename (p
, '/');
410 /* Destructively turn slashes into backslashes. */
412 unixtodos_filename (p
)
415 normalize_filename (p
, '\\');
418 /* Remove all CR's that are followed by a LF.
419 (From msdos.c...probably should figure out a way to share it,
420 although this code isn't going to ever change.) */
424 register unsigned char *buf
;
426 unsigned char *np
= buf
;
427 unsigned char *startp
= buf
;
428 unsigned char *endp
= buf
+ n
;
432 while (buf
< endp
- 1)
436 if (*(++buf
) != 0x0a)
447 /* Parse the root part of file name, if present. Return length and
448 optionally store pointer to char after root. */
450 parse_root (char * name
, char ** pPath
)
457 /* find the root name of the volume if given */
458 if (isalpha (name
[0]) && name
[1] == ':')
460 /* skip past drive specifier */
462 if (IS_DIRECTORY_SEP (name
[0]))
465 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
471 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
476 if (IS_DIRECTORY_SEP (name
[0]))
486 /* Get long base name for name; name is assumed to be absolute. */
488 get_long_basename (char * name
, char * buf
, int size
)
490 WIN32_FIND_DATA find_data
;
494 /* must be valid filename, no wild cards or other invalid characters */
495 if (strpbrk (name
, "*?|<>\""))
498 dir_handle
= FindFirstFile (name
, &find_data
);
499 if (dir_handle
!= INVALID_HANDLE_VALUE
)
501 if ((len
= strlen (find_data
.cFileName
)) < size
)
502 memcpy (buf
, find_data
.cFileName
, len
+ 1);
505 FindClose (dir_handle
);
510 /* Get long name for file, if possible (assumed to be absolute). */
512 w32_get_long_filename (char * name
, char * buf
, int size
)
517 char full
[ MAX_PATH
];
524 /* Use local copy for destructive modification. */
525 memcpy (full
, name
, len
+1);
526 unixtodos_filename (full
);
528 /* Copy root part verbatim. */
529 len
= parse_root (full
, &p
);
530 memcpy (o
, full
, len
);
535 while (p
!= NULL
&& *p
)
538 p
= strchr (q
, '\\');
540 len
= get_long_basename (full
, o
, size
);
563 is_unc_volume (const char *filename
)
565 const char *ptr
= filename
;
567 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
570 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
576 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
579 sigsetmask (int signal_mask
)
603 setpgrp (int pid
, int gid
)
615 unrequest_sigio (void)
626 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
629 w32_get_resource (key
, lpdwtype
)
634 HKEY hrootkey
= NULL
;
638 /* Check both the current user and the local machine to see if
639 we have any resources. */
641 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
645 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
646 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
647 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
652 if (lpvalue
) xfree (lpvalue
);
654 RegCloseKey (hrootkey
);
657 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
661 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
662 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
663 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
668 if (lpvalue
) xfree (lpvalue
);
670 RegCloseKey (hrootkey
);
676 char *get_emacs_configuration (void);
677 extern Lisp_Object Vsystem_configuration
;
680 init_environment (char ** argv
)
682 static const char * const tempdirs
[] = {
683 "$TMPDIR", "$TEMP", "$TMP", "c:/"
686 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
688 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
689 temporary files and assume "/tmp" if $TMPDIR is unset, which
690 will break on DOS/Windows. Refuse to work if we cannot find
691 a directory, not even "c:/", usable for that purpose. */
692 for (i
= 0; i
< imax
; i
++)
694 const char *tmp
= tempdirs
[i
];
697 tmp
= getenv (tmp
+ 1);
698 /* Note that `access' can lie to us if the directory resides on a
699 read-only filesystem, like CD-ROM or a write-protected floppy.
700 The only way to be really sure is to actually create a file and
701 see if it succeeds. But I think that's too much to ask. */
702 if (tmp
&& _access (tmp
, D_OK
) == 0)
704 char * var
= alloca (strlen (tmp
) + 8);
705 sprintf (var
, "TMPDIR=%s", tmp
);
706 _putenv (strdup (var
));
713 Fcons (build_string ("no usable temporary directories found!!"),
715 "While setting TMPDIR: ");
717 /* Check for environment variables and use registry settings if they
718 don't exist. Fallback on default values where applicable. */
723 char locale_name
[32];
725 static struct env_entry
732 {"PRELOAD_WINSOCK", NULL
},
733 {"emacs_dir", "C:/emacs"},
734 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/../site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
735 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
736 {"EMACSDATA", "%emacs_dir%/etc"},
737 {"EMACSPATH", "%emacs_dir%/bin"},
738 {"EMACSLOCKDIR", "%emacs_dir%/lock"},
739 /* We no longer set INFOPATH because Info-default-directory-list
741 /* {"INFOPATH", "%emacs_dir%/info"}, */
742 {"EMACSDOC", "%emacs_dir%/etc"},
747 /* Get default locale info and use it for LANG. */
748 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
749 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
750 locale_name
, sizeof (locale_name
)))
752 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
754 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
756 env_vars
[i
].def_value
= locale_name
;
762 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
764 /* Treat emacs_dir specially: set it unconditionally based on our
765 location, if it appears that we are running from the bin subdir
766 of a standard installation. */
769 char modname
[MAX_PATH
];
771 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
773 if ((p
= strrchr (modname
, '\\')) == NULL
)
777 if ((p
= strrchr (modname
, '\\')) && stricmp (p
, "\\bin") == 0)
779 char buf
[SET_ENV_BUF_SIZE
];
782 for (p
= modname
; *p
; p
++)
783 if (*p
== '\\') *p
= '/';
785 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
786 _putenv (strdup (buf
));
790 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
792 if (!getenv (env_vars
[i
].name
))
796 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
)
798 lpval
= env_vars
[i
].def_value
;
799 dwType
= REG_EXPAND_SZ
;
805 if (dwType
== REG_EXPAND_SZ
)
807 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
809 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof(buf1
));
810 _snprintf (buf2
, sizeof(buf2
)-1, "%s=%s", env_vars
[i
].name
, buf1
);
811 _putenv (strdup (buf2
));
813 else if (dwType
== REG_SZ
)
815 char buf
[SET_ENV_BUF_SIZE
];
817 _snprintf (buf
, sizeof(buf
)-1, "%s=%s", env_vars
[i
].name
, lpval
);
818 _putenv (strdup (buf
));
828 /* Rebuild system configuration to reflect invoking system. */
829 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
831 /* Another special case: on NT, the PATH variable is actually named
832 "Path" although cmd.exe (perhaps NT itself) arranges for
833 environment variable lookup and setting to be case insensitive.
834 However, Emacs assumes a fully case sensitive environment, so we
835 need to change "Path" to "PATH" to match the expectations of
836 various elisp packages. We do this by the sneaky method of
837 modifying the string in the C runtime environ entry.
839 The same applies to COMSPEC. */
843 for (envp
= environ
; *envp
; envp
++)
844 if (_strnicmp (*envp
, "PATH=", 5) == 0)
845 memcpy (*envp
, "PATH=", 5);
846 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
847 memcpy (*envp
, "COMSPEC=", 8);
850 /* Remember the initial working directory for getwd, then make the
851 real wd be the location of emacs.exe to avoid conflicts when
852 renaming or deleting directories. (We also don't call chdir when
853 running subprocesses for the same reason.) */
854 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
859 static char modname
[MAX_PATH
];
861 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
863 if ((p
= strrchr (modname
, '\\')) == NULL
)
867 SetCurrentDirectory (modname
);
869 /* Ensure argv[0] has the full path to Emacs. */
874 /* Determine if there is a middle mouse button, to allow parse_button
875 to decide whether right mouse events should be mouse-2 or
877 XSETINT (Vw32_num_mouse_buttons
, GetSystemMetrics (SM_CMOUSEBUTTONS
));
883 emacs_root_dir (void)
885 static char root_dir
[FILENAME_MAX
];
888 p
= getenv ("emacs_dir");
891 strcpy (root_dir
, p
);
892 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
893 dostounix_filename (root_dir
);
897 /* We don't have scripts to automatically determine the system configuration
898 for Emacs before it's compiled, and we don't want to have to make the
899 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
903 get_emacs_configuration (void)
905 char *arch
, *oem
, *os
;
907 static char configuration_buffer
[32];
909 /* Determine the processor type. */
910 switch (get_processor_type ())
913 #ifdef PROCESSOR_INTEL_386
914 case PROCESSOR_INTEL_386
:
915 case PROCESSOR_INTEL_486
:
916 case PROCESSOR_INTEL_PENTIUM
:
921 #ifdef PROCESSOR_INTEL_860
922 case PROCESSOR_INTEL_860
:
927 #ifdef PROCESSOR_MIPS_R2000
928 case PROCESSOR_MIPS_R2000
:
929 case PROCESSOR_MIPS_R3000
:
930 case PROCESSOR_MIPS_R4000
:
935 #ifdef PROCESSOR_ALPHA_21064
936 case PROCESSOR_ALPHA_21064
:
946 /* Use the OEM field to reflect the compiler/library combination. */
948 #define COMPILER_NAME "msvc"
951 #define COMPILER_NAME "mingw"
953 #define COMPILER_NAME "unknown"
958 switch (osinfo_cache
.dwPlatformId
) {
959 case VER_PLATFORM_WIN32_NT
:
961 build_num
= osinfo_cache
.dwBuildNumber
;
963 case VER_PLATFORM_WIN32_WINDOWS
:
964 if (osinfo_cache
.dwMinorVersion
== 0) {
969 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
971 case VER_PLATFORM_WIN32s
:
972 /* Not supported, should not happen. */
974 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
982 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
983 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
984 get_w32_major_version (), get_w32_minor_version (), build_num
);
986 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
989 return configuration_buffer
;
993 get_emacs_configuration_options (void)
995 static char options_buffer
[256];
997 /* Work out the effective configure options for this build. */
999 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1002 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1004 #define COMPILER_VERSION ""
1008 sprintf (options_buffer
, COMPILER_VERSION
);
1010 strcat (options_buffer
, " --no-opt");
1013 strcat (options_buffer
, " --cflags");
1014 strcat (options_buffer
, USER_CFLAGS
);
1017 strcat (options_buffer
, " --ldflags");
1018 strcat (options_buffer
, USER_LDFLAGS
);
1020 return options_buffer
;
1024 #include <sys/timeb.h>
1026 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1028 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
1033 tv
->tv_sec
= tb
.time
;
1034 tv
->tv_usec
= tb
.millitm
* 1000L;
1037 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
1038 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
1042 /* ------------------------------------------------------------------------- */
1043 /* IO support and wrapper functions for W32 API. */
1044 /* ------------------------------------------------------------------------- */
1046 /* Place a wrapper around the MSVC version of ctime. It returns NULL
1047 on network directories, so we handle that case here.
1048 (Ulrich Leodolter, 1/11/95). */
1050 sys_ctime (const time_t *t
)
1052 char *str
= (char *) ctime (t
);
1053 return (str
? str
: "Sun Jan 01 00:00:00 1970");
1056 /* Emulate sleep...we could have done this with a define, but that
1057 would necessitate including windows.h in the files that used it.
1058 This is much easier. */
1060 sys_sleep (int seconds
)
1062 Sleep (seconds
* 1000);
1065 /* Internal MSVC functions for low-level descriptor munging */
1066 extern int __cdecl
_set_osfhnd (int fd
, long h
);
1067 extern int __cdecl
_free_osfhnd (int fd
);
1069 /* parallel array of private info on file handles */
1070 filedesc fd_info
[ MAXDESC
];
1072 typedef struct volume_info_data
{
1073 struct volume_info_data
* next
;
1075 /* time when info was obtained */
1078 /* actual volume info */
1087 /* Global referenced by various functions. */
1088 static volume_info_data volume_info
;
1090 /* Vector to indicate which drives are local and fixed (for which cached
1091 data never expires). */
1092 static BOOL fixed_drives
[26];
1094 /* Consider cached volume information to be stale if older than 10s,
1095 at least for non-local drives. Info for fixed drives is never stale. */
1096 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
1097 #define VOLINFO_STILL_VALID( root_dir, info ) \
1098 ( ( isalpha (root_dir[0]) && \
1099 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
1100 || GetTickCount () - info->timestamp < 10000 )
1102 /* Cache support functions. */
1104 /* Simple linked list with linear search is sufficient. */
1105 static volume_info_data
*volume_cache
= NULL
;
1107 static volume_info_data
*
1108 lookup_volume_info (char * root_dir
)
1110 volume_info_data
* info
;
1112 for (info
= volume_cache
; info
; info
= info
->next
)
1113 if (stricmp (info
->root_dir
, root_dir
) == 0)
1119 add_volume_info (char * root_dir
, volume_info_data
* info
)
1121 info
->root_dir
= xstrdup (root_dir
);
1122 info
->next
= volume_cache
;
1123 volume_cache
= info
;
1127 /* Wrapper for GetVolumeInformation, which uses caching to avoid
1128 performance penalty (~2ms on 486 for local drives, 7.5ms for local
1129 cdrom drive, ~5-10ms or more for remote drives on LAN). */
1131 GetCachedVolumeInformation (char * root_dir
)
1133 volume_info_data
* info
;
1134 char default_root
[ MAX_PATH
];
1136 /* NULL for root_dir means use root from current directory. */
1137 if (root_dir
== NULL
)
1139 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
1141 parse_root (default_root
, &root_dir
);
1143 root_dir
= default_root
;
1146 /* Local fixed drives can be cached permanently. Removable drives
1147 cannot be cached permanently, since the volume name and serial
1148 number (if nothing else) can change. Remote drives should be
1149 treated as if they are removable, since there is no sure way to
1150 tell whether they are or not. Also, the UNC association of drive
1151 letters mapped to remote volumes can be changed at any time (even
1152 by other processes) without notice.
1154 As a compromise, so we can benefit from caching info for remote
1155 volumes, we use a simple expiry mechanism to invalidate cache
1156 entries that are more than ten seconds old. */
1159 /* No point doing this, because WNetGetConnection is even slower than
1160 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
1161 GetDriveType is about the only call of this type which does not
1162 involve network access, and so is extremely quick). */
1164 /* Map drive letter to UNC if remote. */
1165 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
1167 char remote_name
[ 256 ];
1168 char drive
[3] = { root_dir
[0], ':' };
1170 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
1172 /* do something */ ;
1176 info
= lookup_volume_info (root_dir
);
1178 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
1186 /* Info is not cached, or is stale. */
1187 if (!GetVolumeInformation (root_dir
,
1188 name
, sizeof (name
),
1192 type
, sizeof (type
)))
1195 /* Cache the volume information for future use, overwriting existing
1196 entry if present. */
1199 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
1200 add_volume_info (root_dir
, info
);
1208 info
->name
= xstrdup (name
);
1209 info
->serialnum
= serialnum
;
1210 info
->maxcomp
= maxcomp
;
1211 info
->flags
= flags
;
1212 info
->type
= xstrdup (type
);
1213 info
->timestamp
= GetTickCount ();
1219 /* Get information on the volume where name is held; set path pointer to
1220 start of pathname in name (past UNC header\volume header if present). */
1222 get_volume_info (const char * name
, const char ** pPath
)
1224 char temp
[MAX_PATH
];
1225 char *rootname
= NULL
; /* default to current volume */
1226 volume_info_data
* info
;
1231 /* find the root name of the volume if given */
1232 if (isalpha (name
[0]) && name
[1] == ':')
1240 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1247 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1260 info
= GetCachedVolumeInformation (rootname
);
1263 /* Set global referenced by other functions. */
1264 volume_info
= *info
;
1270 /* Determine if volume is FAT format (ie. only supports short 8.3
1271 names); also set path pointer to start of pathname in name. */
1273 is_fat_volume (const char * name
, const char ** pPath
)
1275 if (get_volume_info (name
, pPath
))
1276 return (volume_info
.maxcomp
== 12);
1280 /* Map filename to a legal 8.3 name if necessary. */
1282 map_w32_filename (const char * name
, const char ** pPath
)
1284 static char shortname
[MAX_PATH
];
1285 char * str
= shortname
;
1288 const char * save_name
= name
;
1290 if (strlen (name
) >= MAX_PATH
)
1292 /* Return a filename which will cause callers to fail. */
1293 strcpy (shortname
, "?");
1297 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
1299 register int left
= 8; /* maximum number of chars in part */
1300 register int extn
= 0; /* extension added? */
1301 register int dots
= 2; /* maximum number of dots allowed */
1304 *str
++ = *name
++; /* skip past UNC header */
1306 while ((c
= *name
++))
1313 extn
= 0; /* reset extension flags */
1314 dots
= 2; /* max 2 dots */
1315 left
= 8; /* max length 8 for main part */
1319 extn
= 0; /* reset extension flags */
1320 dots
= 2; /* max 2 dots */
1321 left
= 8; /* max length 8 for main part */
1326 /* Convert path components of the form .xxx to _xxx,
1327 but leave . and .. as they are. This allows .emacs
1328 to be read as _emacs, for example. */
1332 IS_DIRECTORY_SEP (*name
))
1347 extn
= 1; /* we've got an extension */
1348 left
= 3; /* 3 chars in extension */
1352 /* any embedded dots after the first are converted to _ */
1357 case '#': /* don't lose these, they're important */
1359 str
[-1] = c
; /* replace last character of part */
1364 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1366 dots
= 0; /* started a path component */
1375 strcpy (shortname
, name
);
1376 unixtodos_filename (shortname
);
1380 *pPath
= shortname
+ (path
- save_name
);
1386 is_exec (const char * name
)
1388 char * p
= strrchr (name
, '.');
1391 && (stricmp (p
, ".exe") == 0 ||
1392 stricmp (p
, ".com") == 0 ||
1393 stricmp (p
, ".bat") == 0 ||
1394 stricmp (p
, ".cmd") == 0));
1397 /* Emulate the Unix directory procedures opendir, closedir,
1398 and readdir. We can't use the procedures supplied in sysdep.c,
1399 so we provide them here. */
1401 struct direct dir_static
; /* simulated directory contents */
1402 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1403 static int dir_is_fat
;
1404 static char dir_pathname
[MAXPATHLEN
+1];
1405 static WIN32_FIND_DATA dir_find_data
;
1407 /* Support shares on a network resource as subdirectories of a read-only
1409 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1410 HANDLE
open_unc_volume (char *);
1411 char *read_unc_volume (HANDLE
, char *, int);
1412 void close_unc_volume (HANDLE
);
1415 opendir (char *filename
)
1419 /* Opening is done by FindFirstFile. However, a read is inherent to
1420 this operation, so we defer the open until read time. */
1422 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1424 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1427 if (is_unc_volume (filename
))
1429 wnet_enum_handle
= open_unc_volume (filename
);
1430 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
1434 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1441 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1442 dir_pathname
[MAXPATHLEN
] = '\0';
1443 dir_is_fat
= is_fat_volume (filename
, NULL
);
1449 closedir (DIR *dirp
)
1451 /* If we have a find-handle open, close it. */
1452 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1454 FindClose (dir_find_handle
);
1455 dir_find_handle
= INVALID_HANDLE_VALUE
;
1457 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1459 close_unc_volume (wnet_enum_handle
);
1460 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1462 xfree ((char *) dirp
);
1468 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1470 if (!read_unc_volume (wnet_enum_handle
,
1471 dir_find_data
.cFileName
,
1475 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1476 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1478 char filename
[MAXNAMLEN
+ 3];
1481 strcpy (filename
, dir_pathname
);
1482 ln
= strlen (filename
) - 1;
1483 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1484 strcat (filename
, "\\");
1485 strcat (filename
, "*");
1487 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1489 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1494 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1498 /* Emacs never uses this value, so don't bother making it match
1499 value returned by stat(). */
1500 dir_static
.d_ino
= 1;
1502 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1503 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1505 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1506 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1508 _strlwr (dir_static
.d_name
);
1509 else if (!NILP (Vw32_downcase_file_names
))
1512 for (p
= dir_static
.d_name
; *p
; p
++)
1513 if (*p
>= 'a' && *p
<= 'z')
1516 _strlwr (dir_static
.d_name
);
1523 open_unc_volume (char *path
)
1529 nr
.dwScope
= RESOURCE_GLOBALNET
;
1530 nr
.dwType
= RESOURCETYPE_DISK
;
1531 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
1532 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
1533 nr
.lpLocalName
= NULL
;
1534 nr
.lpRemoteName
= map_w32_filename (path
, NULL
);
1535 nr
.lpComment
= NULL
;
1536 nr
.lpProvider
= NULL
;
1538 result
= WNetOpenEnum(RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
1539 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
1541 if (result
== NO_ERROR
)
1544 return INVALID_HANDLE_VALUE
;
1548 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
1552 DWORD bufsize
= 512;
1557 buffer
= alloca (bufsize
);
1558 result
= WNetEnumResource (wnet_enum_handle
, &count
, buffer
, &bufsize
);
1559 if (result
!= NO_ERROR
)
1562 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
1563 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
1565 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
1568 strncpy (readbuf
, ptr
, size
);
1573 close_unc_volume (HANDLE henum
)
1575 if (henum
!= INVALID_HANDLE_VALUE
)
1576 WNetCloseEnum (henum
);
1580 unc_volume_file_attributes (char *path
)
1585 henum
= open_unc_volume (path
);
1586 if (henum
== INVALID_HANDLE_VALUE
)
1589 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
1591 close_unc_volume (henum
);
1597 /* Shadow some MSVC runtime functions to map requests for long filenames
1598 to reasonable short names if necessary. This was originally added to
1599 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1603 sys_access (const char * path
, int mode
)
1607 /* MSVC implementation doesn't recognize D_OK. */
1608 path
= map_w32_filename (path
, NULL
);
1609 if (is_unc_volume (path
))
1611 attributes
= unc_volume_file_attributes (path
);
1612 if (attributes
== -1) {
1617 else if ((attributes
= GetFileAttributes (path
)) == -1)
1619 /* Should try mapping GetLastError to errno; for now just indicate
1620 that path doesn't exist. */
1624 if ((mode
& X_OK
) != 0 && !is_exec (path
))
1629 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
1634 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1643 sys_chdir (const char * path
)
1645 return _chdir (map_w32_filename (path
, NULL
));
1649 sys_chmod (const char * path
, int mode
)
1651 return _chmod (map_w32_filename (path
, NULL
), mode
);
1655 sys_creat (const char * path
, int mode
)
1657 return _creat (map_w32_filename (path
, NULL
), mode
);
1661 sys_fopen(const char * path
, const char * mode
)
1665 const char * mode_save
= mode
;
1667 /* Force all file handles to be non-inheritable. This is necessary to
1668 ensure child processes don't unwittingly inherit handles that might
1669 prevent future file access. */
1673 else if (mode
[0] == 'w' || mode
[0] == 'a')
1674 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1678 /* Only do simplistic option parsing. */
1682 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1685 else if (mode
[0] == 'b')
1690 else if (mode
[0] == 't')
1697 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1701 return _fdopen (fd
, mode_save
);
1704 /* This only works on NTFS volumes, but is useful to have. */
1706 sys_link (const char * old
, const char * new)
1710 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
1712 if (old
== NULL
|| new == NULL
)
1718 strcpy (oldname
, map_w32_filename (old
, NULL
));
1719 strcpy (newname
, map_w32_filename (new, NULL
));
1721 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
1722 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1723 if (fileh
!= INVALID_HANDLE_VALUE
)
1727 /* Confusingly, the "alternate" stream name field does not apply
1728 when restoring a hard link, and instead contains the actual
1729 stream data for the link (ie. the name of the link to create).
1730 The WIN32_STREAM_ID structure before the cStreamName field is
1731 the stream header, which is then immediately followed by the
1735 WIN32_STREAM_ID wid
;
1736 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
1739 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
1740 data
.wid
.cStreamName
, MAX_PATH
);
1743 LPVOID context
= NULL
;
1746 data
.wid
.dwStreamId
= BACKUP_LINK
;
1747 data
.wid
.dwStreamAttributes
= 0;
1748 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
1749 data
.wid
.Size
.HighPart
= 0;
1750 data
.wid
.dwStreamNameSize
= 0;
1752 if (BackupWrite (fileh
, (LPBYTE
)&data
,
1753 offsetof (WIN32_STREAM_ID
, cStreamName
)
1754 + data
.wid
.Size
.LowPart
,
1755 &wbytes
, FALSE
, FALSE
, &context
)
1756 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
1763 /* Should try mapping GetLastError to errno; for now just
1764 indicate a general error (eg. links not supported). */
1765 errno
= EINVAL
; // perhaps EMLINK?
1769 CloseHandle (fileh
);
1778 sys_mkdir (const char * path
)
1780 return _mkdir (map_w32_filename (path
, NULL
));
1783 /* Because of long name mapping issues, we need to implement this
1784 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1785 a unique name, instead of setting the input template to an empty
1788 Standard algorithm seems to be use pid or tid with a letter on the
1789 front (in place of the 6 X's) and cycle through the letters to find a
1790 unique name. We extend that to allow any reasonable character as the
1791 first of the 6 X's. */
1793 sys_mktemp (char * template)
1797 unsigned uid
= GetCurrentThreadId ();
1798 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1800 if (template == NULL
)
1802 p
= template + strlen (template);
1804 /* replace up to the last 5 X's with uid in decimal */
1805 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
1807 p
[0] = '0' + uid
% 10;
1811 if (i
< 0 && p
[0] == 'X')
1816 int save_errno
= errno
;
1817 p
[0] = first_char
[i
];
1818 if (sys_access (template, 0) < 0)
1824 while (++i
< sizeof (first_char
));
1827 /* Template is badly formed or else we can't generate a unique name,
1828 so return empty string */
1834 sys_open (const char * path
, int oflag
, int mode
)
1836 const char* mpath
= map_w32_filename (path
, NULL
);
1837 /* Try to open file without _O_CREAT, to be able to write to hidden
1838 and system files. Force all file handles to be
1840 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
1843 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
1847 sys_rename (const char * oldname
, const char * newname
)
1850 char temp
[MAX_PATH
];
1852 /* MoveFile on Windows 95 doesn't correctly change the short file name
1853 alias in a number of circumstances (it is not easy to predict when
1854 just by looking at oldname and newname, unfortunately). In these
1855 cases, renaming through a temporary name avoids the problem.
1857 A second problem on Windows 95 is that renaming through a temp name when
1858 newname is uppercase fails (the final long name ends up in
1859 lowercase, although the short alias might be uppercase) UNLESS the
1860 long temp name is not 8.3.
1862 So, on Windows 95 we always rename through a temp name, and we make sure
1863 the temp name has a long extension to ensure correct renaming. */
1865 strcpy (temp
, map_w32_filename (oldname
, NULL
));
1867 if (os_subtype
== OS_WIN95
)
1873 oldname
= map_w32_filename (oldname
, NULL
);
1874 if (o
= strrchr (oldname
, '\\'))
1877 o
= (char *) oldname
;
1879 if (p
= strrchr (temp
, '\\'))
1886 /* Force temp name to require a manufactured 8.3 alias - this
1887 seems to make the second rename work properly. */
1888 sprintf (p
, "_.%s.%u", o
, i
);
1890 result
= rename (oldname
, temp
);
1892 /* This loop must surely terminate! */
1893 while (result
< 0 && errno
== EEXIST
);
1898 /* Emulate Unix behaviour - newname is deleted if it already exists
1899 (at least if it is a file; don't do this for directories).
1901 Since we mustn't do this if we are just changing the case of the
1902 file name (we would end up deleting the file we are trying to
1903 rename!), we let rename detect if the destination file already
1904 exists - that way we avoid the possible pitfalls of trying to
1905 determine ourselves whether two names really refer to the same
1906 file, which is not always possible in the general case. (Consider
1907 all the permutations of shared or subst'd drives, etc.) */
1909 newname
= map_w32_filename (newname
, NULL
);
1910 result
= rename (temp
, newname
);
1914 && _chmod (newname
, 0666) == 0
1915 && _unlink (newname
) == 0)
1916 result
= rename (temp
, newname
);
1922 sys_rmdir (const char * path
)
1924 return _rmdir (map_w32_filename (path
, NULL
));
1928 sys_unlink (const char * path
)
1930 path
= map_w32_filename (path
, NULL
);
1932 /* On Unix, unlink works without write permission. */
1933 _chmod (path
, 0666);
1934 return _unlink (path
);
1937 static FILETIME utc_base_ft
;
1938 static long double utc_base
;
1939 static int init
= 0;
1942 convert_time (FILETIME ft
)
1948 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1957 st
.wMilliseconds
= 0;
1959 SystemTimeToFileTime (&st
, &utc_base_ft
);
1960 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1961 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1965 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
1968 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
1970 return (time_t) (ret
* 1e-7);
1974 convert_from_time_t (time_t time
, FILETIME
* pft
)
1980 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1989 st
.wMilliseconds
= 0;
1991 SystemTimeToFileTime (&st
, &utc_base_ft
);
1992 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1993 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1997 /* time in 100ns units since 1-Jan-1601 */
1998 tmp
= (long double) time
* 1e7
+ utc_base
;
1999 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
2000 pft
->dwLowDateTime
= (DWORD
) (tmp
- (4096.0 * 1024 * 1024) * pft
->dwHighDateTime
);
2004 /* No reason to keep this; faking inode values either by hashing or even
2005 using the file index from GetInformationByHandle, is not perfect and
2006 so by default Emacs doesn't use the inode values on Windows.
2007 Instead, we now determine file-truename correctly (except for
2008 possible drive aliasing etc). */
2010 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
2012 hashval (const unsigned char * str
)
2017 h
= (h
<< 4) + *str
++;
2023 /* Return the hash value of the canonical pathname, excluding the
2024 drive/UNC header, to get a hopefully unique inode number. */
2026 generate_inode_val (const char * name
)
2028 char fullname
[ MAX_PATH
];
2032 /* Get the truly canonical filename, if it exists. (Note: this
2033 doesn't resolve aliasing due to subst commands, or recognise hard
2035 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
2038 parse_root (fullname
, &p
);
2039 /* Normal W32 filesystems are still case insensitive. */
2046 /* MSVC stat function can't cope with UNC names and has other bugs, so
2047 replace it with our own. This also allows us to calculate consistent
2048 inode values without hacks in the main Emacs code. */
2050 stat (const char * path
, struct stat
* buf
)
2053 WIN32_FIND_DATA wfd
;
2058 int rootdir
= FALSE
;
2060 if (path
== NULL
|| buf
== NULL
)
2066 name
= (char *) map_w32_filename (path
, &path
);
2067 /* must be valid filename, no wild cards or other invalid characters */
2068 if (strpbrk (name
, "*?|<>\""))
2074 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
2075 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
2076 if (IS_DIRECTORY_SEP (r
[0]) && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
2081 /* Remove trailing directory separator, unless name is the root
2082 directory of a drive or UNC volume in which case ensure there
2083 is a trailing separator. */
2084 len
= strlen (name
);
2085 rootdir
= (path
>= name
+ len
- 1
2086 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
2087 name
= strcpy (alloca (len
+ 2), name
);
2089 if (is_unc_volume (name
))
2091 DWORD attrs
= unc_volume_file_attributes (name
);
2096 memset (&wfd
, 0, sizeof (wfd
));
2097 wfd
.dwFileAttributes
= attrs
;
2098 wfd
.ftCreationTime
= utc_base_ft
;
2099 wfd
.ftLastAccessTime
= utc_base_ft
;
2100 wfd
.ftLastWriteTime
= utc_base_ft
;
2101 strcpy (wfd
.cFileName
, name
);
2105 if (!IS_DIRECTORY_SEP (name
[len
-1]))
2106 strcat (name
, "\\");
2107 if (GetDriveType (name
) < 2)
2112 memset (&wfd
, 0, sizeof (wfd
));
2113 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
2114 wfd
.ftCreationTime
= utc_base_ft
;
2115 wfd
.ftLastAccessTime
= utc_base_ft
;
2116 wfd
.ftLastWriteTime
= utc_base_ft
;
2117 strcpy (wfd
.cFileName
, name
);
2121 if (IS_DIRECTORY_SEP (name
[len
-1]))
2124 /* (This is hacky, but helps when doing file completions on
2125 network drives.) Optimize by using information available from
2126 active readdir if possible. */
2127 len
= strlen (dir_pathname
);
2128 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
2130 if (dir_find_handle
!= INVALID_HANDLE_VALUE
2131 && strnicmp (name
, dir_pathname
, len
) == 0
2132 && IS_DIRECTORY_SEP (name
[len
])
2133 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
2135 /* This was the last entry returned by readdir. */
2136 wfd
= dir_find_data
;
2140 fh
= FindFirstFile (name
, &wfd
);
2141 if (fh
== INVALID_HANDLE_VALUE
)
2150 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2152 buf
->st_mode
= _S_IFDIR
;
2153 buf
->st_nlink
= 2; /* doesn't really matter */
2154 fake_inode
= 0; /* this doesn't either I think */
2156 else if (!NILP (Vw32_get_true_file_attributes
)
2157 /* No access rights required to get info. */
2158 && (fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
, 0, NULL
))
2159 != INVALID_HANDLE_VALUE
)
2161 /* This is more accurate in terms of gettting the correct number
2162 of links, but is quite slow (it is noticable when Emacs is
2163 making a list of file name completions). */
2164 BY_HANDLE_FILE_INFORMATION info
;
2166 if (GetFileInformationByHandle (fh
, &info
))
2168 buf
->st_nlink
= info
.nNumberOfLinks
;
2169 /* Might as well use file index to fake inode values, but this
2170 is not guaranteed to be unique unless we keep a handle open
2171 all the time (even then there are situations where it is
2172 not unique). Reputedly, there are at most 48 bits of info
2173 (on NTFS, presumably less on FAT). */
2174 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
2182 switch (GetFileType (fh
))
2184 case FILE_TYPE_DISK
:
2185 buf
->st_mode
= _S_IFREG
;
2187 case FILE_TYPE_PIPE
:
2188 buf
->st_mode
= _S_IFIFO
;
2190 case FILE_TYPE_CHAR
:
2191 case FILE_TYPE_UNKNOWN
:
2193 buf
->st_mode
= _S_IFCHR
;
2199 /* Don't bother to make this information more accurate. */
2200 buf
->st_mode
= _S_IFREG
;
2206 /* Not sure if there is any point in this. */
2207 if (!NILP (Vw32_generate_fake_inodes
))
2208 fake_inode
= generate_inode_val (name
);
2209 else if (fake_inode
== 0)
2211 /* For want of something better, try to make everything unique. */
2212 static DWORD gen_num
= 0;
2213 fake_inode
= ++gen_num
;
2217 /* MSVC defines _ino_t to be short; other libc's might not. */
2218 if (sizeof (buf
->st_ino
) == 2)
2219 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
2221 buf
->st_ino
= fake_inode
;
2223 /* consider files to belong to current user */
2224 buf
->st_uid
= the_passwd
.pw_uid
;
2225 buf
->st_gid
= the_passwd
.pw_gid
;
2227 /* volume_info is set indirectly by map_w32_filename */
2228 buf
->st_dev
= volume_info
.serialnum
;
2229 buf
->st_rdev
= volume_info
.serialnum
;
2232 buf
->st_size
= wfd
.nFileSizeLow
;
2234 /* Convert timestamps to Unix format. */
2235 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
2236 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
2237 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
2238 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
2239 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
2241 /* determine rwx permissions */
2242 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2243 permission
= _S_IREAD
;
2245 permission
= _S_IREAD
| _S_IWRITE
;
2247 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2248 permission
|= _S_IEXEC
;
2249 else if (is_exec (name
))
2250 permission
|= _S_IEXEC
;
2252 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2257 /* Provide fstat and utime as well as stat for consistent handling of
2260 fstat (int desc
, struct stat
* buf
)
2262 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
2263 BY_HANDLE_FILE_INFORMATION info
;
2267 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
2269 case FILE_TYPE_DISK
:
2270 buf
->st_mode
= _S_IFREG
;
2271 if (!GetFileInformationByHandle (fh
, &info
))
2277 case FILE_TYPE_PIPE
:
2278 buf
->st_mode
= _S_IFIFO
;
2280 case FILE_TYPE_CHAR
:
2281 case FILE_TYPE_UNKNOWN
:
2283 buf
->st_mode
= _S_IFCHR
;
2285 memset (&info
, 0, sizeof (info
));
2286 info
.dwFileAttributes
= 0;
2287 info
.ftCreationTime
= utc_base_ft
;
2288 info
.ftLastAccessTime
= utc_base_ft
;
2289 info
.ftLastWriteTime
= utc_base_ft
;
2292 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2294 buf
->st_mode
= _S_IFDIR
;
2295 buf
->st_nlink
= 2; /* doesn't really matter */
2296 fake_inode
= 0; /* this doesn't either I think */
2300 buf
->st_nlink
= info
.nNumberOfLinks
;
2301 /* Might as well use file index to fake inode values, but this
2302 is not guaranteed to be unique unless we keep a handle open
2303 all the time (even then there are situations where it is
2304 not unique). Reputedly, there are at most 48 bits of info
2305 (on NTFS, presumably less on FAT). */
2306 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
2309 /* MSVC defines _ino_t to be short; other libc's might not. */
2310 if (sizeof (buf
->st_ino
) == 2)
2311 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
2313 buf
->st_ino
= fake_inode
;
2315 /* consider files to belong to current user */
2319 buf
->st_dev
= info
.dwVolumeSerialNumber
;
2320 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
2322 buf
->st_size
= info
.nFileSizeLow
;
2324 /* Convert timestamps to Unix format. */
2325 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
2326 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
2327 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
2328 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
2329 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
2331 /* determine rwx permissions */
2332 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2333 permission
= _S_IREAD
;
2335 permission
= _S_IREAD
| _S_IWRITE
;
2337 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2338 permission
|= _S_IEXEC
;
2341 #if 0 /* no way of knowing the filename */
2342 char * p
= strrchr (name
, '.');
2344 (stricmp (p
, ".exe") == 0 ||
2345 stricmp (p
, ".com") == 0 ||
2346 stricmp (p
, ".bat") == 0 ||
2347 stricmp (p
, ".cmd") == 0))
2348 permission
|= _S_IEXEC
;
2352 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2358 utime (const char *name
, struct utimbuf
*times
)
2360 struct utimbuf deftime
;
2367 deftime
.modtime
= deftime
.actime
= time (NULL
);
2371 /* Need write access to set times. */
2372 fh
= CreateFile (name
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
2373 0, OPEN_EXISTING
, 0, NULL
);
2376 convert_from_time_t (times
->actime
, &atime
);
2377 convert_from_time_t (times
->modtime
, &mtime
);
2378 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
2396 /* Wrappers for winsock functions to map between our file descriptors
2397 and winsock's handles; also set h_errno for convenience.
2399 To allow Emacs to run on systems which don't have winsock support
2400 installed, we dynamically link to winsock on startup if present, and
2401 otherwise provide the minimum necessary functionality
2402 (eg. gethostname). */
2404 /* function pointers for relevant socket functions */
2405 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
2406 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
2407 int (PASCAL
*pfn_WSAGetLastError
) (void);
2408 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
2409 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
2410 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
2411 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
2412 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
2413 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
2414 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
2415 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
2416 int (PASCAL
*pfn_WSACleanup
) (void);
2418 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
2419 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
2420 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
2421 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
2422 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
2423 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
2425 /* SetHandleInformation is only needed to make sockets non-inheritable. */
2426 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
2427 #ifndef HANDLE_FLAG_INHERIT
2428 #define HANDLE_FLAG_INHERIT 1
2432 static int winsock_inuse
;
2437 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
2439 /* Not sure what would cause WSAENETDOWN, or even if it can happen
2440 after WSAStartup returns successfully, but it seems reasonable
2441 to allow unloading winsock anyway in that case. */
2442 if (pfn_WSACleanup () == 0 ||
2443 pfn_WSAGetLastError () == WSAENETDOWN
)
2445 if (FreeLibrary (winsock_lib
))
2454 init_winsock (int load_now
)
2456 WSADATA winsockData
;
2458 if (winsock_lib
!= NULL
)
2461 pfn_SetHandleInformation
= NULL
;
2462 pfn_SetHandleInformation
2463 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2464 "SetHandleInformation");
2466 winsock_lib
= LoadLibrary ("wsock32.dll");
2468 if (winsock_lib
!= NULL
)
2470 /* dynamically link to socket functions */
2472 #define LOAD_PROC(fn) \
2473 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2476 LOAD_PROC( WSAStartup
);
2477 LOAD_PROC( WSASetLastError
);
2478 LOAD_PROC( WSAGetLastError
);
2479 LOAD_PROC( socket
);
2481 LOAD_PROC( connect
);
2482 LOAD_PROC( ioctlsocket
);
2485 LOAD_PROC( closesocket
);
2486 LOAD_PROC( shutdown
);
2489 LOAD_PROC( inet_addr
);
2490 LOAD_PROC( gethostname
);
2491 LOAD_PROC( gethostbyname
);
2492 LOAD_PROC( getservbyname
);
2493 LOAD_PROC( WSACleanup
);
2497 /* specify version 1.1 of winsock */
2498 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
2500 if (winsockData
.wVersion
!= 0x101)
2505 /* Report that winsock exists and is usable, but leave
2506 socket functions disabled. I am assuming that calling
2507 WSAStartup does not require any network interaction,
2508 and in particular does not cause or require a dial-up
2509 connection to be established. */
2512 FreeLibrary (winsock_lib
);
2520 FreeLibrary (winsock_lib
);
2530 /* function to set h_errno for compatability; map winsock error codes to
2531 normal system codes where they overlap (non-overlapping definitions
2532 are already in <sys/socket.h> */
2533 static void set_errno ()
2535 if (winsock_lib
== NULL
)
2538 h_errno
= pfn_WSAGetLastError ();
2542 case WSAEACCES
: h_errno
= EACCES
; break;
2543 case WSAEBADF
: h_errno
= EBADF
; break;
2544 case WSAEFAULT
: h_errno
= EFAULT
; break;
2545 case WSAEINTR
: h_errno
= EINTR
; break;
2546 case WSAEINVAL
: h_errno
= EINVAL
; break;
2547 case WSAEMFILE
: h_errno
= EMFILE
; break;
2548 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
2549 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
2554 static void check_errno ()
2556 if (h_errno
== 0 && winsock_lib
!= NULL
)
2557 pfn_WSASetLastError (0);
2560 /* Extend strerror to handle the winsock-specific error codes. */
2564 } _wsa_errlist
[] = {
2565 WSAEINTR
, "Interrupted function call",
2566 WSAEBADF
, "Bad file descriptor",
2567 WSAEACCES
, "Permission denied",
2568 WSAEFAULT
, "Bad address",
2569 WSAEINVAL
, "Invalid argument",
2570 WSAEMFILE
, "Too many open files",
2572 WSAEWOULDBLOCK
, "Resource temporarily unavailable",
2573 WSAEINPROGRESS
, "Operation now in progress",
2574 WSAEALREADY
, "Operation already in progress",
2575 WSAENOTSOCK
, "Socket operation on non-socket",
2576 WSAEDESTADDRREQ
, "Destination address required",
2577 WSAEMSGSIZE
, "Message too long",
2578 WSAEPROTOTYPE
, "Protocol wrong type for socket",
2579 WSAENOPROTOOPT
, "Bad protocol option",
2580 WSAEPROTONOSUPPORT
, "Protocol not supported",
2581 WSAESOCKTNOSUPPORT
, "Socket type not supported",
2582 WSAEOPNOTSUPP
, "Operation not supported",
2583 WSAEPFNOSUPPORT
, "Protocol family not supported",
2584 WSAEAFNOSUPPORT
, "Address family not supported by protocol family",
2585 WSAEADDRINUSE
, "Address already in use",
2586 WSAEADDRNOTAVAIL
, "Cannot assign requested address",
2587 WSAENETDOWN
, "Network is down",
2588 WSAENETUNREACH
, "Network is unreachable",
2589 WSAENETRESET
, "Network dropped connection on reset",
2590 WSAECONNABORTED
, "Software caused connection abort",
2591 WSAECONNRESET
, "Connection reset by peer",
2592 WSAENOBUFS
, "No buffer space available",
2593 WSAEISCONN
, "Socket is already connected",
2594 WSAENOTCONN
, "Socket is not connected",
2595 WSAESHUTDOWN
, "Cannot send after socket shutdown",
2596 WSAETOOMANYREFS
, "Too many references", /* not sure */
2597 WSAETIMEDOUT
, "Connection timed out",
2598 WSAECONNREFUSED
, "Connection refused",
2599 WSAELOOP
, "Network loop", /* not sure */
2600 WSAENAMETOOLONG
, "Name is too long",
2601 WSAEHOSTDOWN
, "Host is down",
2602 WSAEHOSTUNREACH
, "No route to host",
2603 WSAENOTEMPTY
, "Buffer not empty", /* not sure */
2604 WSAEPROCLIM
, "Too many processes",
2605 WSAEUSERS
, "Too many users", /* not sure */
2606 WSAEDQUOT
, "Double quote in host name", /* really not sure */
2607 WSAESTALE
, "Data is stale", /* not sure */
2608 WSAEREMOTE
, "Remote error", /* not sure */
2610 WSASYSNOTREADY
, "Network subsystem is unavailable",
2611 WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range",
2612 WSANOTINITIALISED
, "Winsock not initialized successfully",
2613 WSAEDISCON
, "Graceful shutdown in progress",
2615 WSAENOMORE
, "No more operations allowed", /* not sure */
2616 WSAECANCELLED
, "Operation cancelled", /* not sure */
2617 WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider",
2618 WSAEINVALIDPROVIDER
, "Invalid service provider version number",
2619 WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider",
2620 WSASYSCALLFAILURE
, "System call failured",
2621 WSASERVICE_NOT_FOUND
, "Service not found", /* not sure */
2622 WSATYPE_NOT_FOUND
, "Class type not found",
2623 WSA_E_NO_MORE
, "No more resources available", /* really not sure */
2624 WSA_E_CANCELLED
, "Operation already cancelled", /* really not sure */
2625 WSAEREFUSED
, "Operation refused", /* not sure */
2628 WSAHOST_NOT_FOUND
, "Host not found",
2629 WSATRY_AGAIN
, "Authoritative host not found during name lookup",
2630 WSANO_RECOVERY
, "Non-recoverable error during name lookup",
2631 WSANO_DATA
, "Valid name, no data record of requested type",
2637 sys_strerror(int error_no
)
2640 static char unknown_msg
[40];
2642 if (error_no
>= 0 && error_no
< sys_nerr
)
2643 return sys_errlist
[error_no
];
2645 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
2646 if (_wsa_errlist
[i
].errnum
== error_no
)
2647 return _wsa_errlist
[i
].msg
;
2649 sprintf(unknown_msg
, "Unidentified error: %d", error_no
);
2653 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2654 but I believe the method of keeping the socket handle separate (and
2655 insuring it is not inheritable) is the correct one. */
2657 //#define SOCK_REPLACE_HANDLE
2659 #ifdef SOCK_REPLACE_HANDLE
2660 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2662 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2666 sys_socket(int af
, int type
, int protocol
)
2672 if (winsock_lib
== NULL
)
2675 return INVALID_SOCKET
;
2680 /* call the real socket function */
2681 s
= (long) pfn_socket (af
, type
, protocol
);
2683 if (s
!= INVALID_SOCKET
)
2685 /* Although under NT 3.5 _open_osfhandle will accept a socket
2686 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2687 that does not work under NT 3.1. However, we can get the same
2688 effect by using a backdoor function to replace an existing
2689 descriptor handle with the one we want. */
2691 /* allocate a file descriptor (with appropriate flags) */
2692 fd
= _open ("NUL:", _O_RDWR
);
2695 #ifdef SOCK_REPLACE_HANDLE
2696 /* now replace handle to NUL with our socket handle */
2697 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
2699 _set_osfhnd (fd
, s
);
2700 /* setmode (fd, _O_BINARY); */
2702 /* Make a non-inheritable copy of the socket handle. Note
2703 that it is possible that sockets aren't actually kernel
2704 handles, which appears to be the case on Windows 9x when
2705 the MS Proxy winsock client is installed. */
2707 /* Apparently there is a bug in NT 3.51 with some service
2708 packs, which prevents using DuplicateHandle to make a
2709 socket handle non-inheritable (causes WSACleanup to
2710 hang). The work-around is to use SetHandleInformation
2711 instead if it is available and implemented. */
2712 if (pfn_SetHandleInformation
)
2714 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
2718 HANDLE parent
= GetCurrentProcess ();
2719 HANDLE new_s
= INVALID_HANDLE_VALUE
;
2721 if (DuplicateHandle (parent
,
2727 DUPLICATE_SAME_ACCESS
))
2729 /* It is possible that DuplicateHandle succeeds even
2730 though the socket wasn't really a kernel handle,
2731 because a real handle has the same value. So
2732 test whether the new handle really is a socket. */
2733 long nonblocking
= 0;
2734 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
2736 pfn_closesocket (s
);
2741 CloseHandle (new_s
);
2746 fd_info
[fd
].hnd
= (HANDLE
) s
;
2749 /* set our own internal flags */
2750 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
2756 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2758 /* attach child_process to fd_info */
2759 if (fd_info
[ fd
].cp
!= NULL
)
2761 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
2765 fd_info
[ fd
].cp
= cp
;
2768 winsock_inuse
++; /* count open sockets */
2775 pfn_closesocket (s
);
2785 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
2787 if (winsock_lib
== NULL
)
2790 return SOCKET_ERROR
;
2794 if (fd_info
[s
].flags
& FILE_SOCKET
)
2796 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
2797 if (rc
== SOCKET_ERROR
)
2802 return SOCKET_ERROR
;
2807 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
2809 if (winsock_lib
== NULL
)
2812 return SOCKET_ERROR
;
2816 if (fd_info
[s
].flags
& FILE_SOCKET
)
2818 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
2819 if (rc
== SOCKET_ERROR
)
2824 return SOCKET_ERROR
;
2828 sys_htons (u_short hostshort
)
2830 return (winsock_lib
!= NULL
) ?
2831 pfn_htons (hostshort
) : hostshort
;
2835 sys_ntohs (u_short netshort
)
2837 return (winsock_lib
!= NULL
) ?
2838 pfn_ntohs (netshort
) : netshort
;
2842 sys_inet_addr (const char * cp
)
2844 return (winsock_lib
!= NULL
) ?
2845 pfn_inet_addr (cp
) : INADDR_NONE
;
2849 sys_gethostname (char * name
, int namelen
)
2851 if (winsock_lib
!= NULL
)
2852 return pfn_gethostname (name
, namelen
);
2854 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
2855 return !GetComputerName (name
, (DWORD
*)&namelen
);
2858 return SOCKET_ERROR
;
2862 sys_gethostbyname(const char * name
)
2864 struct hostent
* host
;
2866 if (winsock_lib
== NULL
)
2873 host
= pfn_gethostbyname (name
);
2880 sys_getservbyname(const char * name
, const char * proto
)
2882 struct servent
* serv
;
2884 if (winsock_lib
== NULL
)
2891 serv
= pfn_getservbyname (name
, proto
);
2898 sys_shutdown (int s
, int how
)
2900 if (winsock_lib
== NULL
)
2903 return SOCKET_ERROR
;
2907 if (fd_info
[s
].flags
& FILE_SOCKET
)
2909 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
2910 if (rc
== SOCKET_ERROR
)
2915 return SOCKET_ERROR
;
2918 #endif /* HAVE_SOCKETS */
2921 /* Shadow main io functions: we need to handle pipes and sockets more
2922 intelligently, and implement non-blocking mode as well. */
2929 if (fd
< 0 || fd
>= MAXDESC
)
2937 child_process
* cp
= fd_info
[fd
].cp
;
2939 fd_info
[fd
].cp
= NULL
;
2941 if (CHILD_ACTIVE (cp
))
2943 /* if last descriptor to active child_process then cleanup */
2945 for (i
= 0; i
< MAXDESC
; i
++)
2949 if (fd_info
[i
].cp
== cp
)
2955 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2957 #ifndef SOCK_REPLACE_HANDLE
2958 if (winsock_lib
== NULL
) abort ();
2960 pfn_shutdown (SOCK_HANDLE (fd
), 2);
2961 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
2963 winsock_inuse
--; /* count open sockets */
2971 /* Note that sockets do not need special treatment here (at least on
2972 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2973 closesocket is equivalent to CloseHandle, which is to be expected
2974 because socket handles are fully fledged kernel handles. */
2978 fd_info
[fd
].flags
= 0;
2991 /* duplicate our internal info as well */
2992 fd_info
[new_fd
] = fd_info
[fd
];
2999 sys_dup2 (int src
, int dst
)
3003 if (dst
< 0 || dst
>= MAXDESC
)
3009 /* make sure we close the destination first if it's a pipe or socket */
3010 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
3013 rc
= _dup2 (src
, dst
);
3016 /* duplicate our internal info as well */
3017 fd_info
[dst
] = fd_info
[src
];
3022 /* Unix pipe() has only one arg */
3024 sys_pipe (int * phandles
)
3029 /* make pipe handles non-inheritable; when we spawn a child, we
3030 replace the relevant handle with an inheritable one. Also put
3031 pipes into binary mode; we will do text mode translation ourselves
3033 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
3037 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
3038 fd_info
[phandles
[0]].flags
= flags
;
3040 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
3041 fd_info
[phandles
[1]].flags
= flags
;
3048 extern Lisp_Object Vw32_pipe_read_delay
;
3050 /* Function to do blocking read of one byte, needed to implement
3051 select. It is only allowed on sockets and pipes. */
3053 _sys_read_ahead (int fd
)
3058 if (fd
< 0 || fd
>= MAXDESC
)
3059 return STATUS_READ_ERROR
;
3061 cp
= fd_info
[fd
].cp
;
3063 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
3064 return STATUS_READ_ERROR
;
3066 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
3067 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
3069 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
3073 cp
->status
= STATUS_READ_IN_PROGRESS
;
3075 if (fd_info
[fd
].flags
& FILE_PIPE
)
3077 rc
= _read (fd
, &cp
->chr
, sizeof (char));
3079 /* Give subprocess time to buffer some more output for us before
3080 reporting that input is available; we need this because Windows 95
3081 connects DOS programs to pipes by making the pipe appear to be
3082 the normal console stdout - as a result most DOS programs will
3083 write to stdout without buffering, ie. one character at a
3084 time. Even some W32 programs do this - "dir" in a command
3085 shell on NT is very slow if we don't do this. */
3088 int wait
= XINT (Vw32_pipe_read_delay
);
3094 /* Yield remainder of our time slice, effectively giving a
3095 temporary priority boost to the child process. */
3100 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
3101 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
3104 if (rc
== sizeof (char))
3105 cp
->status
= STATUS_READ_SUCCEEDED
;
3107 cp
->status
= STATUS_READ_FAILED
;
3113 sys_read (int fd
, char * buffer
, unsigned int count
)
3118 char * orig_buffer
= buffer
;
3120 if (fd
< 0 || fd
>= MAXDESC
)
3126 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3128 child_process
*cp
= fd_info
[fd
].cp
;
3130 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
3138 /* re-read CR carried over from last read */
3139 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
3141 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
3145 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
3148 /* presence of a child_process structure means we are operating in
3149 non-blocking mode - otherwise we just call _read directly.
3150 Note that the child_process structure might be missing because
3151 reap_subprocess has been called; in this case the pipe is
3152 already broken, so calling _read on it is okay. */
3155 int current_status
= cp
->status
;
3157 switch (current_status
)
3159 case STATUS_READ_FAILED
:
3160 case STATUS_READ_ERROR
:
3161 /* report normal EOF if nothing in buffer */
3163 fd_info
[fd
].flags
|= FILE_AT_EOF
;
3166 case STATUS_READ_READY
:
3167 case STATUS_READ_IN_PROGRESS
:
3168 DebPrint (("sys_read called when read is in progress\n"));
3169 errno
= EWOULDBLOCK
;
3172 case STATUS_READ_SUCCEEDED
:
3173 /* consume read-ahead char */
3174 *buffer
++ = cp
->chr
;
3177 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3178 ResetEvent (cp
->char_avail
);
3180 case STATUS_READ_ACKNOWLEDGED
:
3184 DebPrint (("sys_read: bad status %d\n", current_status
));
3189 if (fd_info
[fd
].flags
& FILE_PIPE
)
3191 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
3192 to_read
= min (waiting
, (DWORD
) count
);
3195 nchars
+= _read (fd
, buffer
, to_read
);
3198 else /* FILE_SOCKET */
3200 if (winsock_lib
== NULL
) abort ();
3202 /* do the equivalent of a non-blocking read */
3203 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
3204 if (waiting
== 0 && nchars
== 0)
3206 h_errno
= errno
= EWOULDBLOCK
;
3212 /* always use binary mode for sockets */
3213 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
3214 if (res
== SOCKET_ERROR
)
3216 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
3217 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3228 int nread
= _read (fd
, buffer
, count
);
3231 else if (nchars
== 0)
3236 fd_info
[fd
].flags
|= FILE_AT_EOF
;
3237 /* Perform text mode translation if required. */
3238 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
3240 nchars
= crlf_to_lf (nchars
, orig_buffer
);
3241 /* If buffer contains only CR, return that. To be absolutely
3242 sure we should attempt to read the next char, but in
3243 practice a CR to be followed by LF would not appear by
3244 itself in the buffer. */
3245 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
3247 fd_info
[fd
].flags
|= FILE_LAST_CR
;
3253 nchars
= _read (fd
, buffer
, count
);
3258 /* For now, don't bother with a non-blocking mode */
3260 sys_write (int fd
, const void * buffer
, unsigned int count
)
3264 if (fd
< 0 || fd
>= MAXDESC
)
3270 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3272 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
3278 /* Perform text mode translation if required. */
3279 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
3281 char * tmpbuf
= alloca (count
* 2);
3282 unsigned char * src
= (void *)buffer
;
3283 unsigned char * dst
= tmpbuf
;
3288 unsigned char *next
;
3289 /* copy next line or remaining bytes */
3290 next
= _memccpy (dst
, src
, '\n', nbytes
);
3293 /* copied one line ending with '\n' */
3294 int copied
= next
- dst
;
3297 /* insert '\r' before '\n' */
3304 /* copied remaining partial line -> now finished */
3312 if (fd_info
[fd
].flags
& FILE_SOCKET
)
3314 if (winsock_lib
== NULL
) abort ();
3315 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
3316 if (nchars
== SOCKET_ERROR
)
3318 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
3319 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3325 nchars
= _write (fd
, buffer
, count
);
3331 check_windows_init_file ()
3333 extern int noninteractive
, inhibit_window_system
;
3335 /* A common indication that Emacs is not installed properly is when
3336 it cannot find the Windows installation file. If this file does
3337 not exist in the expected place, tell the user. */
3339 if (!noninteractive
&& !inhibit_window_system
)
3341 extern Lisp_Object Vwindow_system
, Vload_path
, Qfile_exists_p
;
3342 Lisp_Object objs
[2];
3343 Lisp_Object full_load_path
;
3344 Lisp_Object init_file
;
3347 objs
[0] = Vload_path
;
3348 objs
[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
3349 full_load_path
= Fappend (2, objs
);
3350 init_file
= build_string ("term/w32-win");
3351 fd
= openp (full_load_path
, init_file
, Vload_suffixes
, NULL
, 0);
3354 Lisp_Object load_path_print
= Fprin1_to_string (full_load_path
, Qnil
);
3355 char *init_file_name
= XSTRING (init_file
)->data
;
3356 char *load_path
= XSTRING (load_path_print
)->data
;
3357 char *buffer
= alloca (1024);
3360 "The Emacs Windows initialization file \"%s.el\" "
3361 "could not be found in your Emacs installation. "
3362 "Emacs checked the following directories for this file:\n"
3364 "When Emacs cannot find this file, it usually means that it "
3365 "was not installed properly, or its distribution file was "
3366 "not unpacked properly.\nSee the README.W32 file in the "
3367 "top-level Emacs directory for more information.",
3368 init_file_name
, load_path
);
3371 "Emacs Abort Dialog",
3372 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
3373 /* Use the low-level Emacs abort. */
3388 /* shutdown the socket interface if necessary */
3397 /* Initialise the socket interface now if available and requested by
3398 the user by defining PRELOAD_WINSOCK; otherwise loading will be
3399 delayed until open-network-stream is called (w32-has-winsock can
3400 also be used to dynamically load or reload winsock).
3402 Conveniently, init_environment is called before us, so
3403 PRELOAD_WINSOCK can be set in the registry. */
3405 /* Always initialize this correctly. */
3408 if (getenv ("PRELOAD_WINSOCK") != NULL
)
3409 init_winsock (TRUE
);
3412 /* Initial preparation for subprocess support: replace our standard
3413 handles with non-inheritable versions. */
3416 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
3417 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
3418 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
3420 parent
= GetCurrentProcess ();
3422 /* ignore errors when duplicating and closing; typically the
3423 handles will be invalid when running as a gui program. */
3424 DuplicateHandle (parent
,
3425 GetStdHandle (STD_INPUT_HANDLE
),
3430 DUPLICATE_SAME_ACCESS
);
3432 DuplicateHandle (parent
,
3433 GetStdHandle (STD_OUTPUT_HANDLE
),
3438 DUPLICATE_SAME_ACCESS
);
3440 DuplicateHandle (parent
,
3441 GetStdHandle (STD_ERROR_HANDLE
),
3446 DUPLICATE_SAME_ACCESS
);
3452 if (stdin_save
!= INVALID_HANDLE_VALUE
)
3453 _open_osfhandle ((long) stdin_save
, O_TEXT
);
3455 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
3458 if (stdout_save
!= INVALID_HANDLE_VALUE
)
3459 _open_osfhandle ((long) stdout_save
, O_TEXT
);
3461 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
3464 if (stderr_save
!= INVALID_HANDLE_VALUE
)
3465 _open_osfhandle ((long) stderr_save
, O_TEXT
);
3467 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
3471 /* unfortunately, atexit depends on implementation of malloc */
3472 /* atexit (term_ntproc); */
3473 signal (SIGABRT
, term_ntproc
);
3475 /* determine which drives are fixed, for GetCachedVolumeInformation */
3477 /* GetDriveType must have trailing backslash. */
3478 char drive
[] = "A:\\";
3480 /* Loop over all possible drive letters */
3481 while (*drive
<= 'Z')
3483 /* Record if this drive letter refers to a fixed drive. */
3484 fixed_drives
[DRIVE_INDEX (*drive
)] =
3485 (GetDriveType (drive
) == DRIVE_FIXED
);
3490 /* Reset the volume info cache. */
3491 volume_cache
= NULL
;
3494 /* Check to see if Emacs has been installed correctly. */
3495 check_windows_init_file ();