1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995 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 */
67 #define _ANONYMOUS_UNION
68 #define _ANONYMOUS_STRUCT
72 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
73 #include <sys/socket.h>
92 #define min(x, y) (((x) < (y)) ? (x) : (y))
93 #define max(x, y) (((x) > (y)) ? (x) : (y))
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
;
100 static char startup_dir
[MAXPATHLEN
];
102 /* Get the current working directory. */
107 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
111 /* Emacs doesn't actually change directory itself, and we want to
112 force our real wd to be where emacs.exe is to avoid unnecessary
113 conflicts when trying to rename or delete directories. */
114 strcpy (dir
, startup_dir
);
120 /* Emulate gethostname. */
122 gethostname (char *buffer
, int size
)
124 /* NT only allows small host names, so the buffer is
125 certainly large enough. */
126 return !GetComputerName (buffer
, &size
);
128 #endif /* HAVE_SOCKETS */
130 /* Emulate getloadavg. */
132 getloadavg (double loadavg
[], int nelem
)
136 /* A faithful emulation is going to have to be saved for a rainy day. */
137 for (i
= 0; i
< nelem
; i
++)
144 /* Emulate getpwuid, getpwnam and others. */
146 #define PASSWD_FIELD_SIZE 256
148 static char the_passwd_name
[PASSWD_FIELD_SIZE
];
149 static char the_passwd_passwd
[PASSWD_FIELD_SIZE
];
150 static char the_passwd_gecos
[PASSWD_FIELD_SIZE
];
151 static char the_passwd_dir
[PASSWD_FIELD_SIZE
];
152 static char the_passwd_shell
[PASSWD_FIELD_SIZE
];
154 static struct passwd the_passwd
=
169 return the_passwd
.pw_uid
;
175 /* I could imagine arguing for checking to see whether the user is
176 in the Administrators group and returning a UID of 0 for that
177 case, but I don't know how wise that would be in the long run. */
184 return the_passwd
.pw_gid
;
196 if (uid
== the_passwd
.pw_uid
)
202 getpwnam (char *name
)
206 pw
= getpwuid (getuid ());
210 if (stricmp (name
, pw
->pw_name
))
219 /* Find the user's real name by opening the process token and
220 looking up the name associated with the user-sid in that token.
222 Use the relative portion of the identifier authority value from
223 the user-sid as the user id value (same for group id using the
224 primary group sid from the process token). */
226 char user_sid
[256], name
[256], domain
[256];
227 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
229 SID_NAME_USE user_type
;
231 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &token
)
232 && GetTokenInformation (token
, TokenUser
,
233 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
234 && LookupAccountSid (NULL
, *((PSID
*) user_sid
), name
, &length
,
235 domain
, &dlength
, &user_type
))
237 strcpy (the_passwd
.pw_name
, name
);
238 /* Determine a reasonable uid value. */
239 if (stricmp ("administrator", name
) == 0)
241 the_passwd
.pw_uid
= 0;
242 the_passwd
.pw_gid
= 0;
246 SID_IDENTIFIER_AUTHORITY
* pSIA
;
248 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
249 /* I believe the relative portion is the last 4 bytes (of 6)
251 the_passwd
.pw_uid
= ((pSIA
->Value
[2] << 24) +
252 (pSIA
->Value
[3] << 16) +
253 (pSIA
->Value
[4] << 8) +
254 (pSIA
->Value
[5] << 0));
255 /* restrict to conventional uid range for normal users */
256 the_passwd
.pw_uid
= the_passwd
.pw_uid
% 60001;
259 if (GetTokenInformation (token
, TokenPrimaryGroup
,
260 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
262 SID_IDENTIFIER_AUTHORITY
* pSIA
;
264 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
265 the_passwd
.pw_gid
= ((pSIA
->Value
[2] << 24) +
266 (pSIA
->Value
[3] << 16) +
267 (pSIA
->Value
[4] << 8) +
268 (pSIA
->Value
[5] << 0));
269 /* I don't know if this is necessary, but for safety... */
270 the_passwd
.pw_gid
= the_passwd
.pw_gid
% 60001;
273 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
276 /* If security calls are not supported (presumably because we
277 are running under Windows 95), fallback to this. */
278 else if (GetUserName (name
, &length
))
280 strcpy (the_passwd
.pw_name
, name
);
281 if (stricmp ("administrator", name
) == 0)
282 the_passwd
.pw_uid
= 0;
284 the_passwd
.pw_uid
= 123;
285 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
289 strcpy (the_passwd
.pw_name
, "unknown");
290 the_passwd
.pw_uid
= 123;
291 the_passwd
.pw_gid
= 123;
294 /* Ensure HOME and SHELL are defined. */
295 if (getenv ("HOME") == NULL
)
297 if (getenv ("SHELL") == NULL
)
300 /* Set dir and shell from environment variables. */
301 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
302 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
311 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
312 return ((rand () << 15) | rand ());
322 /* Normalize filename by converting all path separators to
323 the specified separator. Also conditionally convert upper
324 case path name components to lower case. */
327 normalize_filename (fp
, path_sep
)
334 /* Always lower-case drive letters a-z, even if the filesystem
335 preserves case in filenames.
336 This is so filenames can be compared by string comparison
337 functions that are case-sensitive. Even case-preserving filesystems
338 do not distinguish case in drive letters. */
339 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
345 if (NILP (Vw32_downcase_file_names
))
349 if (*fp
== '/' || *fp
== '\\')
356 sep
= path_sep
; /* convert to this path separator */
357 elem
= fp
; /* start of current path element */
360 if (*fp
>= 'a' && *fp
<= 'z')
361 elem
= 0; /* don't convert this element */
363 if (*fp
== 0 || *fp
== ':')
365 sep
= *fp
; /* restore current separator (or 0) */
366 *fp
= '/'; /* after conversion of this element */
369 if (*fp
== '/' || *fp
== '\\')
371 if (elem
&& elem
!= fp
)
373 *fp
= 0; /* temporary end of string */
374 _strlwr (elem
); /* while we convert to lower case */
376 *fp
= sep
; /* convert (or restore) path separator */
377 elem
= fp
+ 1; /* next element starts after separator */
383 /* Destructively turn backslashes into slashes. */
385 dostounix_filename (p
)
388 normalize_filename (p
, '/');
391 /* Destructively turn slashes into backslashes. */
393 unixtodos_filename (p
)
396 normalize_filename (p
, '\\');
399 /* Remove all CR's that are followed by a LF.
400 (From msdos.c...probably should figure out a way to share it,
401 although this code isn't going to ever change.) */
405 register unsigned char *buf
;
407 unsigned char *np
= buf
;
408 unsigned char *startp
= buf
;
409 unsigned char *endp
= buf
+ n
;
413 while (buf
< endp
- 1)
417 if (*(++buf
) != 0x0a)
428 /* Parse the root part of file name, if present. Return length and
429 optionally store pointer to char after root. */
431 parse_root (char * name
, char ** pPath
)
438 /* find the root name of the volume if given */
439 if (isalpha (name
[0]) && name
[1] == ':')
441 /* skip past drive specifier */
443 if (IS_DIRECTORY_SEP (name
[0]))
446 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
452 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
457 if (IS_DIRECTORY_SEP (name
[0]))
467 /* Get long base name for name; name is assumed to be absolute. */
469 get_long_basename (char * name
, char * buf
, int size
)
471 WIN32_FIND_DATA find_data
;
475 /* must be valid filename, no wild cards or other invalid characters */
476 if (strpbrk (name
, "*?|<>\""))
479 dir_handle
= FindFirstFile (name
, &find_data
);
480 if (dir_handle
!= INVALID_HANDLE_VALUE
)
482 if ((len
= strlen (find_data
.cFileName
)) < size
)
483 memcpy (buf
, find_data
.cFileName
, len
+ 1);
486 FindClose (dir_handle
);
491 /* Get long name for file, if possible (assumed to be absolute). */
493 w32_get_long_filename (char * name
, char * buf
, int size
)
498 char full
[ MAX_PATH
];
505 /* Use local copy for destructive modification. */
506 memcpy (full
, name
, len
+1);
507 unixtodos_filename (full
);
509 /* Copy root part verbatim. */
510 len
= parse_root (full
, &p
);
511 memcpy (o
, full
, len
);
516 while (p
!= NULL
&& *p
)
519 p
= strchr (q
, '\\');
521 len
= get_long_basename (full
, o
, size
);
544 is_unc_volume (const char *filename
)
546 const char *ptr
= filename
;
548 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
551 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
557 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
560 sigsetmask (int signal_mask
)
584 setpgrp (int pid
, int gid
)
596 unrequest_sigio (void)
607 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
610 w32_get_resource (key
, lpdwtype
)
615 HKEY hrootkey
= NULL
;
619 /* Check both the current user and the local machine to see if
620 we have any resources. */
622 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
626 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
627 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
628 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
633 if (lpvalue
) xfree (lpvalue
);
635 RegCloseKey (hrootkey
);
638 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
642 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
643 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
644 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
649 if (lpvalue
) xfree (lpvalue
);
651 RegCloseKey (hrootkey
);
657 char *get_emacs_configuration (void);
658 extern Lisp_Object Vsystem_configuration
;
661 init_environment (char ** argv
)
664 static const char * const tempdirs
[] = {
665 "$TMPDIR", "$TEMP", "$TMP", "c:/"
668 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
670 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
671 temporary files and assume "/tmp" if $TMPDIR is unset, which
672 will break on DOS/Windows. Refuse to work if we cannot find
673 a directory, not even "c:/", usable for that purpose. */
674 for (i
= 0; i
< imax
; i
++)
676 const char *tmp
= tempdirs
[i
];
679 tmp
= getenv (tmp
+ 1);
680 /* Note that `access' can lie to us if the directory resides on a
681 read-only filesystem, like CD-ROM or a write-protected floppy.
682 The only way to be really sure is to actually create a file and
683 see if it succeeds. But I think that's too much to ask. */
684 if (tmp
&& _access (tmp
, D_OK
) == 0)
686 char * var
= alloca (strlen (tmp
) + 8);
687 sprintf (var
, "TMPDIR=%s", tmp
);
695 Fcons (build_string ("no usable temporary directories found!!"),
697 "While setting TMPDIR: ");
699 /* Check for environment variables and use registry settings if they
700 don't exist. Fallback on default values where applicable. */
706 static struct env_entry
713 {"PRELOAD_WINSOCK", NULL
},
714 {"emacs_dir", "C:/emacs"},
715 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
716 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
717 {"EMACSDATA", "%emacs_dir%/etc"},
718 {"EMACSPATH", "%emacs_dir%/bin"},
719 {"EMACSLOCKDIR", "%emacs_dir%/lock"},
720 /* We no longer set INFOPATH because Info-default-directory-list
722 /* {"INFOPATH", "%emacs_dir%/info"}, */
723 {"EMACSDOC", "%emacs_dir%/etc"},
727 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
729 /* Treat emacs_dir specially: set it unconditionally based on our
730 location, if it appears that we are running from the bin subdir
731 of a standard installation. */
734 char modname
[MAX_PATH
];
736 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
738 if ((p
= strrchr (modname
, '\\')) == NULL
)
742 if ((p
= strrchr (modname
, '\\')) && stricmp (p
, "\\bin") == 0)
744 char buf
[SET_ENV_BUF_SIZE
];
747 for (p
= modname
; *p
; p
++)
748 if (*p
== '\\') *p
= '/';
750 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
751 _putenv (strdup (buf
));
755 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
757 if (!getenv (env_vars
[i
].name
))
761 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
)
763 lpval
= env_vars
[i
].def_value
;
764 dwType
= REG_EXPAND_SZ
;
770 if (dwType
== REG_EXPAND_SZ
)
772 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
774 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof(buf1
));
775 _snprintf (buf2
, sizeof(buf2
)-1, "%s=%s", env_vars
[i
].name
, buf1
);
776 _putenv (strdup (buf2
));
778 else if (dwType
== REG_SZ
)
780 char buf
[SET_ENV_BUF_SIZE
];
782 _snprintf (buf
, sizeof(buf
)-1, "%s=%s", env_vars
[i
].name
, lpval
);
783 _putenv (strdup (buf
));
793 /* Rebuild system configuration to reflect invoking system. */
794 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
796 /* Another special case: on NT, the PATH variable is actually named
797 "Path" although cmd.exe (perhaps NT itself) arranges for
798 environment variable lookup and setting to be case insensitive.
799 However, Emacs assumes a fully case sensitive environment, so we
800 need to change "Path" to "PATH" to match the expectations of
801 various elisp packages. We do this by the sneaky method of
802 modifying the string in the C runtime environ entry.
804 The same applies to COMSPEC. */
808 for (envp
= environ
; *envp
; envp
++)
809 if (_strnicmp (*envp
, "PATH=", 5) == 0)
810 memcpy (*envp
, "PATH=", 5);
811 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
812 memcpy (*envp
, "COMSPEC=", 8);
815 /* Remember the initial working directory for getwd, then make the
816 real wd be the location of emacs.exe to avoid conflicts when
817 renaming or deleting directories. (We also don't call chdir when
818 running subprocesses for the same reason.) */
819 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
824 static char modname
[MAX_PATH
];
826 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
828 if ((p
= strrchr (modname
, '\\')) == NULL
)
832 SetCurrentDirectory (modname
);
834 /* Ensure argv[0] has the full path to Emacs. */
839 /* Determine if there is a middle mouse button, to allow parse_button
840 to decide whether right mouse events should be mouse-2 or
842 XSETINT (Vw32_num_mouse_buttons
, GetSystemMetrics (SM_CMOUSEBUTTONS
));
847 /* We don't have scripts to automatically determine the system configuration
848 for Emacs before it's compiled, and we don't want to have to make the
849 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
853 get_emacs_configuration (void)
855 char *arch
, *oem
, *os
;
857 static char configuration_buffer
[32];
859 /* Determine the processor type. */
860 switch (get_processor_type ())
863 #ifdef PROCESSOR_INTEL_386
864 case PROCESSOR_INTEL_386
:
865 case PROCESSOR_INTEL_486
:
866 case PROCESSOR_INTEL_PENTIUM
:
871 #ifdef PROCESSOR_INTEL_860
872 case PROCESSOR_INTEL_860
:
877 #ifdef PROCESSOR_MIPS_R2000
878 case PROCESSOR_MIPS_R2000
:
879 case PROCESSOR_MIPS_R3000
:
880 case PROCESSOR_MIPS_R4000
:
885 #ifdef PROCESSOR_ALPHA_21064
886 case PROCESSOR_ALPHA_21064
:
896 /* Use the OEM field to reflect the compiler/library combination. */
898 #define COMPILER_NAME "msvc"
901 #define COMPILER_NAME "mingw"
903 #define COMPILER_NAME "unknown"
908 switch (osinfo_cache
.dwPlatformId
) {
909 case VER_PLATFORM_WIN32_NT
:
911 build_num
= osinfo_cache
.dwBuildNumber
;
913 case VER_PLATFORM_WIN32_WINDOWS
:
914 if (osinfo_cache
.dwMinorVersion
== 0) {
919 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
921 case VER_PLATFORM_WIN32s
:
922 /* Not supported, should not happen. */
924 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
932 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
933 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
934 get_w32_major_version (), get_w32_minor_version (), build_num
);
936 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
939 return configuration_buffer
;
943 get_emacs_configuration_options (void)
945 static char options_buffer
[256];
947 /* Work out the effective configure options for this build. */
949 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
952 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
954 #define COMPILER_VERSION ""
958 sprintf (options_buffer
, COMPILER_VERSION
);
960 strcat (options_buffer
, " --no-opt");
963 strcat (options_buffer
, " --cflags");
964 strcat (options_buffer
, USER_CFLAGS
);
967 strcat (options_buffer
, " --ldflags");
968 strcat (options_buffer
, USER_LDFLAGS
);
970 return options_buffer
;
974 #include <sys/timeb.h>
976 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
978 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
983 tv
->tv_sec
= tb
.time
;
984 tv
->tv_usec
= tb
.millitm
* 1000L;
987 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
988 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
992 /* ------------------------------------------------------------------------- */
993 /* IO support and wrapper functions for W32 API. */
994 /* ------------------------------------------------------------------------- */
996 /* Place a wrapper around the MSVC version of ctime. It returns NULL
997 on network directories, so we handle that case here.
998 (Ulrich Leodolter, 1/11/95). */
1000 sys_ctime (const time_t *t
)
1002 char *str
= (char *) ctime (t
);
1003 return (str
? str
: "Sun Jan 01 00:00:00 1970");
1006 /* Emulate sleep...we could have done this with a define, but that
1007 would necessitate including windows.h in the files that used it.
1008 This is much easier. */
1010 sys_sleep (int seconds
)
1012 Sleep (seconds
* 1000);
1015 /* Internal MSVC functions for low-level descriptor munging */
1016 extern int __cdecl
_set_osfhnd (int fd
, long h
);
1017 extern int __cdecl
_free_osfhnd (int fd
);
1019 /* parallel array of private info on file handles */
1020 filedesc fd_info
[ MAXDESC
];
1022 typedef struct volume_info_data
{
1023 struct volume_info_data
* next
;
1025 /* time when info was obtained */
1028 /* actual volume info */
1037 /* Global referenced by various functions. */
1038 static volume_info_data volume_info
;
1040 /* Vector to indicate which drives are local and fixed (for which cached
1041 data never expires). */
1042 static BOOL fixed_drives
[26];
1044 /* Consider cached volume information to be stale if older than 10s,
1045 at least for non-local drives. Info for fixed drives is never stale. */
1046 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
1047 #define VOLINFO_STILL_VALID( root_dir, info ) \
1048 ( ( isalpha (root_dir[0]) && \
1049 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
1050 || GetTickCount () - info->timestamp < 10000 )
1052 /* Cache support functions. */
1054 /* Simple linked list with linear search is sufficient. */
1055 static volume_info_data
*volume_cache
= NULL
;
1057 static volume_info_data
*
1058 lookup_volume_info (char * root_dir
)
1060 volume_info_data
* info
;
1062 for (info
= volume_cache
; info
; info
= info
->next
)
1063 if (stricmp (info
->root_dir
, root_dir
) == 0)
1069 add_volume_info (char * root_dir
, volume_info_data
* info
)
1071 info
->root_dir
= xstrdup (root_dir
);
1072 info
->next
= volume_cache
;
1073 volume_cache
= info
;
1077 /* Wrapper for GetVolumeInformation, which uses caching to avoid
1078 performance penalty (~2ms on 486 for local drives, 7.5ms for local
1079 cdrom drive, ~5-10ms or more for remote drives on LAN). */
1081 GetCachedVolumeInformation (char * root_dir
)
1083 volume_info_data
* info
;
1084 char default_root
[ MAX_PATH
];
1086 /* NULL for root_dir means use root from current directory. */
1087 if (root_dir
== NULL
)
1089 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
1091 parse_root (default_root
, &root_dir
);
1093 root_dir
= default_root
;
1096 /* Local fixed drives can be cached permanently. Removable drives
1097 cannot be cached permanently, since the volume name and serial
1098 number (if nothing else) can change. Remote drives should be
1099 treated as if they are removable, since there is no sure way to
1100 tell whether they are or not. Also, the UNC association of drive
1101 letters mapped to remote volumes can be changed at any time (even
1102 by other processes) without notice.
1104 As a compromise, so we can benefit from caching info for remote
1105 volumes, we use a simple expiry mechanism to invalidate cache
1106 entries that are more than ten seconds old. */
1109 /* No point doing this, because WNetGetConnection is even slower than
1110 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
1111 GetDriveType is about the only call of this type which does not
1112 involve network access, and so is extremely quick). */
1114 /* Map drive letter to UNC if remote. */
1115 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
1117 char remote_name
[ 256 ];
1118 char drive
[3] = { root_dir
[0], ':' };
1120 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
1122 /* do something */ ;
1126 info
= lookup_volume_info (root_dir
);
1128 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
1136 /* Info is not cached, or is stale. */
1137 if (!GetVolumeInformation (root_dir
,
1138 name
, sizeof (name
),
1142 type
, sizeof (type
)))
1145 /* Cache the volume information for future use, overwriting existing
1146 entry if present. */
1149 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
1150 add_volume_info (root_dir
, info
);
1158 info
->name
= xstrdup (name
);
1159 info
->serialnum
= serialnum
;
1160 info
->maxcomp
= maxcomp
;
1161 info
->flags
= flags
;
1162 info
->type
= xstrdup (type
);
1163 info
->timestamp
= GetTickCount ();
1169 /* Get information on the volume where name is held; set path pointer to
1170 start of pathname in name (past UNC header\volume header if present). */
1172 get_volume_info (const char * name
, const char ** pPath
)
1174 char temp
[MAX_PATH
];
1175 char *rootname
= NULL
; /* default to current volume */
1176 volume_info_data
* info
;
1181 /* find the root name of the volume if given */
1182 if (isalpha (name
[0]) && name
[1] == ':')
1190 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1197 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1210 info
= GetCachedVolumeInformation (rootname
);
1213 /* Set global referenced by other functions. */
1214 volume_info
= *info
;
1220 /* Determine if volume is FAT format (ie. only supports short 8.3
1221 names); also set path pointer to start of pathname in name. */
1223 is_fat_volume (const char * name
, const char ** pPath
)
1225 if (get_volume_info (name
, pPath
))
1226 return (volume_info
.maxcomp
== 12);
1230 /* Map filename to a legal 8.3 name if necessary. */
1232 map_w32_filename (const char * name
, const char ** pPath
)
1234 static char shortname
[MAX_PATH
];
1235 char * str
= shortname
;
1238 const char * save_name
= name
;
1240 if (strlen (name
) >= MAX_PATH
)
1242 /* Return a filename which will cause callers to fail. */
1243 strcpy (shortname
, "?");
1247 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
1249 register int left
= 8; /* maximum number of chars in part */
1250 register int extn
= 0; /* extension added? */
1251 register int dots
= 2; /* maximum number of dots allowed */
1254 *str
++ = *name
++; /* skip past UNC header */
1256 while ((c
= *name
++))
1263 extn
= 0; /* reset extension flags */
1264 dots
= 2; /* max 2 dots */
1265 left
= 8; /* max length 8 for main part */
1269 extn
= 0; /* reset extension flags */
1270 dots
= 2; /* max 2 dots */
1271 left
= 8; /* max length 8 for main part */
1276 /* Convert path components of the form .xxx to _xxx,
1277 but leave . and .. as they are. This allows .emacs
1278 to be read as _emacs, for example. */
1282 IS_DIRECTORY_SEP (*name
))
1297 extn
= 1; /* we've got an extension */
1298 left
= 3; /* 3 chars in extension */
1302 /* any embedded dots after the first are converted to _ */
1307 case '#': /* don't lose these, they're important */
1309 str
[-1] = c
; /* replace last character of part */
1314 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1316 dots
= 0; /* started a path component */
1325 strcpy (shortname
, name
);
1326 unixtodos_filename (shortname
);
1330 *pPath
= shortname
+ (path
- save_name
);
1336 is_exec (const char * name
)
1338 char * p
= strrchr (name
, '.');
1341 && (stricmp (p
, ".exe") == 0 ||
1342 stricmp (p
, ".com") == 0 ||
1343 stricmp (p
, ".bat") == 0 ||
1344 stricmp (p
, ".cmd") == 0));
1347 /* Emulate the Unix directory procedures opendir, closedir,
1348 and readdir. We can't use the procedures supplied in sysdep.c,
1349 so we provide them here. */
1351 struct direct dir_static
; /* simulated directory contents */
1352 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1353 static int dir_is_fat
;
1354 static char dir_pathname
[MAXPATHLEN
+1];
1355 static WIN32_FIND_DATA dir_find_data
;
1357 /* Support shares on a network resource as subdirectories of a read-only
1359 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1360 HANDLE
open_unc_volume (char *);
1361 char *read_unc_volume (HANDLE
, char *, int);
1362 void close_unc_volume (HANDLE
);
1365 opendir (char *filename
)
1369 /* Opening is done by FindFirstFile. However, a read is inherent to
1370 this operation, so we defer the open until read time. */
1372 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1374 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1377 if (is_unc_volume (filename
))
1379 wnet_enum_handle
= open_unc_volume (filename
);
1380 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
1384 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1391 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1392 dir_pathname
[MAXPATHLEN
] = '\0';
1393 dir_is_fat
= is_fat_volume (filename
, NULL
);
1399 closedir (DIR *dirp
)
1401 /* If we have a find-handle open, close it. */
1402 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1404 FindClose (dir_find_handle
);
1405 dir_find_handle
= INVALID_HANDLE_VALUE
;
1407 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1409 close_unc_volume (wnet_enum_handle
);
1410 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1412 xfree ((char *) dirp
);
1418 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1420 if (!read_unc_volume (wnet_enum_handle
,
1421 dir_find_data
.cFileName
,
1425 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1426 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1428 char filename
[MAXNAMLEN
+ 3];
1431 strcpy (filename
, dir_pathname
);
1432 ln
= strlen (filename
) - 1;
1433 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1434 strcat (filename
, "\\");
1435 strcat (filename
, "*");
1437 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1439 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1444 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1448 /* Emacs never uses this value, so don't bother making it match
1449 value returned by stat(). */
1450 dir_static
.d_ino
= 1;
1452 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1453 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1455 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1456 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1458 _strlwr (dir_static
.d_name
);
1459 else if (!NILP (Vw32_downcase_file_names
))
1462 for (p
= dir_static
.d_name
; *p
; p
++)
1463 if (*p
>= 'a' && *p
<= 'z')
1466 _strlwr (dir_static
.d_name
);
1473 open_unc_volume (char *path
)
1479 nr
.dwScope
= RESOURCE_GLOBALNET
;
1480 nr
.dwType
= RESOURCETYPE_DISK
;
1481 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
1482 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
1483 nr
.lpLocalName
= NULL
;
1484 nr
.lpRemoteName
= map_w32_filename (path
, NULL
);
1485 nr
.lpComment
= NULL
;
1486 nr
.lpProvider
= NULL
;
1488 result
= WNetOpenEnum(RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
1489 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
1491 if (result
== NO_ERROR
)
1494 return INVALID_HANDLE_VALUE
;
1498 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
1502 DWORD bufsize
= 512;
1507 buffer
= alloca (bufsize
);
1508 result
= WNetEnumResource (wnet_enum_handle
, &count
, buffer
, &bufsize
);
1509 if (result
!= NO_ERROR
)
1512 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
1513 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
1515 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
1518 strncpy (readbuf
, ptr
, size
);
1523 close_unc_volume (HANDLE henum
)
1525 if (henum
!= INVALID_HANDLE_VALUE
)
1526 WNetCloseEnum (henum
);
1530 unc_volume_file_attributes (char *path
)
1535 henum
= open_unc_volume (path
);
1536 if (henum
== INVALID_HANDLE_VALUE
)
1539 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
1541 close_unc_volume (henum
);
1547 /* Shadow some MSVC runtime functions to map requests for long filenames
1548 to reasonable short names if necessary. This was originally added to
1549 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1553 sys_access (const char * path
, int mode
)
1557 /* MSVC implementation doesn't recognize D_OK. */
1558 path
= map_w32_filename (path
, NULL
);
1559 if (is_unc_volume (path
))
1561 attributes
= unc_volume_file_attributes (path
);
1562 if (attributes
== -1) {
1567 else if ((attributes
= GetFileAttributes (path
)) == -1)
1569 /* Should try mapping GetLastError to errno; for now just indicate
1570 that path doesn't exist. */
1574 if ((mode
& X_OK
) != 0 && !is_exec (path
))
1579 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
1584 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1593 sys_chdir (const char * path
)
1595 return _chdir (map_w32_filename (path
, NULL
));
1599 sys_chmod (const char * path
, int mode
)
1601 return _chmod (map_w32_filename (path
, NULL
), mode
);
1605 sys_creat (const char * path
, int mode
)
1607 return _creat (map_w32_filename (path
, NULL
), mode
);
1611 sys_fopen(const char * path
, const char * mode
)
1615 const char * mode_save
= mode
;
1617 /* Force all file handles to be non-inheritable. This is necessary to
1618 ensure child processes don't unwittingly inherit handles that might
1619 prevent future file access. */
1623 else if (mode
[0] == 'w' || mode
[0] == 'a')
1624 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1628 /* Only do simplistic option parsing. */
1632 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1635 else if (mode
[0] == 'b')
1640 else if (mode
[0] == 't')
1647 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1651 return _fdopen (fd
, mode_save
);
1654 /* This only works on NTFS volumes, but is useful to have. */
1656 sys_link (const char * old
, const char * new)
1660 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
1662 if (old
== NULL
|| new == NULL
)
1668 strcpy (oldname
, map_w32_filename (old
, NULL
));
1669 strcpy (newname
, map_w32_filename (new, NULL
));
1671 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
1672 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1673 if (fileh
!= INVALID_HANDLE_VALUE
)
1677 /* Confusingly, the "alternate" stream name field does not apply
1678 when restoring a hard link, and instead contains the actual
1679 stream data for the link (ie. the name of the link to create).
1680 The WIN32_STREAM_ID structure before the cStreamName field is
1681 the stream header, which is then immediately followed by the
1685 WIN32_STREAM_ID wid
;
1686 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
1689 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
1690 data
.wid
.cStreamName
, MAX_PATH
);
1693 LPVOID context
= NULL
;
1696 data
.wid
.dwStreamId
= BACKUP_LINK
;
1697 data
.wid
.dwStreamAttributes
= 0;
1698 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
1699 data
.wid
.Size
.HighPart
= 0;
1700 data
.wid
.dwStreamNameSize
= 0;
1702 if (BackupWrite (fileh
, (LPBYTE
)&data
,
1703 offsetof (WIN32_STREAM_ID
, cStreamName
)
1704 + data
.wid
.Size
.LowPart
,
1705 &wbytes
, FALSE
, FALSE
, &context
)
1706 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
1713 /* Should try mapping GetLastError to errno; for now just
1714 indicate a general error (eg. links not supported). */
1715 errno
= EINVAL
; // perhaps EMLINK?
1719 CloseHandle (fileh
);
1728 sys_mkdir (const char * path
)
1730 return _mkdir (map_w32_filename (path
, NULL
));
1733 /* Because of long name mapping issues, we need to implement this
1734 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1735 a unique name, instead of setting the input template to an empty
1738 Standard algorithm seems to be use pid or tid with a letter on the
1739 front (in place of the 6 X's) and cycle through the letters to find a
1740 unique name. We extend that to allow any reasonable character as the
1741 first of the 6 X's. */
1743 sys_mktemp (char * template)
1747 unsigned uid
= GetCurrentThreadId ();
1748 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1750 if (template == NULL
)
1752 p
= template + strlen (template);
1754 /* replace up to the last 5 X's with uid in decimal */
1755 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
1757 p
[0] = '0' + uid
% 10;
1761 if (i
< 0 && p
[0] == 'X')
1766 int save_errno
= errno
;
1767 p
[0] = first_char
[i
];
1768 if (sys_access (template, 0) < 0)
1774 while (++i
< sizeof (first_char
));
1777 /* Template is badly formed or else we can't generate a unique name,
1778 so return empty string */
1784 sys_open (const char * path
, int oflag
, int mode
)
1786 /* Force all file handles to be non-inheritable. */
1787 return _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, mode
);
1791 sys_rename (const char * oldname
, const char * newname
)
1794 char temp
[MAX_PATH
];
1796 /* MoveFile on Windows 95 doesn't correctly change the short file name
1797 alias in a number of circumstances (it is not easy to predict when
1798 just by looking at oldname and newname, unfortunately). In these
1799 cases, renaming through a temporary name avoids the problem.
1801 A second problem on Windows 95 is that renaming through a temp name when
1802 newname is uppercase fails (the final long name ends up in
1803 lowercase, although the short alias might be uppercase) UNLESS the
1804 long temp name is not 8.3.
1806 So, on Windows 95 we always rename through a temp name, and we make sure
1807 the temp name has a long extension to ensure correct renaming. */
1809 strcpy (temp
, map_w32_filename (oldname
, NULL
));
1811 if (os_subtype
== OS_WIN95
)
1817 oldname
= map_w32_filename (oldname
, NULL
);
1818 if (o
= strrchr (oldname
, '\\'))
1821 o
= (char *) oldname
;
1823 if (p
= strrchr (temp
, '\\'))
1830 /* Force temp name to require a manufactured 8.3 alias - this
1831 seems to make the second rename work properly. */
1832 sprintf (p
, "_.%s.%u", o
, i
);
1834 result
= rename (oldname
, temp
);
1836 /* This loop must surely terminate! */
1837 while (result
< 0 && (errno
== EEXIST
|| errno
== EACCES
));
1842 /* Emulate Unix behaviour - newname is deleted if it already exists
1843 (at least if it is a file; don't do this for directories).
1845 Since we mustn't do this if we are just changing the case of the
1846 file name (we would end up deleting the file we are trying to
1847 rename!), we let rename detect if the destination file already
1848 exists - that way we avoid the possible pitfalls of trying to
1849 determine ourselves whether two names really refer to the same
1850 file, which is not always possible in the general case. (Consider
1851 all the permutations of shared or subst'd drives, etc.) */
1853 newname
= map_w32_filename (newname
, NULL
);
1854 result
= rename (temp
, newname
);
1857 && (errno
== EEXIST
|| errno
== EACCES
)
1858 && _chmod (newname
, 0666) == 0
1859 && _unlink (newname
) == 0)
1860 result
= rename (temp
, newname
);
1866 sys_rmdir (const char * path
)
1868 return _rmdir (map_w32_filename (path
, NULL
));
1872 sys_unlink (const char * path
)
1874 path
= map_w32_filename (path
, NULL
);
1876 /* On Unix, unlink works without write permission. */
1877 _chmod (path
, 0666);
1878 return _unlink (path
);
1881 static FILETIME utc_base_ft
;
1882 static long double utc_base
;
1883 static int init
= 0;
1886 convert_time (FILETIME ft
)
1892 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1901 st
.wMilliseconds
= 0;
1903 SystemTimeToFileTime (&st
, &utc_base_ft
);
1904 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1905 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1909 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
1912 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
1914 return (time_t) (ret
* 1e-7);
1918 convert_from_time_t (time_t time
, FILETIME
* pft
)
1924 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1933 st
.wMilliseconds
= 0;
1935 SystemTimeToFileTime (&st
, &utc_base_ft
);
1936 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1937 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1941 /* time in 100ns units since 1-Jan-1601 */
1942 tmp
= (long double) time
* 1e7
+ utc_base
;
1943 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
1944 pft
->dwLowDateTime
= (DWORD
) (tmp
- (4096.0 * 1024 * 1024) * pft
->dwHighDateTime
);
1948 /* No reason to keep this; faking inode values either by hashing or even
1949 using the file index from GetInformationByHandle, is not perfect and
1950 so by default Emacs doesn't use the inode values on Windows.
1951 Instead, we now determine file-truename correctly (except for
1952 possible drive aliasing etc). */
1954 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1956 hashval (const unsigned char * str
)
1961 h
= (h
<< 4) + *str
++;
1967 /* Return the hash value of the canonical pathname, excluding the
1968 drive/UNC header, to get a hopefully unique inode number. */
1970 generate_inode_val (const char * name
)
1972 char fullname
[ MAX_PATH
];
1976 /* Get the truly canonical filename, if it exists. (Note: this
1977 doesn't resolve aliasing due to subst commands, or recognise hard
1979 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
1982 parse_root (fullname
, &p
);
1983 /* Normal W32 filesystems are still case insensitive. */
1990 /* MSVC stat function can't cope with UNC names and has other bugs, so
1991 replace it with our own. This also allows us to calculate consistent
1992 inode values without hacks in the main Emacs code. */
1994 stat (const char * path
, struct stat
* buf
)
1997 WIN32_FIND_DATA wfd
;
2002 int rootdir
= FALSE
;
2004 if (path
== NULL
|| buf
== NULL
)
2010 name
= (char *) map_w32_filename (path
, &path
);
2011 /* must be valid filename, no wild cards or other invalid characters */
2012 if (strpbrk (name
, "*?|<>\""))
2018 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
2019 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
2020 if (IS_DIRECTORY_SEP (r
[0]) && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
2025 /* Remove trailing directory separator, unless name is the root
2026 directory of a drive or UNC volume in which case ensure there
2027 is a trailing separator. */
2028 len
= strlen (name
);
2029 rootdir
= (path
>= name
+ len
- 1
2030 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
2031 name
= strcpy (alloca (len
+ 2), name
);
2033 if (is_unc_volume (name
))
2035 DWORD attrs
= unc_volume_file_attributes (name
);
2040 memset (&wfd
, 0, sizeof (wfd
));
2041 wfd
.dwFileAttributes
= attrs
;
2042 wfd
.ftCreationTime
= utc_base_ft
;
2043 wfd
.ftLastAccessTime
= utc_base_ft
;
2044 wfd
.ftLastWriteTime
= utc_base_ft
;
2045 strcpy (wfd
.cFileName
, name
);
2049 if (!IS_DIRECTORY_SEP (name
[len
-1]))
2050 strcat (name
, "\\");
2051 if (GetDriveType (name
) < 2)
2056 memset (&wfd
, 0, sizeof (wfd
));
2057 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
2058 wfd
.ftCreationTime
= utc_base_ft
;
2059 wfd
.ftLastAccessTime
= utc_base_ft
;
2060 wfd
.ftLastWriteTime
= utc_base_ft
;
2061 strcpy (wfd
.cFileName
, name
);
2065 if (IS_DIRECTORY_SEP (name
[len
-1]))
2068 /* (This is hacky, but helps when doing file completions on
2069 network drives.) Optimize by using information available from
2070 active readdir if possible. */
2071 len
= strlen (dir_pathname
);
2072 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
2074 if (dir_find_handle
!= INVALID_HANDLE_VALUE
2075 && strnicmp (name
, dir_pathname
, len
) == 0
2076 && IS_DIRECTORY_SEP (name
[len
])
2077 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
2079 /* This was the last entry returned by readdir. */
2080 wfd
= dir_find_data
;
2084 fh
= FindFirstFile (name
, &wfd
);
2085 if (fh
== INVALID_HANDLE_VALUE
)
2094 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2096 buf
->st_mode
= _S_IFDIR
;
2097 buf
->st_nlink
= 2; /* doesn't really matter */
2098 fake_inode
= 0; /* this doesn't either I think */
2100 else if (!NILP (Vw32_get_true_file_attributes
)
2101 /* No access rights required to get info. */
2102 && (fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
, 0, NULL
))
2103 != INVALID_HANDLE_VALUE
)
2105 /* This is more accurate in terms of gettting the correct number
2106 of links, but is quite slow (it is noticable when Emacs is
2107 making a list of file name completions). */
2108 BY_HANDLE_FILE_INFORMATION info
;
2110 if (GetFileInformationByHandle (fh
, &info
))
2112 buf
->st_nlink
= info
.nNumberOfLinks
;
2113 /* Might as well use file index to fake inode values, but this
2114 is not guaranteed to be unique unless we keep a handle open
2115 all the time (even then there are situations where it is
2116 not unique). Reputedly, there are at most 48 bits of info
2117 (on NTFS, presumably less on FAT). */
2118 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
2126 switch (GetFileType (fh
))
2128 case FILE_TYPE_DISK
:
2129 buf
->st_mode
= _S_IFREG
;
2131 case FILE_TYPE_PIPE
:
2132 buf
->st_mode
= _S_IFIFO
;
2134 case FILE_TYPE_CHAR
:
2135 case FILE_TYPE_UNKNOWN
:
2137 buf
->st_mode
= _S_IFCHR
;
2143 /* Don't bother to make this information more accurate. */
2144 buf
->st_mode
= _S_IFREG
;
2150 /* Not sure if there is any point in this. */
2151 if (!NILP (Vw32_generate_fake_inodes
))
2152 fake_inode
= generate_inode_val (name
);
2153 else if (fake_inode
== 0)
2155 /* For want of something better, try to make everything unique. */
2156 static DWORD gen_num
= 0;
2157 fake_inode
= ++gen_num
;
2161 /* MSVC defines _ino_t to be short; other libc's might not. */
2162 if (sizeof (buf
->st_ino
) == 2)
2163 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
2165 buf
->st_ino
= fake_inode
;
2167 /* consider files to belong to current user */
2168 buf
->st_uid
= the_passwd
.pw_uid
;
2169 buf
->st_gid
= the_passwd
.pw_gid
;
2171 /* volume_info is set indirectly by map_w32_filename */
2172 buf
->st_dev
= volume_info
.serialnum
;
2173 buf
->st_rdev
= volume_info
.serialnum
;
2176 buf
->st_size
= wfd
.nFileSizeLow
;
2178 /* Convert timestamps to Unix format. */
2179 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
2180 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
2181 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
2182 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
2183 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
2185 /* determine rwx permissions */
2186 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2187 permission
= _S_IREAD
;
2189 permission
= _S_IREAD
| _S_IWRITE
;
2191 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2192 permission
|= _S_IEXEC
;
2193 else if (is_exec (name
))
2194 permission
|= _S_IEXEC
;
2196 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2201 /* Provide fstat and utime as well as stat for consistent handling of
2204 fstat (int desc
, struct stat
* buf
)
2206 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
2207 BY_HANDLE_FILE_INFORMATION info
;
2211 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
2213 case FILE_TYPE_DISK
:
2214 buf
->st_mode
= _S_IFREG
;
2215 if (!GetFileInformationByHandle (fh
, &info
))
2221 case FILE_TYPE_PIPE
:
2222 buf
->st_mode
= _S_IFIFO
;
2224 case FILE_TYPE_CHAR
:
2225 case FILE_TYPE_UNKNOWN
:
2227 buf
->st_mode
= _S_IFCHR
;
2229 memset (&info
, 0, sizeof (info
));
2230 info
.dwFileAttributes
= 0;
2231 info
.ftCreationTime
= utc_base_ft
;
2232 info
.ftLastAccessTime
= utc_base_ft
;
2233 info
.ftLastWriteTime
= utc_base_ft
;
2236 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2238 buf
->st_mode
= _S_IFDIR
;
2239 buf
->st_nlink
= 2; /* doesn't really matter */
2240 fake_inode
= 0; /* this doesn't either I think */
2244 buf
->st_nlink
= info
.nNumberOfLinks
;
2245 /* Might as well use file index to fake inode values, but this
2246 is not guaranteed to be unique unless we keep a handle open
2247 all the time (even then there are situations where it is
2248 not unique). Reputedly, there are at most 48 bits of info
2249 (on NTFS, presumably less on FAT). */
2250 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
2253 /* MSVC defines _ino_t to be short; other libc's might not. */
2254 if (sizeof (buf
->st_ino
) == 2)
2255 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
2257 buf
->st_ino
= fake_inode
;
2259 /* consider files to belong to current user */
2263 buf
->st_dev
= info
.dwVolumeSerialNumber
;
2264 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
2266 buf
->st_size
= info
.nFileSizeLow
;
2268 /* Convert timestamps to Unix format. */
2269 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
2270 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
2271 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
2272 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
2273 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
2275 /* determine rwx permissions */
2276 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2277 permission
= _S_IREAD
;
2279 permission
= _S_IREAD
| _S_IWRITE
;
2281 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2282 permission
|= _S_IEXEC
;
2285 #if 0 /* no way of knowing the filename */
2286 char * p
= strrchr (name
, '.');
2288 (stricmp (p
, ".exe") == 0 ||
2289 stricmp (p
, ".com") == 0 ||
2290 stricmp (p
, ".bat") == 0 ||
2291 stricmp (p
, ".cmd") == 0))
2292 permission
|= _S_IEXEC
;
2296 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2302 utime (const char *name
, struct utimbuf
*times
)
2304 struct utimbuf deftime
;
2311 deftime
.modtime
= deftime
.actime
= time (NULL
);
2315 /* Need write access to set times. */
2316 fh
= CreateFile (name
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
2317 0, OPEN_EXISTING
, 0, NULL
);
2320 convert_from_time_t (times
->actime
, &atime
);
2321 convert_from_time_t (times
->modtime
, &mtime
);
2322 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
2340 /* Wrappers for winsock functions to map between our file descriptors
2341 and winsock's handles; also set h_errno for convenience.
2343 To allow Emacs to run on systems which don't have winsock support
2344 installed, we dynamically link to winsock on startup if present, and
2345 otherwise provide the minimum necessary functionality
2346 (eg. gethostname). */
2348 /* function pointers for relevant socket functions */
2349 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
2350 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
2351 int (PASCAL
*pfn_WSAGetLastError
) (void);
2352 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
2353 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
2354 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
2355 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
2356 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
2357 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
2358 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
2359 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
2360 int (PASCAL
*pfn_WSACleanup
) (void);
2362 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
2363 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
2364 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
2365 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
2366 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
2367 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
2369 /* SetHandleInformation is only needed to make sockets non-inheritable. */
2370 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
2371 #ifndef HANDLE_FLAG_INHERIT
2372 #define HANDLE_FLAG_INHERIT 1
2376 static int winsock_inuse
;
2381 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
2383 /* Not sure what would cause WSAENETDOWN, or even if it can happen
2384 after WSAStartup returns successfully, but it seems reasonable
2385 to allow unloading winsock anyway in that case. */
2386 if (pfn_WSACleanup () == 0 ||
2387 pfn_WSAGetLastError () == WSAENETDOWN
)
2389 if (FreeLibrary (winsock_lib
))
2398 init_winsock (int load_now
)
2400 WSADATA winsockData
;
2402 if (winsock_lib
!= NULL
)
2405 pfn_SetHandleInformation
= NULL
;
2406 pfn_SetHandleInformation
2407 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2408 "SetHandleInformation");
2410 winsock_lib
= LoadLibrary ("wsock32.dll");
2412 if (winsock_lib
!= NULL
)
2414 /* dynamically link to socket functions */
2416 #define LOAD_PROC(fn) \
2417 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2420 LOAD_PROC( WSAStartup
);
2421 LOAD_PROC( WSASetLastError
);
2422 LOAD_PROC( WSAGetLastError
);
2423 LOAD_PROC( socket
);
2425 LOAD_PROC( connect
);
2426 LOAD_PROC( ioctlsocket
);
2429 LOAD_PROC( closesocket
);
2430 LOAD_PROC( shutdown
);
2433 LOAD_PROC( inet_addr
);
2434 LOAD_PROC( gethostname
);
2435 LOAD_PROC( gethostbyname
);
2436 LOAD_PROC( getservbyname
);
2437 LOAD_PROC( WSACleanup
);
2441 /* specify version 1.1 of winsock */
2442 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
2444 if (winsockData
.wVersion
!= 0x101)
2449 /* Report that winsock exists and is usable, but leave
2450 socket functions disabled. I am assuming that calling
2451 WSAStartup does not require any network interaction,
2452 and in particular does not cause or require a dial-up
2453 connection to be established. */
2456 FreeLibrary (winsock_lib
);
2464 FreeLibrary (winsock_lib
);
2474 /* function to set h_errno for compatability; map winsock error codes to
2475 normal system codes where they overlap (non-overlapping definitions
2476 are already in <sys/socket.h> */
2477 static void set_errno ()
2479 if (winsock_lib
== NULL
)
2482 h_errno
= pfn_WSAGetLastError ();
2486 case WSAEACCES
: h_errno
= EACCES
; break;
2487 case WSAEBADF
: h_errno
= EBADF
; break;
2488 case WSAEFAULT
: h_errno
= EFAULT
; break;
2489 case WSAEINTR
: h_errno
= EINTR
; break;
2490 case WSAEINVAL
: h_errno
= EINVAL
; break;
2491 case WSAEMFILE
: h_errno
= EMFILE
; break;
2492 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
2493 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
2498 static void check_errno ()
2500 if (h_errno
== 0 && winsock_lib
!= NULL
)
2501 pfn_WSASetLastError (0);
2504 /* Extend strerror to handle the winsock-specific error codes. */
2508 } _wsa_errlist
[] = {
2509 WSAEINTR
, "Interrupted function call",
2510 WSAEBADF
, "Bad file descriptor",
2511 WSAEACCES
, "Permission denied",
2512 WSAEFAULT
, "Bad address",
2513 WSAEINVAL
, "Invalid argument",
2514 WSAEMFILE
, "Too many open files",
2516 WSAEWOULDBLOCK
, "Resource temporarily unavailable",
2517 WSAEINPROGRESS
, "Operation now in progress",
2518 WSAEALREADY
, "Operation already in progress",
2519 WSAENOTSOCK
, "Socket operation on non-socket",
2520 WSAEDESTADDRREQ
, "Destination address required",
2521 WSAEMSGSIZE
, "Message too long",
2522 WSAEPROTOTYPE
, "Protocol wrong type for socket",
2523 WSAENOPROTOOPT
, "Bad protocol option",
2524 WSAEPROTONOSUPPORT
, "Protocol not supported",
2525 WSAESOCKTNOSUPPORT
, "Socket type not supported",
2526 WSAEOPNOTSUPP
, "Operation not supported",
2527 WSAEPFNOSUPPORT
, "Protocol family not supported",
2528 WSAEAFNOSUPPORT
, "Address family not supported by protocol family",
2529 WSAEADDRINUSE
, "Address already in use",
2530 WSAEADDRNOTAVAIL
, "Cannot assign requested address",
2531 WSAENETDOWN
, "Network is down",
2532 WSAENETUNREACH
, "Network is unreachable",
2533 WSAENETRESET
, "Network dropped connection on reset",
2534 WSAECONNABORTED
, "Software caused connection abort",
2535 WSAECONNRESET
, "Connection reset by peer",
2536 WSAENOBUFS
, "No buffer space available",
2537 WSAEISCONN
, "Socket is already connected",
2538 WSAENOTCONN
, "Socket is not connected",
2539 WSAESHUTDOWN
, "Cannot send after socket shutdown",
2540 WSAETOOMANYREFS
, "Too many references", /* not sure */
2541 WSAETIMEDOUT
, "Connection timed out",
2542 WSAECONNREFUSED
, "Connection refused",
2543 WSAELOOP
, "Network loop", /* not sure */
2544 WSAENAMETOOLONG
, "Name is too long",
2545 WSAEHOSTDOWN
, "Host is down",
2546 WSAEHOSTUNREACH
, "No route to host",
2547 WSAENOTEMPTY
, "Buffer not empty", /* not sure */
2548 WSAEPROCLIM
, "Too many processes",
2549 WSAEUSERS
, "Too many users", /* not sure */
2550 WSAEDQUOT
, "Double quote in host name", /* really not sure */
2551 WSAESTALE
, "Data is stale", /* not sure */
2552 WSAEREMOTE
, "Remote error", /* not sure */
2554 WSASYSNOTREADY
, "Network subsystem is unavailable",
2555 WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range",
2556 WSANOTINITIALISED
, "Winsock not initialized successfully",
2557 WSAEDISCON
, "Graceful shutdown in progress",
2559 WSAENOMORE
, "No more operations allowed", /* not sure */
2560 WSAECANCELLED
, "Operation cancelled", /* not sure */
2561 WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider",
2562 WSAEINVALIDPROVIDER
, "Invalid service provider version number",
2563 WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider",
2564 WSASYSCALLFAILURE
, "System call failured",
2565 WSASERVICE_NOT_FOUND
, "Service not found", /* not sure */
2566 WSATYPE_NOT_FOUND
, "Class type not found",
2567 WSA_E_NO_MORE
, "No more resources available", /* really not sure */
2568 WSA_E_CANCELLED
, "Operation already cancelled", /* really not sure */
2569 WSAEREFUSED
, "Operation refused", /* not sure */
2572 WSAHOST_NOT_FOUND
, "Host not found",
2573 WSATRY_AGAIN
, "Authoritative host not found during name lookup",
2574 WSANO_RECOVERY
, "Non-recoverable error during name lookup",
2575 WSANO_DATA
, "Valid name, no data record of requested type",
2581 sys_strerror(int error_no
)
2584 static char unknown_msg
[40];
2586 if (error_no
>= 0 && error_no
< sys_nerr
)
2587 return sys_errlist
[error_no
];
2589 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
2590 if (_wsa_errlist
[i
].errnum
== error_no
)
2591 return _wsa_errlist
[i
].msg
;
2593 sprintf(unknown_msg
, "Unidentified error: %d", error_no
);
2597 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2598 but I believe the method of keeping the socket handle separate (and
2599 insuring it is not inheritable) is the correct one. */
2601 //#define SOCK_REPLACE_HANDLE
2603 #ifdef SOCK_REPLACE_HANDLE
2604 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2606 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2610 sys_socket(int af
, int type
, int protocol
)
2616 if (winsock_lib
== NULL
)
2619 return INVALID_SOCKET
;
2624 /* call the real socket function */
2625 s
= (long) pfn_socket (af
, type
, protocol
);
2627 if (s
!= INVALID_SOCKET
)
2629 /* Although under NT 3.5 _open_osfhandle will accept a socket
2630 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2631 that does not work under NT 3.1. However, we can get the same
2632 effect by using a backdoor function to replace an existing
2633 descriptor handle with the one we want. */
2635 /* allocate a file descriptor (with appropriate flags) */
2636 fd
= _open ("NUL:", _O_RDWR
);
2639 #ifdef SOCK_REPLACE_HANDLE
2640 /* now replace handle to NUL with our socket handle */
2641 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
2643 _set_osfhnd (fd
, s
);
2644 /* setmode (fd, _O_BINARY); */
2646 /* Make a non-inheritable copy of the socket handle. Note
2647 that it is possible that sockets aren't actually kernel
2648 handles, which appears to be the case on Windows 9x when
2649 the MS Proxy winsock client is installed. */
2651 /* Apparently there is a bug in NT 3.51 with some service
2652 packs, which prevents using DuplicateHandle to make a
2653 socket handle non-inheritable (causes WSACleanup to
2654 hang). The work-around is to use SetHandleInformation
2655 instead if it is available and implemented. */
2656 if (pfn_SetHandleInformation
)
2658 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
2662 HANDLE parent
= GetCurrentProcess ();
2663 HANDLE new_s
= INVALID_HANDLE_VALUE
;
2665 if (DuplicateHandle (parent
,
2671 DUPLICATE_SAME_ACCESS
))
2673 /* It is possible that DuplicateHandle succeeds even
2674 though the socket wasn't really a kernel handle,
2675 because a real handle has the same value. So
2676 test whether the new handle really is a socket. */
2677 long nonblocking
= 0;
2678 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
2680 pfn_closesocket (s
);
2685 CloseHandle (new_s
);
2690 fd_info
[fd
].hnd
= (HANDLE
) s
;
2693 /* set our own internal flags */
2694 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
2700 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2702 /* attach child_process to fd_info */
2703 if (fd_info
[ fd
].cp
!= NULL
)
2705 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
2709 fd_info
[ fd
].cp
= cp
;
2712 winsock_inuse
++; /* count open sockets */
2719 pfn_closesocket (s
);
2729 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
2731 if (winsock_lib
== NULL
)
2734 return SOCKET_ERROR
;
2738 if (fd_info
[s
].flags
& FILE_SOCKET
)
2740 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
2741 if (rc
== SOCKET_ERROR
)
2746 return SOCKET_ERROR
;
2751 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
2753 if (winsock_lib
== NULL
)
2756 return SOCKET_ERROR
;
2760 if (fd_info
[s
].flags
& FILE_SOCKET
)
2762 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
2763 if (rc
== SOCKET_ERROR
)
2768 return SOCKET_ERROR
;
2772 sys_htons (u_short hostshort
)
2774 return (winsock_lib
!= NULL
) ?
2775 pfn_htons (hostshort
) : hostshort
;
2779 sys_ntohs (u_short netshort
)
2781 return (winsock_lib
!= NULL
) ?
2782 pfn_ntohs (netshort
) : netshort
;
2786 sys_inet_addr (const char * cp
)
2788 return (winsock_lib
!= NULL
) ?
2789 pfn_inet_addr (cp
) : INADDR_NONE
;
2793 sys_gethostname (char * name
, int namelen
)
2795 if (winsock_lib
!= NULL
)
2796 return pfn_gethostname (name
, namelen
);
2798 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
2799 return !GetComputerName (name
, (DWORD
*)&namelen
);
2802 return SOCKET_ERROR
;
2806 sys_gethostbyname(const char * name
)
2808 struct hostent
* host
;
2810 if (winsock_lib
== NULL
)
2817 host
= pfn_gethostbyname (name
);
2824 sys_getservbyname(const char * name
, const char * proto
)
2826 struct servent
* serv
;
2828 if (winsock_lib
== NULL
)
2835 serv
= pfn_getservbyname (name
, proto
);
2842 sys_shutdown (int s
, int how
)
2846 if (winsock_lib
== NULL
)
2849 return SOCKET_ERROR
;
2853 if (fd_info
[s
].flags
& FILE_SOCKET
)
2855 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
2856 if (rc
== SOCKET_ERROR
)
2861 return SOCKET_ERROR
;
2864 #endif /* HAVE_SOCKETS */
2867 /* Shadow main io functions: we need to handle pipes and sockets more
2868 intelligently, and implement non-blocking mode as well. */
2875 if (fd
< 0 || fd
>= MAXDESC
)
2883 child_process
* cp
= fd_info
[fd
].cp
;
2885 fd_info
[fd
].cp
= NULL
;
2887 if (CHILD_ACTIVE (cp
))
2889 /* if last descriptor to active child_process then cleanup */
2891 for (i
= 0; i
< MAXDESC
; i
++)
2895 if (fd_info
[i
].cp
== cp
)
2901 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2903 #ifndef SOCK_REPLACE_HANDLE
2904 if (winsock_lib
== NULL
) abort ();
2906 pfn_shutdown (SOCK_HANDLE (fd
), 2);
2907 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
2909 winsock_inuse
--; /* count open sockets */
2917 /* Note that sockets do not need special treatment here (at least on
2918 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2919 closesocket is equivalent to CloseHandle, which is to be expected
2920 because socket handles are fully fledged kernel handles. */
2924 fd_info
[fd
].flags
= 0;
2937 /* duplicate our internal info as well */
2938 fd_info
[new_fd
] = fd_info
[fd
];
2945 sys_dup2 (int src
, int dst
)
2949 if (dst
< 0 || dst
>= MAXDESC
)
2955 /* make sure we close the destination first if it's a pipe or socket */
2956 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
2959 rc
= _dup2 (src
, dst
);
2962 /* duplicate our internal info as well */
2963 fd_info
[dst
] = fd_info
[src
];
2968 /* Unix pipe() has only one arg */
2970 sys_pipe (int * phandles
)
2976 /* make pipe handles non-inheritable; when we spawn a child, we
2977 replace the relevant handle with an inheritable one. Also put
2978 pipes into binary mode; we will do text mode translation ourselves
2980 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
2984 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
2985 fd_info
[phandles
[0]].flags
= flags
;
2987 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
2988 fd_info
[phandles
[1]].flags
= flags
;
2995 extern Lisp_Object Vw32_pipe_read_delay
;
2997 /* Function to do blocking read of one byte, needed to implement
2998 select. It is only allowed on sockets and pipes. */
3000 _sys_read_ahead (int fd
)
3005 if (fd
< 0 || fd
>= MAXDESC
)
3006 return STATUS_READ_ERROR
;
3008 cp
= fd_info
[fd
].cp
;
3010 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
3011 return STATUS_READ_ERROR
;
3013 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
3014 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
3016 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
3020 cp
->status
= STATUS_READ_IN_PROGRESS
;
3022 if (fd_info
[fd
].flags
& FILE_PIPE
)
3024 rc
= _read (fd
, &cp
->chr
, sizeof (char));
3026 /* Give subprocess time to buffer some more output for us before
3027 reporting that input is available; we need this because Windows 95
3028 connects DOS programs to pipes by making the pipe appear to be
3029 the normal console stdout - as a result most DOS programs will
3030 write to stdout without buffering, ie. one character at a
3031 time. Even some W32 programs do this - "dir" in a command
3032 shell on NT is very slow if we don't do this. */
3035 int wait
= XINT (Vw32_pipe_read_delay
);
3041 /* Yield remainder of our time slice, effectively giving a
3042 temporary priority boost to the child process. */
3047 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
3048 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
3051 if (rc
== sizeof (char))
3052 cp
->status
= STATUS_READ_SUCCEEDED
;
3054 cp
->status
= STATUS_READ_FAILED
;
3060 sys_read (int fd
, char * buffer
, unsigned int count
)
3065 char * orig_buffer
= buffer
;
3067 if (fd
< 0 || fd
>= MAXDESC
)
3073 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3075 child_process
*cp
= fd_info
[fd
].cp
;
3077 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
3085 /* re-read CR carried over from last read */
3086 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
3088 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
3092 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
3095 /* presence of a child_process structure means we are operating in
3096 non-blocking mode - otherwise we just call _read directly.
3097 Note that the child_process structure might be missing because
3098 reap_subprocess has been called; in this case the pipe is
3099 already broken, so calling _read on it is okay. */
3102 int current_status
= cp
->status
;
3104 switch (current_status
)
3106 case STATUS_READ_FAILED
:
3107 case STATUS_READ_ERROR
:
3108 /* report normal EOF if nothing in buffer */
3110 fd_info
[fd
].flags
|= FILE_AT_EOF
;
3113 case STATUS_READ_READY
:
3114 case STATUS_READ_IN_PROGRESS
:
3115 DebPrint (("sys_read called when read is in progress\n"));
3116 errno
= EWOULDBLOCK
;
3119 case STATUS_READ_SUCCEEDED
:
3120 /* consume read-ahead char */
3121 *buffer
++ = cp
->chr
;
3124 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3125 ResetEvent (cp
->char_avail
);
3127 case STATUS_READ_ACKNOWLEDGED
:
3131 DebPrint (("sys_read: bad status %d\n", current_status
));
3136 if (fd_info
[fd
].flags
& FILE_PIPE
)
3138 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
3139 to_read
= min (waiting
, (DWORD
) count
);
3142 nchars
+= _read (fd
, buffer
, to_read
);
3145 else /* FILE_SOCKET */
3147 if (winsock_lib
== NULL
) abort ();
3149 /* do the equivalent of a non-blocking read */
3150 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
3151 if (waiting
== 0 && nchars
== 0)
3153 h_errno
= errno
= EWOULDBLOCK
;
3159 /* always use binary mode for sockets */
3160 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
3161 if (res
== SOCKET_ERROR
)
3163 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
3164 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3175 int nread
= _read (fd
, buffer
, count
);
3178 else if (nchars
== 0)
3183 fd_info
[fd
].flags
|= FILE_AT_EOF
;
3184 /* Perform text mode translation if required. */
3185 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
3187 nchars
= crlf_to_lf (nchars
, orig_buffer
);
3188 /* If buffer contains only CR, return that. To be absolutely
3189 sure we should attempt to read the next char, but in
3190 practice a CR to be followed by LF would not appear by
3191 itself in the buffer. */
3192 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
3194 fd_info
[fd
].flags
|= FILE_LAST_CR
;
3200 nchars
= _read (fd
, buffer
, count
);
3205 /* For now, don't bother with a non-blocking mode */
3207 sys_write (int fd
, const void * buffer
, unsigned int count
)
3211 if (fd
< 0 || fd
>= MAXDESC
)
3217 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3219 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
3225 /* Perform text mode translation if required. */
3226 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
3228 char * tmpbuf
= alloca (count
* 2);
3229 unsigned char * src
= (void *)buffer
;
3230 unsigned char * dst
= tmpbuf
;
3235 unsigned char *next
;
3236 /* copy next line or remaining bytes */
3237 next
= _memccpy (dst
, src
, '\n', nbytes
);
3240 /* copied one line ending with '\n' */
3241 int copied
= next
- dst
;
3244 /* insert '\r' before '\n' */
3251 /* copied remaining partial line -> now finished */
3259 if (fd_info
[fd
].flags
& FILE_SOCKET
)
3261 if (winsock_lib
== NULL
) abort ();
3262 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
3263 if (nchars
== SOCKET_ERROR
)
3265 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
3266 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3272 nchars
= _write (fd
, buffer
, count
);
3278 check_windows_init_file ()
3280 extern int noninteractive
, inhibit_window_system
;
3282 /* A common indication that Emacs is not installed properly is when
3283 it cannot find the Windows installation file. If this file does
3284 not exist in the expected place, tell the user. */
3286 if (!noninteractive
&& !inhibit_window_system
)
3288 extern Lisp_Object Vwindow_system
, Vload_path
, Qfile_exists_p
;
3289 Lisp_Object objs
[2];
3290 Lisp_Object full_load_path
;
3291 Lisp_Object init_file
;
3294 objs
[0] = Vload_path
;
3295 objs
[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
3296 full_load_path
= Fappend (2, objs
);
3297 init_file
= build_string ("term/w32-win");
3298 fd
= openp (full_load_path
, init_file
, ".el:.elc", NULL
, 0);
3301 Lisp_Object load_path_print
= Fprin1_to_string (full_load_path
, Qnil
);
3302 char *init_file_name
= XSTRING (init_file
)->data
;
3303 char *load_path
= XSTRING (load_path_print
)->data
;
3304 char *buffer
= alloca (1024);
3307 "The Emacs Windows initialization file \"%s.el\" "
3308 "could not be found in your Emacs installation. "
3309 "Emacs checked the following directories for this file:\n"
3311 "When Emacs cannot find this file, it usually means that it "
3312 "was not installed properly, or its distribution file was "
3313 "not unpacked properly.\nSee the README.W32 file in the "
3314 "top-level Emacs directory for more information.",
3315 init_file_name
, load_path
);
3318 "Emacs Abort Dialog",
3319 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
3320 /* Use the low-level Emacs abort. */
3335 /* shutdown the socket interface if necessary */
3344 /* Initialise the socket interface now if available and requested by
3345 the user by defining PRELOAD_WINSOCK; otherwise loading will be
3346 delayed until open-network-stream is called (w32-has-winsock can
3347 also be used to dynamically load or reload winsock).
3349 Conveniently, init_environment is called before us, so
3350 PRELOAD_WINSOCK can be set in the registry. */
3352 /* Always initialize this correctly. */
3355 if (getenv ("PRELOAD_WINSOCK") != NULL
)
3356 init_winsock (TRUE
);
3359 /* Initial preparation for subprocess support: replace our standard
3360 handles with non-inheritable versions. */
3363 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
3364 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
3365 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
3367 parent
= GetCurrentProcess ();
3369 /* ignore errors when duplicating and closing; typically the
3370 handles will be invalid when running as a gui program. */
3371 DuplicateHandle (parent
,
3372 GetStdHandle (STD_INPUT_HANDLE
),
3377 DUPLICATE_SAME_ACCESS
);
3379 DuplicateHandle (parent
,
3380 GetStdHandle (STD_OUTPUT_HANDLE
),
3385 DUPLICATE_SAME_ACCESS
);
3387 DuplicateHandle (parent
,
3388 GetStdHandle (STD_ERROR_HANDLE
),
3393 DUPLICATE_SAME_ACCESS
);
3399 if (stdin_save
!= INVALID_HANDLE_VALUE
)
3400 _open_osfhandle ((long) stdin_save
, O_TEXT
);
3402 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
3405 if (stdout_save
!= INVALID_HANDLE_VALUE
)
3406 _open_osfhandle ((long) stdout_save
, O_TEXT
);
3408 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
3411 if (stderr_save
!= INVALID_HANDLE_VALUE
)
3412 _open_osfhandle ((long) stderr_save
, O_TEXT
);
3414 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
3418 /* unfortunately, atexit depends on implementation of malloc */
3419 /* atexit (term_ntproc); */
3420 signal (SIGABRT
, term_ntproc
);
3422 /* determine which drives are fixed, for GetCachedVolumeInformation */
3424 /* GetDriveType must have trailing backslash. */
3425 char drive
[] = "A:\\";
3427 /* Loop over all possible drive letters */
3428 while (*drive
<= 'Z')
3430 /* Record if this drive letter refers to a fixed drive. */
3431 fixed_drives
[DRIVE_INDEX (*drive
)] =
3432 (GetDriveType (drive
) == DRIVE_FIXED
);
3437 /* Reset the volume info cache. */
3438 volume_cache
= NULL
;
3441 /* Check to see if Emacs has been installed correctly. */
3442 check_windows_init_file ();