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 */
34 #include <sys/utime.h>
36 /* must include CRT headers *before* config.h */
65 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
66 #include <sys/socket.h>
85 #define min(x, y) (((x) < (y)) ? (x) : (y))
86 #define max(x, y) (((x) > (y)) ? (x) : (y))
88 extern Lisp_Object Vw32_downcase_file_names
;
89 extern Lisp_Object Vw32_generate_fake_inodes
;
90 extern Lisp_Object Vw32_get_true_file_attributes
;
92 static char startup_dir
[MAXPATHLEN
];
94 /* Get the current working directory. */
99 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
103 /* Emacs doesn't actually change directory itself, and we want to
104 force our real wd to be where emacs.exe is to avoid unnecessary
105 conflicts when trying to rename or delete directories. */
106 strcpy (dir
, startup_dir
);
112 /* Emulate gethostname. */
114 gethostname (char *buffer
, int size
)
116 /* NT only allows small host names, so the buffer is
117 certainly large enough. */
118 return !GetComputerName (buffer
, &size
);
120 #endif /* HAVE_SOCKETS */
122 /* Emulate getloadavg. */
124 getloadavg (double loadavg
[], int nelem
)
128 /* A faithful emulation is going to have to be saved for a rainy day. */
129 for (i
= 0; i
< nelem
; i
++)
136 /* Emulate getpwuid, getpwnam and others. */
138 #define PASSWD_FIELD_SIZE 256
140 static char the_passwd_name
[PASSWD_FIELD_SIZE
];
141 static char the_passwd_passwd
[PASSWD_FIELD_SIZE
];
142 static char the_passwd_gecos
[PASSWD_FIELD_SIZE
];
143 static char the_passwd_dir
[PASSWD_FIELD_SIZE
];
144 static char the_passwd_shell
[PASSWD_FIELD_SIZE
];
146 static struct passwd the_passwd
=
161 return the_passwd
.pw_uid
;
167 /* I could imagine arguing for checking to see whether the user is
168 in the Administrators group and returning a UID of 0 for that
169 case, but I don't know how wise that would be in the long run. */
176 return the_passwd
.pw_gid
;
188 if (uid
== the_passwd
.pw_uid
)
194 getpwnam (char *name
)
198 pw
= getpwuid (getuid ());
202 if (stricmp (name
, pw
->pw_name
))
211 /* Find the user's real name by opening the process token and
212 looking up the name associated with the user-sid in that token.
214 Use the relative portion of the identifier authority value from
215 the user-sid as the user id value (same for group id using the
216 primary group sid from the process token). */
218 char user_sid
[256], name
[256], domain
[256];
219 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
221 SID_NAME_USE user_type
;
223 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &token
)
224 && GetTokenInformation (token
, TokenUser
,
225 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
226 && LookupAccountSid (NULL
, *((PSID
*) user_sid
), name
, &length
,
227 domain
, &dlength
, &user_type
))
229 strcpy (the_passwd
.pw_name
, name
);
230 /* Determine a reasonable uid value. */
231 if (stricmp ("administrator", name
) == 0)
233 the_passwd
.pw_uid
= 0;
234 the_passwd
.pw_gid
= 0;
238 SID_IDENTIFIER_AUTHORITY
* pSIA
;
240 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
241 /* I believe the relative portion is the last 4 bytes (of 6)
243 the_passwd
.pw_uid
= ((pSIA
->Value
[2] << 24) +
244 (pSIA
->Value
[3] << 16) +
245 (pSIA
->Value
[4] << 8) +
246 (pSIA
->Value
[5] << 0));
247 /* restrict to conventional uid range for normal users */
248 the_passwd
.pw_uid
= the_passwd
.pw_uid
% 60001;
251 if (GetTokenInformation (token
, TokenPrimaryGroup
,
252 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
254 SID_IDENTIFIER_AUTHORITY
* pSIA
;
256 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
257 the_passwd
.pw_gid
= ((pSIA
->Value
[2] << 24) +
258 (pSIA
->Value
[3] << 16) +
259 (pSIA
->Value
[4] << 8) +
260 (pSIA
->Value
[5] << 0));
261 /* I don't know if this is necessary, but for safety... */
262 the_passwd
.pw_gid
= the_passwd
.pw_gid
% 60001;
265 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
268 /* If security calls are not supported (presumably because we
269 are running under Windows 95), fallback to this. */
270 else if (GetUserName (name
, &length
))
272 strcpy (the_passwd
.pw_name
, name
);
273 if (stricmp ("administrator", name
) == 0)
274 the_passwd
.pw_uid
= 0;
276 the_passwd
.pw_uid
= 123;
277 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
281 strcpy (the_passwd
.pw_name
, "unknown");
282 the_passwd
.pw_uid
= 123;
283 the_passwd
.pw_gid
= 123;
286 /* Ensure HOME and SHELL are defined. */
287 if (getenv ("HOME") == NULL
)
289 if (getenv ("SHELL") == NULL
)
290 putenv (os_subtype
== OS_WIN95
? "SHELL=command" : "SHELL=cmd");
292 /* Set dir and shell from environment variables. */
293 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
294 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
303 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
304 return ((rand () << 15) | rand ());
314 /* Normalize filename by converting all path separators to
315 the specified separator. Also conditionally convert upper
316 case path name components to lower case. */
319 normalize_filename (fp
, path_sep
)
326 /* Always lower-case drive letters a-z, even if the filesystem
327 preserves case in filenames.
328 This is so filenames can be compared by string comparison
329 functions that are case-sensitive. Even case-preserving filesystems
330 do not distinguish case in drive letters. */
331 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
337 if (NILP (Vw32_downcase_file_names
))
341 if (*fp
== '/' || *fp
== '\\')
348 sep
= path_sep
; /* convert to this path separator */
349 elem
= fp
; /* start of current path element */
352 if (*fp
>= 'a' && *fp
<= 'z')
353 elem
= 0; /* don't convert this element */
355 if (*fp
== 0 || *fp
== ':')
357 sep
= *fp
; /* restore current separator (or 0) */
358 *fp
= '/'; /* after conversion of this element */
361 if (*fp
== '/' || *fp
== '\\')
363 if (elem
&& elem
!= fp
)
365 *fp
= 0; /* temporary end of string */
366 _strlwr (elem
); /* while we convert to lower case */
368 *fp
= sep
; /* convert (or restore) path separator */
369 elem
= fp
+ 1; /* next element starts after separator */
375 /* Destructively turn backslashes into slashes. */
377 dostounix_filename (p
)
380 normalize_filename (p
, '/');
383 /* Destructively turn slashes into backslashes. */
385 unixtodos_filename (p
)
388 normalize_filename (p
, '\\');
391 /* Remove all CR's that are followed by a LF.
392 (From msdos.c...probably should figure out a way to share it,
393 although this code isn't going to ever change.) */
397 register unsigned char *buf
;
399 unsigned char *np
= buf
;
400 unsigned char *startp
= buf
;
401 unsigned char *endp
= buf
+ n
;
405 while (buf
< endp
- 1)
409 if (*(++buf
) != 0x0a)
420 /* Parse the root part of file name, if present. Return length and
421 optionally store pointer to char after root. */
423 parse_root (char * name
, char ** pPath
)
430 /* find the root name of the volume if given */
431 if (isalpha (name
[0]) && name
[1] == ':')
433 /* skip past drive specifier */
435 if (IS_DIRECTORY_SEP (name
[0]))
438 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
444 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
449 if (IS_DIRECTORY_SEP (name
[0]))
459 /* Get long base name for name; name is assumed to be absolute. */
461 get_long_basename (char * name
, char * buf
, int size
)
463 WIN32_FIND_DATA find_data
;
467 dir_handle
= FindFirstFile (name
, &find_data
);
468 if (dir_handle
!= INVALID_HANDLE_VALUE
)
470 if ((len
= strlen (find_data
.cFileName
)) < size
)
471 memcpy (buf
, find_data
.cFileName
, len
+ 1);
474 FindClose (dir_handle
);
479 /* Get long name for file, if possible (assumed to be absolute). */
481 w32_get_long_filename (char * name
, char * buf
, int size
)
486 char full
[ MAX_PATH
];
493 /* Use local copy for destructive modification. */
494 memcpy (full
, name
, len
+1);
495 unixtodos_filename (full
);
497 /* Copy root part verbatim. */
498 len
= parse_root (full
, &p
);
499 memcpy (o
, full
, len
);
506 p
= strchr (q
, '\\');
508 len
= get_long_basename (full
, o
, size
);
526 while (p
!= NULL
&& *p
);
532 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
535 sigsetmask (int signal_mask
)
547 setpgrp (int pid
, int gid
)
559 unrequest_sigio (void)
570 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
573 w32_get_resource (key
, lpdwtype
)
578 HKEY hrootkey
= NULL
;
582 /* Check both the current user and the local machine to see if
583 we have any resources. */
585 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
589 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
590 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
591 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
596 if (lpvalue
) xfree (lpvalue
);
598 RegCloseKey (hrootkey
);
601 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
605 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
606 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
607 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
612 if (lpvalue
) xfree (lpvalue
);
614 RegCloseKey (hrootkey
);
620 char *get_emacs_configuration (void);
621 extern Lisp_Object Vsystem_configuration
;
626 /* Check for environment variables and use registry if they don't exist */
632 static char * env_vars
[] =
643 /* We no longer set INFOPATH because Info-default-directory-list
644 is then ignored. We use a hook in winnt.el instead. */
650 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
652 if (!getenv (env_vars
[i
])
653 && (lpval
= w32_get_resource (env_vars
[i
], &dwType
)) != NULL
)
655 if (dwType
== REG_EXPAND_SZ
)
657 char buf1
[500], buf2
[500];
659 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, 500);
660 _snprintf (buf2
, 499, "%s=%s", env_vars
[i
], buf1
);
661 putenv (strdup (buf2
));
663 else if (dwType
== REG_SZ
)
667 _snprintf (buf
, 499, "%s=%s", env_vars
[i
], lpval
);
668 putenv (strdup (buf
));
676 /* Rebuild system configuration to reflect invoking system. */
677 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
679 /* Another special case: on NT, the PATH variable is actually named
680 "Path" although cmd.exe (perhaps NT itself) arranges for
681 environment variable lookup and setting to be case insensitive.
682 However, Emacs assumes a fully case sensitive environment, so we
683 need to change "Path" to "PATH" to match the expectations of
684 various elisp packages. We do this by the sneaky method of
685 modifying the string in the C runtime environ entry.
687 The same applies to COMSPEC. */
691 for (envp
= environ
; *envp
; envp
++)
692 if (_strnicmp (*envp
, "PATH=", 5) == 0)
693 memcpy (*envp
, "PATH=", 5);
694 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
695 memcpy (*envp
, "COMSPEC=", 8);
698 /* Remember the initial working directory for getwd, then make the
699 real wd be the location of emacs.exe to avoid conflicts when
700 renaming or deleting directories. (We also don't call chdir when
701 running subprocesses for the same reason.) */
702 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
707 char modname
[MAX_PATH
];
709 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
711 if ((p
= strrchr (modname
, '\\')) == NULL
)
715 SetCurrentDirectory (modname
);
721 /* We don't have scripts to automatically determine the system configuration
722 for Emacs before it's compiled, and we don't want to have to make the
723 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
726 static char configuration_buffer
[32];
729 get_emacs_configuration (void)
731 char *arch
, *oem
, *os
;
733 /* Determine the processor type. */
734 switch (get_processor_type ())
737 #ifdef PROCESSOR_INTEL_386
738 case PROCESSOR_INTEL_386
:
739 case PROCESSOR_INTEL_486
:
740 case PROCESSOR_INTEL_PENTIUM
:
745 #ifdef PROCESSOR_INTEL_860
746 case PROCESSOR_INTEL_860
:
751 #ifdef PROCESSOR_MIPS_R2000
752 case PROCESSOR_MIPS_R2000
:
753 case PROCESSOR_MIPS_R3000
:
754 case PROCESSOR_MIPS_R4000
:
759 #ifdef PROCESSOR_ALPHA_21064
760 case PROCESSOR_ALPHA_21064
:
770 /* Let oem be "*" until we figure out how to decode the OEM field. */
773 os
= (GetVersion () & OS_WIN95
) ? "windows95" : "nt";
775 sprintf (configuration_buffer
, "%s-%s-%s%d.%d", arch
, oem
, os
,
776 get_w32_major_version (), get_w32_minor_version ());
777 return configuration_buffer
;
780 #include <sys/timeb.h>
782 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
784 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
789 tv
->tv_sec
= tb
.time
;
790 tv
->tv_usec
= tb
.millitm
* 1000L;
793 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
794 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
798 /* ------------------------------------------------------------------------- */
799 /* IO support and wrapper functions for W32 API. */
800 /* ------------------------------------------------------------------------- */
802 /* Place a wrapper around the MSVC version of ctime. It returns NULL
803 on network directories, so we handle that case here.
804 (Ulrich Leodolter, 1/11/95). */
806 sys_ctime (const time_t *t
)
808 char *str
= (char *) ctime (t
);
809 return (str
? str
: "Sun Jan 01 00:00:00 1970");
812 /* Emulate sleep...we could have done this with a define, but that
813 would necessitate including windows.h in the files that used it.
814 This is much easier. */
816 sys_sleep (int seconds
)
818 Sleep (seconds
* 1000);
821 /* Internal MSVC functions for low-level descriptor munging */
822 extern int __cdecl
_set_osfhnd (int fd
, long h
);
823 extern int __cdecl
_free_osfhnd (int fd
);
825 /* parallel array of private info on file handles */
826 filedesc fd_info
[ MAXDESC
];
828 typedef struct volume_info_data
{
829 struct volume_info_data
* next
;
831 /* time when info was obtained */
834 /* actual volume info */
843 /* Global referenced by various functions. */
844 static volume_info_data volume_info
;
846 /* Vector to indicate which drives are local and fixed (for which cached
847 data never expires). */
848 static BOOL fixed_drives
[26];
850 /* Consider cached volume information to be stale if older than 10s,
851 at least for non-local drives. Info for fixed drives is never stale. */
852 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
853 #define VOLINFO_STILL_VALID( root_dir, info ) \
854 ( ( isalpha (root_dir[0]) && \
855 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
856 || GetTickCount () - info->timestamp < 10000 )
858 /* Cache support functions. */
860 /* Simple linked list with linear search is sufficient. */
861 static volume_info_data
*volume_cache
= NULL
;
863 static volume_info_data
*
864 lookup_volume_info (char * root_dir
)
866 volume_info_data
* info
;
868 for (info
= volume_cache
; info
; info
= info
->next
)
869 if (stricmp (info
->root_dir
, root_dir
) == 0)
875 add_volume_info (char * root_dir
, volume_info_data
* info
)
877 info
->root_dir
= strdup (root_dir
);
878 info
->next
= volume_cache
;
883 /* Wrapper for GetVolumeInformation, which uses caching to avoid
884 performance penalty (~2ms on 486 for local drives, 7.5ms for local
885 cdrom drive, ~5-10ms or more for remote drives on LAN). */
887 GetCachedVolumeInformation (char * root_dir
)
889 volume_info_data
* info
;
890 char default_root
[ MAX_PATH
];
892 /* NULL for root_dir means use root from current directory. */
893 if (root_dir
== NULL
)
895 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
897 parse_root (default_root
, &root_dir
);
899 root_dir
= default_root
;
902 /* Local fixed drives can be cached permanently. Removable drives
903 cannot be cached permanently, since the volume name and serial
904 number (if nothing else) can change. Remote drives should be
905 treated as if they are removable, since there is no sure way to
906 tell whether they are or not. Also, the UNC association of drive
907 letters mapped to remote volumes can be changed at any time (even
908 by other processes) without notice.
910 As a compromise, so we can benefit from caching info for remote
911 volumes, we use a simple expiry mechanism to invalidate cache
912 entries that are more than ten seconds old. */
915 /* No point doing this, because WNetGetConnection is even slower than
916 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
917 GetDriveType is about the only call of this type which does not
918 involve network access, and so is extremely quick). */
920 /* Map drive letter to UNC if remote. */
921 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
923 char remote_name
[ 256 ];
924 char drive
[3] = { root_dir
[0], ':' };
926 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
932 info
= lookup_volume_info (root_dir
);
934 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
942 /* Info is not cached, or is stale. */
943 if (!GetVolumeInformation (root_dir
,
948 type
, sizeof (type
)))
951 /* Cache the volume information for future use, overwriting existing
955 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
956 add_volume_info (root_dir
, info
);
964 info
->name
= strdup (name
);
965 info
->serialnum
= serialnum
;
966 info
->maxcomp
= maxcomp
;
968 info
->type
= strdup (type
);
969 info
->timestamp
= GetTickCount ();
975 /* Get information on the volume where name is held; set path pointer to
976 start of pathname in name (past UNC header\volume header if present). */
978 get_volume_info (const char * name
, const char ** pPath
)
981 char *rootname
= NULL
; /* default to current volume */
982 volume_info_data
* info
;
987 /* find the root name of the volume if given */
988 if (isalpha (name
[0]) && name
[1] == ':')
996 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1003 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1016 info
= GetCachedVolumeInformation (rootname
);
1019 /* Set global referenced by other functions. */
1020 volume_info
= *info
;
1026 /* Determine if volume is FAT format (ie. only supports short 8.3
1027 names); also set path pointer to start of pathname in name. */
1029 is_fat_volume (const char * name
, const char ** pPath
)
1031 if (get_volume_info (name
, pPath
))
1032 return (volume_info
.maxcomp
== 12);
1036 /* Map filename to a legal 8.3 name if necessary. */
1038 map_w32_filename (const char * name
, const char ** pPath
)
1040 static char shortname
[MAX_PATH
];
1041 char * str
= shortname
;
1044 const char * save_name
= name
;
1046 if (is_fat_volume (name
, &path
)) /* truncate to 8.3 */
1048 register int left
= 8; /* maximum number of chars in part */
1049 register int extn
= 0; /* extension added? */
1050 register int dots
= 2; /* maximum number of dots allowed */
1053 *str
++ = *name
++; /* skip past UNC header */
1055 while ((c
= *name
++))
1062 extn
= 0; /* reset extension flags */
1063 dots
= 2; /* max 2 dots */
1064 left
= 8; /* max length 8 for main part */
1068 extn
= 0; /* reset extension flags */
1069 dots
= 2; /* max 2 dots */
1070 left
= 8; /* max length 8 for main part */
1075 /* Convert path components of the form .xxx to _xxx,
1076 but leave . and .. as they are. This allows .emacs
1077 to be read as _emacs, for example. */
1081 IS_DIRECTORY_SEP (*name
))
1096 extn
= 1; /* we've got an extension */
1097 left
= 3; /* 3 chars in extension */
1101 /* any embedded dots after the first are converted to _ */
1106 case '#': /* don't lose these, they're important */
1108 str
[-1] = c
; /* replace last character of part */
1113 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1115 dots
= 0; /* started a path component */
1124 strcpy (shortname
, name
);
1125 unixtodos_filename (shortname
);
1129 *pPath
= shortname
+ (path
- save_name
);
1134 /* Emulate the Unix directory procedures opendir, closedir,
1135 and readdir. We can't use the procedures supplied in sysdep.c,
1136 so we provide them here. */
1138 struct direct dir_static
; /* simulated directory contents */
1139 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1140 static int dir_is_fat
;
1141 static char dir_pathname
[MAXPATHLEN
+1];
1142 static WIN32_FIND_DATA dir_find_data
;
1145 opendir (char *filename
)
1149 /* Opening is done by FindFirstFile. However, a read is inherent to
1150 this operation, so we defer the open until read time. */
1152 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1154 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1161 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1162 dir_pathname
[MAXPATHLEN
] = '\0';
1163 dir_is_fat
= is_fat_volume (filename
, NULL
);
1169 closedir (DIR *dirp
)
1171 /* If we have a find-handle open, close it. */
1172 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1174 FindClose (dir_find_handle
);
1175 dir_find_handle
= INVALID_HANDLE_VALUE
;
1177 xfree ((char *) dirp
);
1183 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1184 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1186 char filename
[MAXNAMLEN
+ 3];
1189 strcpy (filename
, dir_pathname
);
1190 ln
= strlen (filename
) - 1;
1191 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1192 strcat (filename
, "\\");
1193 strcat (filename
, "*");
1195 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1197 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1202 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1206 /* Emacs never uses this value, so don't bother making it match
1207 value returned by stat(). */
1208 dir_static
.d_ino
= 1;
1210 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1211 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1213 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1214 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1216 _strlwr (dir_static
.d_name
);
1217 else if (!NILP (Vw32_downcase_file_names
))
1220 for (p
= dir_static
.d_name
; *p
; p
++)
1221 if (*p
>= 'a' && *p
<= 'z')
1224 _strlwr (dir_static
.d_name
);
1231 /* Shadow some MSVC runtime functions to map requests for long filenames
1232 to reasonable short names if necessary. This was originally added to
1233 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1237 sys_access (const char * path
, int mode
)
1239 return _access (map_w32_filename (path
, NULL
), mode
);
1243 sys_chdir (const char * path
)
1245 return _chdir (map_w32_filename (path
, NULL
));
1249 sys_chmod (const char * path
, int mode
)
1251 return _chmod (map_w32_filename (path
, NULL
), mode
);
1255 sys_creat (const char * path
, int mode
)
1257 return _creat (map_w32_filename (path
, NULL
), mode
);
1261 sys_fopen(const char * path
, const char * mode
)
1265 const char * mode_save
= mode
;
1267 /* Force all file handles to be non-inheritable. This is necessary to
1268 ensure child processes don't unwittingly inherit handles that might
1269 prevent future file access. */
1273 else if (mode
[0] == 'w' || mode
[0] == 'a')
1274 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1278 /* Only do simplistic option parsing. */
1282 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1285 else if (mode
[0] == 'b')
1290 else if (mode
[0] == 't')
1297 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1301 return _fdopen (fd
, mode_save
);
1304 /* This only works on NTFS volumes, but is useful to have. */
1306 sys_link (const char * old
, const char * new)
1310 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
1312 if (old
== NULL
|| new == NULL
)
1318 strcpy (oldname
, map_w32_filename (old
, NULL
));
1319 strcpy (newname
, map_w32_filename (new, NULL
));
1321 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
1322 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1323 if (fileh
!= INVALID_HANDLE_VALUE
)
1327 /* Confusingly, the "alternate" stream name field does not apply
1328 when restoring a hard link, and instead contains the actual
1329 stream data for the link (ie. the name of the link to create).
1330 The WIN32_STREAM_ID structure before the cStreamName field is
1331 the stream header, which is then immediately followed by the
1335 WIN32_STREAM_ID wid
;
1336 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
1339 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
1340 data
.wid
.cStreamName
, MAX_PATH
);
1343 LPVOID context
= NULL
;
1346 data
.wid
.dwStreamId
= BACKUP_LINK
;
1347 data
.wid
.dwStreamAttributes
= 0;
1348 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
1349 data
.wid
.Size
.HighPart
= 0;
1350 data
.wid
.dwStreamNameSize
= 0;
1352 if (BackupWrite (fileh
, (LPBYTE
)&data
,
1353 offsetof (WIN32_STREAM_ID
, cStreamName
)
1354 + data
.wid
.Size
.LowPart
,
1355 &wbytes
, FALSE
, FALSE
, &context
)
1356 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
1363 /* Should try mapping GetLastError to errno; for now just
1364 indicate a general error (eg. links not supported). */
1365 errno
= EINVAL
; // perhaps EMLINK?
1369 CloseHandle (fileh
);
1378 sys_mkdir (const char * path
)
1380 return _mkdir (map_w32_filename (path
, NULL
));
1383 /* Because of long name mapping issues, we need to implement this
1384 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1385 a unique name, instead of setting the input template to an empty
1388 Standard algorithm seems to be use pid or tid with a letter on the
1389 front (in place of the 6 X's) and cycle through the letters to find a
1390 unique name. We extend that to allow any reasonable character as the
1391 first of the 6 X's. */
1393 sys_mktemp (char * template)
1397 unsigned uid
= GetCurrentThreadId ();
1398 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1400 if (template == NULL
)
1402 p
= template + strlen (template);
1404 /* replace up to the last 5 X's with uid in decimal */
1405 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
1407 p
[0] = '0' + uid
% 10;
1411 if (i
< 0 && p
[0] == 'X')
1416 int save_errno
= errno
;
1417 p
[0] = first_char
[i
];
1418 if (sys_access (template, 0) < 0)
1424 while (++i
< sizeof (first_char
));
1427 /* Template is badly formed or else we can't generate a unique name,
1428 so return empty string */
1434 sys_open (const char * path
, int oflag
, int mode
)
1436 /* Force all file handles to be non-inheritable. */
1437 return _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, mode
);
1441 sys_rename (const char * oldname
, const char * newname
)
1443 char temp
[MAX_PATH
];
1446 /* MoveFile on Windows 95 doesn't correctly change the short file name
1447 alias in a number of circumstances (it is not easy to predict when
1448 just by looking at oldname and newname, unfortunately). In these
1449 cases, renaming through a temporary name avoids the problem.
1451 A second problem on Windows 95 is that renaming through a temp name when
1452 newname is uppercase fails (the final long name ends up in
1453 lowercase, although the short alias might be uppercase) UNLESS the
1454 long temp name is not 8.3.
1456 So, on Windows 95 we always rename through a temp name, and we make sure
1457 the temp name has a long extension to ensure correct renaming. */
1459 strcpy (temp
, map_w32_filename (oldname
, NULL
));
1461 if (os_subtype
== OS_WIN95
)
1465 if (p
= strrchr (temp
, '\\'))
1469 /* Force temp name to require a manufactured 8.3 alias - this
1470 seems to make the second rename work properly. */
1471 strcpy (p
, "_rename_temp.XXXXXX");
1473 if (rename (map_w32_filename (oldname
, NULL
), temp
) < 0)
1477 /* Emulate Unix behaviour - newname is deleted if it already exists
1478 (at least if it is a file; don't do this for directories).
1479 However, don't do this if we are just changing the case of the file
1480 name - we will end up deleting the file we are trying to rename! */
1481 newname
= map_w32_filename (newname
, NULL
);
1483 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1484 do not refer to the same file, eg. through share aliases. */
1485 if (stricmp (newname
, temp
) != 0
1486 && (attr
= GetFileAttributes (newname
)) != -1
1487 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1489 _chmod (newname
, 0666);
1493 return rename (temp
, newname
);
1497 sys_rmdir (const char * path
)
1499 return _rmdir (map_w32_filename (path
, NULL
));
1503 sys_unlink (const char * path
)
1505 path
= map_w32_filename (path
, NULL
);
1507 /* On Unix, unlink works without write permission. */
1508 _chmod (path
, 0666);
1509 return _unlink (path
);
1512 static FILETIME utc_base_ft
;
1513 static long double utc_base
;
1514 static int init
= 0;
1517 convert_time (FILETIME ft
)
1523 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1532 st
.wMilliseconds
= 0;
1534 SystemTimeToFileTime (&st
, &utc_base_ft
);
1535 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1536 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1540 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
1543 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
1545 return (time_t) (ret
* 1e-7);
1549 convert_from_time_t (time_t time
, FILETIME
* pft
)
1555 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1564 st
.wMilliseconds
= 0;
1566 SystemTimeToFileTime (&st
, &utc_base_ft
);
1567 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1568 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1572 /* time in 100ns units since 1-Jan-1601 */
1573 tmp
= (long double) time
* 1e7
+ utc_base
;
1574 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
1575 pft
->dwLowDateTime
= (DWORD
) (tmp
- (4096.0 * 1024 * 1024) * pft
->dwHighDateTime
);
1579 /* No reason to keep this; faking inode values either by hashing or even
1580 using the file index from GetInformationByHandle, is not perfect and
1581 so by default Emacs doesn't use the inode values on Windows.
1582 Instead, we now determine file-truename correctly (except for
1583 possible drive aliasing etc). */
1585 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1587 hashval (const unsigned char * str
)
1592 h
= (h
<< 4) + *str
++;
1598 /* Return the hash value of the canonical pathname, excluding the
1599 drive/UNC header, to get a hopefully unique inode number. */
1601 generate_inode_val (const char * name
)
1603 char fullname
[ MAX_PATH
];
1607 /* Get the truly canonical filename, if it exists. (Note: this
1608 doesn't resolve aliasing due to subst commands, or recognise hard
1610 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
1613 parse_root (fullname
, &p
);
1614 /* Normal W32 filesystems are still case insensitive. */
1621 /* MSVC stat function can't cope with UNC names and has other bugs, so
1622 replace it with our own. This also allows us to calculate consistent
1623 inode values without hacks in the main Emacs code. */
1625 stat (const char * path
, struct stat
* buf
)
1628 WIN32_FIND_DATA wfd
;
1633 int rootdir
= FALSE
;
1635 if (path
== NULL
|| buf
== NULL
)
1641 name
= (char *) map_w32_filename (path
, &path
);
1642 /* must be valid filename, no wild cards */
1643 if (strchr (name
, '*') || strchr (name
, '?'))
1649 /* Remove trailing directory separator, unless name is the root
1650 directory of a drive or UNC volume in which case ensure there
1651 is a trailing separator. */
1652 len
= strlen (name
);
1653 rootdir
= (path
>= name
+ len
- 1
1654 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
1655 name
= strcpy (alloca (len
+ 2), name
);
1659 if (!IS_DIRECTORY_SEP (name
[len
-1]))
1660 strcat (name
, "\\");
1661 if (GetDriveType (name
) < 2)
1666 memset (&wfd
, 0, sizeof (wfd
));
1667 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
1668 wfd
.ftCreationTime
= utc_base_ft
;
1669 wfd
.ftLastAccessTime
= utc_base_ft
;
1670 wfd
.ftLastWriteTime
= utc_base_ft
;
1671 strcpy (wfd
.cFileName
, name
);
1675 if (IS_DIRECTORY_SEP (name
[len
-1]))
1678 /* (This is hacky, but helps when doing file completions on
1679 network drives.) Optimize by using information available from
1680 active readdir if possible. */
1681 if (dir_find_handle
!= INVALID_HANDLE_VALUE
1682 && (len
= strlen (dir_pathname
)),
1683 strnicmp (name
, dir_pathname
, len
) == 0
1684 && IS_DIRECTORY_SEP (name
[len
])
1685 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
1687 /* This was the last entry returned by readdir. */
1688 wfd
= dir_find_data
;
1692 fh
= FindFirstFile (name
, &wfd
);
1693 if (fh
== INVALID_HANDLE_VALUE
)
1702 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1704 buf
->st_mode
= _S_IFDIR
;
1705 buf
->st_nlink
= 2; /* doesn't really matter */
1706 fake_inode
= 0; /* this doesn't either I think */
1708 else if (!NILP (Vw32_get_true_file_attributes
))
1710 /* This is more accurate in terms of gettting the correct number
1711 of links, but is quite slow (it is noticable when Emacs is
1712 making a list of file name completions). */
1713 BY_HANDLE_FILE_INFORMATION info
;
1715 /* No access rights required to get info. */
1716 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
1718 if (GetFileInformationByHandle (fh
, &info
))
1720 switch (GetFileType (fh
))
1722 case FILE_TYPE_DISK
:
1723 buf
->st_mode
= _S_IFREG
;
1725 case FILE_TYPE_PIPE
:
1726 buf
->st_mode
= _S_IFIFO
;
1728 case FILE_TYPE_CHAR
:
1729 case FILE_TYPE_UNKNOWN
:
1731 buf
->st_mode
= _S_IFCHR
;
1733 buf
->st_nlink
= info
.nNumberOfLinks
;
1734 /* Might as well use file index to fake inode values, but this
1735 is not guaranteed to be unique unless we keep a handle open
1736 all the time (even then there are situations where it is
1737 not unique). Reputedly, there are at most 48 bits of info
1738 (on NTFS, presumably less on FAT). */
1739 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
1750 /* Don't bother to make this information more accurate. */
1751 buf
->st_mode
= _S_IFREG
;
1757 /* Not sure if there is any point in this. */
1758 if (!NILP (Vw32_generate_fake_inodes
))
1759 fake_inode
= generate_inode_val (name
);
1760 else if (fake_inode
== 0)
1762 /* For want of something better, try to make everything unique. */
1763 static DWORD gen_num
= 0;
1764 fake_inode
= ++gen_num
;
1768 /* MSVC defines _ino_t to be short; other libc's might not. */
1769 if (sizeof (buf
->st_ino
) == 2)
1770 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
1772 buf
->st_ino
= fake_inode
;
1774 /* consider files to belong to current user */
1775 buf
->st_uid
= the_passwd
.pw_uid
;
1776 buf
->st_gid
= the_passwd
.pw_gid
;
1778 /* volume_info is set indirectly by map_w32_filename */
1779 buf
->st_dev
= volume_info
.serialnum
;
1780 buf
->st_rdev
= volume_info
.serialnum
;
1783 buf
->st_size
= wfd
.nFileSizeLow
;
1785 /* Convert timestamps to Unix format. */
1786 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
1787 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
1788 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
1789 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
1790 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
1792 /* determine rwx permissions */
1793 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
1794 permission
= _S_IREAD
;
1796 permission
= _S_IREAD
| _S_IWRITE
;
1798 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1799 permission
|= _S_IEXEC
;
1802 char * p
= strrchr (name
, '.');
1804 && (stricmp (p
, ".exe") == 0 ||
1805 stricmp (p
, ".com") == 0 ||
1806 stricmp (p
, ".bat") == 0 ||
1807 stricmp (p
, ".cmd") == 0))
1808 permission
|= _S_IEXEC
;
1811 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
1816 /* Provide fstat and utime as well as stat for consistent handling of
1819 fstat (int desc
, struct stat
* buf
)
1821 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
1822 BY_HANDLE_FILE_INFORMATION info
;
1826 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
1828 case FILE_TYPE_DISK
:
1829 buf
->st_mode
= _S_IFREG
;
1830 if (!GetFileInformationByHandle (fh
, &info
))
1836 case FILE_TYPE_PIPE
:
1837 buf
->st_mode
= _S_IFIFO
;
1839 case FILE_TYPE_CHAR
:
1840 case FILE_TYPE_UNKNOWN
:
1842 buf
->st_mode
= _S_IFCHR
;
1844 memset (&info
, 0, sizeof (info
));
1845 info
.dwFileAttributes
= 0;
1846 info
.ftCreationTime
= utc_base_ft
;
1847 info
.ftLastAccessTime
= utc_base_ft
;
1848 info
.ftLastWriteTime
= utc_base_ft
;
1851 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1853 buf
->st_mode
= _S_IFDIR
;
1854 buf
->st_nlink
= 2; /* doesn't really matter */
1855 fake_inode
= 0; /* this doesn't either I think */
1859 buf
->st_nlink
= info
.nNumberOfLinks
;
1860 /* Might as well use file index to fake inode values, but this
1861 is not guaranteed to be unique unless we keep a handle open
1862 all the time (even then there are situations where it is
1863 not unique). Reputedly, there are at most 48 bits of info
1864 (on NTFS, presumably less on FAT). */
1865 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
1868 /* MSVC defines _ino_t to be short; other libc's might not. */
1869 if (sizeof (buf
->st_ino
) == 2)
1870 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
1872 buf
->st_ino
= fake_inode
;
1874 /* consider files to belong to current user */
1878 buf
->st_dev
= info
.dwVolumeSerialNumber
;
1879 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
1881 buf
->st_size
= info
.nFileSizeLow
;
1883 /* Convert timestamps to Unix format. */
1884 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
1885 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
1886 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
1887 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
1888 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
1890 /* determine rwx permissions */
1891 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
1892 permission
= _S_IREAD
;
1894 permission
= _S_IREAD
| _S_IWRITE
;
1896 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1897 permission
|= _S_IEXEC
;
1900 #if 0 /* no way of knowing the filename */
1901 char * p
= strrchr (name
, '.');
1903 (stricmp (p
, ".exe") == 0 ||
1904 stricmp (p
, ".com") == 0 ||
1905 stricmp (p
, ".bat") == 0 ||
1906 stricmp (p
, ".cmd") == 0))
1907 permission
|= _S_IEXEC
;
1911 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
1917 utime (const char *name
, struct utimbuf
*times
)
1919 struct utimbuf deftime
;
1926 deftime
.modtime
= deftime
.actime
= time (NULL
);
1930 /* Need write access to set times. */
1931 fh
= CreateFile (name
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1932 0, OPEN_EXISTING
, 0, NULL
);
1935 convert_from_time_t (times
->actime
, &atime
);
1936 convert_from_time_t (times
->modtime
, &mtime
);
1937 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
1955 /* Wrappers for winsock functions to map between our file descriptors
1956 and winsock's handles; also set h_errno for convenience.
1958 To allow Emacs to run on systems which don't have winsock support
1959 installed, we dynamically link to winsock on startup if present, and
1960 otherwise provide the minimum necessary functionality
1961 (eg. gethostname). */
1963 /* function pointers for relevant socket functions */
1964 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
1965 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
1966 int (PASCAL
*pfn_WSAGetLastError
) (void);
1967 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
1968 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1969 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1970 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
1971 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
1972 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
1973 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
1974 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
1975 int (PASCAL
*pfn_WSACleanup
) (void);
1977 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
1978 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
1979 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
1980 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
1981 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
1982 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
1984 /* SetHandleInformation is only needed to make sockets non-inheritable. */
1985 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
1986 #ifndef HANDLE_FLAG_INHERIT
1987 #define HANDLE_FLAG_INHERIT 1
1991 static int winsock_inuse
;
1996 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
1998 /* Not sure what would cause WSAENETDOWN, or even if it can happen
1999 after WSAStartup returns successfully, but it seems reasonable
2000 to allow unloading winsock anyway in that case. */
2001 if (pfn_WSACleanup () == 0 ||
2002 pfn_WSAGetLastError () == WSAENETDOWN
)
2004 if (FreeLibrary (winsock_lib
))
2013 init_winsock (int load_now
)
2015 WSADATA winsockData
;
2017 if (winsock_lib
!= NULL
)
2020 pfn_SetHandleInformation
= NULL
;
2021 pfn_SetHandleInformation
2022 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2023 "SetHandleInformation");
2025 winsock_lib
= LoadLibrary ("wsock32.dll");
2027 if (winsock_lib
!= NULL
)
2029 /* dynamically link to socket functions */
2031 #define LOAD_PROC(fn) \
2032 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2035 LOAD_PROC( WSAStartup
);
2036 LOAD_PROC( WSASetLastError
);
2037 LOAD_PROC( WSAGetLastError
);
2038 LOAD_PROC( socket
);
2040 LOAD_PROC( connect
);
2041 LOAD_PROC( ioctlsocket
);
2044 LOAD_PROC( closesocket
);
2045 LOAD_PROC( shutdown
);
2048 LOAD_PROC( inet_addr
);
2049 LOAD_PROC( gethostname
);
2050 LOAD_PROC( gethostbyname
);
2051 LOAD_PROC( getservbyname
);
2052 LOAD_PROC( WSACleanup
);
2056 /* specify version 1.1 of winsock */
2057 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
2059 if (winsockData
.wVersion
!= 0x101)
2064 /* Report that winsock exists and is usable, but leave
2065 socket functions disabled. I am assuming that calling
2066 WSAStartup does not require any network interaction,
2067 and in particular does not cause or require a dial-up
2068 connection to be established. */
2071 FreeLibrary (winsock_lib
);
2079 FreeLibrary (winsock_lib
);
2089 /* function to set h_errno for compatability; map winsock error codes to
2090 normal system codes where they overlap (non-overlapping definitions
2091 are already in <sys/socket.h> */
2092 static void set_errno ()
2094 if (winsock_lib
== NULL
)
2097 h_errno
= pfn_WSAGetLastError ();
2101 case WSAEACCES
: h_errno
= EACCES
; break;
2102 case WSAEBADF
: h_errno
= EBADF
; break;
2103 case WSAEFAULT
: h_errno
= EFAULT
; break;
2104 case WSAEINTR
: h_errno
= EINTR
; break;
2105 case WSAEINVAL
: h_errno
= EINVAL
; break;
2106 case WSAEMFILE
: h_errno
= EMFILE
; break;
2107 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
2108 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
2113 static void check_errno ()
2115 if (h_errno
== 0 && winsock_lib
!= NULL
)
2116 pfn_WSASetLastError (0);
2119 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2120 but I believe the method of keeping the socket handle separate (and
2121 insuring it is not inheritable) is the correct one. */
2123 //#define SOCK_REPLACE_HANDLE
2125 #ifdef SOCK_REPLACE_HANDLE
2126 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2128 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2132 sys_socket(int af
, int type
, int protocol
)
2138 if (winsock_lib
== NULL
)
2141 return INVALID_SOCKET
;
2146 /* call the real socket function */
2147 s
= (long) pfn_socket (af
, type
, protocol
);
2149 if (s
!= INVALID_SOCKET
)
2151 /* Although under NT 3.5 _open_osfhandle will accept a socket
2152 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2153 that does not work under NT 3.1. However, we can get the same
2154 effect by using a backdoor function to replace an existing
2155 descriptor handle with the one we want. */
2157 /* allocate a file descriptor (with appropriate flags) */
2158 fd
= _open ("NUL:", _O_RDWR
);
2161 #ifdef SOCK_REPLACE_HANDLE
2162 /* now replace handle to NUL with our socket handle */
2163 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
2165 _set_osfhnd (fd
, s
);
2166 /* setmode (fd, _O_BINARY); */
2168 /* Make a non-inheritable copy of the socket handle. */
2171 HANDLE new_s
= INVALID_HANDLE_VALUE
;
2173 parent
= GetCurrentProcess ();
2175 /* Apparently there is a bug in NT 3.51 with some service
2176 packs, which prevents using DuplicateHandle to make a
2177 socket handle non-inheritable (causes WSACleanup to
2178 hang). The work-around is to use SetHandleInformation
2179 instead if it is available and implemented. */
2180 if (!pfn_SetHandleInformation
2181 || !pfn_SetHandleInformation ((HANDLE
) s
,
2182 HANDLE_FLAG_INHERIT
,
2185 DuplicateHandle (parent
,
2191 DUPLICATE_SAME_ACCESS
);
2192 pfn_closesocket (s
);
2195 fd_info
[fd
].hnd
= (HANDLE
) s
;
2199 /* set our own internal flags */
2200 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
2206 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2208 /* attach child_process to fd_info */
2209 if (fd_info
[ fd
].cp
!= NULL
)
2211 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
2215 fd_info
[ fd
].cp
= cp
;
2218 winsock_inuse
++; /* count open sockets */
2225 pfn_closesocket (s
);
2235 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
2237 if (winsock_lib
== NULL
)
2240 return SOCKET_ERROR
;
2244 if (fd_info
[s
].flags
& FILE_SOCKET
)
2246 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
2247 if (rc
== SOCKET_ERROR
)
2252 return SOCKET_ERROR
;
2257 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
2259 if (winsock_lib
== NULL
)
2262 return SOCKET_ERROR
;
2266 if (fd_info
[s
].flags
& FILE_SOCKET
)
2268 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
2269 if (rc
== SOCKET_ERROR
)
2274 return SOCKET_ERROR
;
2278 sys_htons (u_short hostshort
)
2280 return (winsock_lib
!= NULL
) ?
2281 pfn_htons (hostshort
) : hostshort
;
2285 sys_ntohs (u_short netshort
)
2287 return (winsock_lib
!= NULL
) ?
2288 pfn_ntohs (netshort
) : netshort
;
2292 sys_inet_addr (const char * cp
)
2294 return (winsock_lib
!= NULL
) ?
2295 pfn_inet_addr (cp
) : INADDR_NONE
;
2299 sys_gethostname (char * name
, int namelen
)
2301 if (winsock_lib
!= NULL
)
2302 return pfn_gethostname (name
, namelen
);
2304 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
2305 return !GetComputerName (name
, &namelen
);
2308 return SOCKET_ERROR
;
2312 sys_gethostbyname(const char * name
)
2314 struct hostent
* host
;
2316 if (winsock_lib
== NULL
)
2323 host
= pfn_gethostbyname (name
);
2330 sys_getservbyname(const char * name
, const char * proto
)
2332 struct servent
* serv
;
2334 if (winsock_lib
== NULL
)
2341 serv
= pfn_getservbyname (name
, proto
);
2348 sys_shutdown (int s
, int how
)
2352 if (winsock_lib
== NULL
)
2355 return SOCKET_ERROR
;
2359 if (fd_info
[s
].flags
& FILE_SOCKET
)
2361 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
2362 if (rc
== SOCKET_ERROR
)
2367 return SOCKET_ERROR
;
2370 #endif /* HAVE_SOCKETS */
2373 /* Shadow main io functions: we need to handle pipes and sockets more
2374 intelligently, and implement non-blocking mode as well. */
2381 if (fd
< 0 || fd
>= MAXDESC
)
2389 child_process
* cp
= fd_info
[fd
].cp
;
2391 fd_info
[fd
].cp
= NULL
;
2393 if (CHILD_ACTIVE (cp
))
2395 /* if last descriptor to active child_process then cleanup */
2397 for (i
= 0; i
< MAXDESC
; i
++)
2401 if (fd_info
[i
].cp
== cp
)
2407 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2409 #ifndef SOCK_REPLACE_HANDLE
2410 if (winsock_lib
== NULL
) abort ();
2412 pfn_shutdown (SOCK_HANDLE (fd
), 2);
2413 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
2415 winsock_inuse
--; /* count open sockets */
2423 /* Note that sockets do not need special treatment here (at least on
2424 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2425 closesocket is equivalent to CloseHandle, which is to be expected
2426 because socket handles are fully fledged kernel handles. */
2430 fd_info
[fd
].flags
= 0;
2443 /* duplicate our internal info as well */
2444 fd_info
[new_fd
] = fd_info
[fd
];
2451 sys_dup2 (int src
, int dst
)
2455 if (dst
< 0 || dst
>= MAXDESC
)
2461 /* make sure we close the destination first if it's a pipe or socket */
2462 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
2465 rc
= _dup2 (src
, dst
);
2468 /* duplicate our internal info as well */
2469 fd_info
[dst
] = fd_info
[src
];
2474 /* Unix pipe() has only one arg */
2476 sys_pipe (int * phandles
)
2482 /* make pipe handles non-inheritable; when we spawn a child, we
2483 replace the relevant handle with an inheritable one. Also put
2484 pipes into binary mode; we will do text mode translation ourselves
2486 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
2490 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
2491 fd_info
[phandles
[0]].flags
= flags
;
2493 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
2494 fd_info
[phandles
[1]].flags
= flags
;
2501 extern Lisp_Object Vw32_pipe_read_delay
;
2503 /* Function to do blocking read of one byte, needed to implement
2504 select. It is only allowed on sockets and pipes. */
2506 _sys_read_ahead (int fd
)
2511 if (fd
< 0 || fd
>= MAXDESC
)
2512 return STATUS_READ_ERROR
;
2514 cp
= fd_info
[fd
].cp
;
2516 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
2517 return STATUS_READ_ERROR
;
2519 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
2520 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
2522 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
2526 cp
->status
= STATUS_READ_IN_PROGRESS
;
2528 if (fd_info
[fd
].flags
& FILE_PIPE
)
2530 rc
= _read (fd
, &cp
->chr
, sizeof (char));
2532 /* Give subprocess time to buffer some more output for us before
2533 reporting that input is available; we need this because Windows 95
2534 connects DOS programs to pipes by making the pipe appear to be
2535 the normal console stdout - as a result most DOS programs will
2536 write to stdout without buffering, ie. one character at a
2537 time. Even some W32 programs do this - "dir" in a command
2538 shell on NT is very slow if we don't do this. */
2541 int wait
= XINT (Vw32_pipe_read_delay
);
2547 /* Yield remainder of our time slice, effectively giving a
2548 temporary priority boost to the child process. */
2553 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
2554 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
2557 if (rc
== sizeof (char))
2558 cp
->status
= STATUS_READ_SUCCEEDED
;
2560 cp
->status
= STATUS_READ_FAILED
;
2566 sys_read (int fd
, char * buffer
, unsigned int count
)
2571 char * orig_buffer
= buffer
;
2573 if (fd
< 0 || fd
>= MAXDESC
)
2579 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2581 child_process
*cp
= fd_info
[fd
].cp
;
2583 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
2591 /* re-read CR carried over from last read */
2592 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
2594 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
2598 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
2601 /* presence of a child_process structure means we are operating in
2602 non-blocking mode - otherwise we just call _read directly.
2603 Note that the child_process structure might be missing because
2604 reap_subprocess has been called; in this case the pipe is
2605 already broken, so calling _read on it is okay. */
2608 int current_status
= cp
->status
;
2610 switch (current_status
)
2612 case STATUS_READ_FAILED
:
2613 case STATUS_READ_ERROR
:
2614 /* report normal EOF if nothing in buffer */
2616 fd_info
[fd
].flags
|= FILE_AT_EOF
;
2619 case STATUS_READ_READY
:
2620 case STATUS_READ_IN_PROGRESS
:
2621 DebPrint (("sys_read called when read is in progress\n"));
2622 errno
= EWOULDBLOCK
;
2625 case STATUS_READ_SUCCEEDED
:
2626 /* consume read-ahead char */
2627 *buffer
++ = cp
->chr
;
2630 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2631 ResetEvent (cp
->char_avail
);
2633 case STATUS_READ_ACKNOWLEDGED
:
2637 DebPrint (("sys_read: bad status %d\n", current_status
));
2642 if (fd_info
[fd
].flags
& FILE_PIPE
)
2644 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
2645 to_read
= min (waiting
, (DWORD
) count
);
2648 nchars
+= _read (fd
, buffer
, to_read
);
2651 else /* FILE_SOCKET */
2653 if (winsock_lib
== NULL
) abort ();
2655 /* do the equivalent of a non-blocking read */
2656 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
2657 if (waiting
== 0 && nchars
== 0)
2659 h_errno
= errno
= EWOULDBLOCK
;
2665 /* always use binary mode for sockets */
2666 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
2667 if (res
== SOCKET_ERROR
)
2669 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
2670 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2681 int nread
= _read (fd
, buffer
, count
);
2684 else if (nchars
== 0)
2689 fd_info
[fd
].flags
|= FILE_AT_EOF
;
2690 /* Perform text mode translation if required. */
2691 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2693 nchars
= crlf_to_lf (nchars
, orig_buffer
);
2694 /* If buffer contains only CR, return that. To be absolutely
2695 sure we should attempt to read the next char, but in
2696 practice a CR to be followed by LF would not appear by
2697 itself in the buffer. */
2698 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
2700 fd_info
[fd
].flags
|= FILE_LAST_CR
;
2706 nchars
= _read (fd
, buffer
, count
);
2711 /* For now, don't bother with a non-blocking mode */
2713 sys_write (int fd
, const void * buffer
, unsigned int count
)
2717 if (fd
< 0 || fd
>= MAXDESC
)
2723 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2725 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
2731 /* Perform text mode translation if required. */
2732 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2734 char * tmpbuf
= alloca (count
* 2);
2735 unsigned char * src
= (void *)buffer
;
2736 unsigned char * dst
= tmpbuf
;
2741 unsigned char *next
;
2742 /* copy next line or remaining bytes */
2743 next
= _memccpy (dst
, src
, '\n', nbytes
);
2746 /* copied one line ending with '\n' */
2747 int copied
= next
- dst
;
2750 /* insert '\r' before '\n' */
2757 /* copied remaining partial line -> now finished */
2765 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2767 if (winsock_lib
== NULL
) abort ();
2768 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
2769 if (nchars
== SOCKET_ERROR
)
2771 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
2772 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2778 nchars
= _write (fd
, buffer
, count
);
2784 check_windows_init_file ()
2786 extern int noninteractive
, inhibit_window_system
;
2788 /* A common indication that Emacs is not installed properly is when
2789 it cannot find the Windows installation file. If this file does
2790 not exist in the expected place, tell the user. */
2792 if (!noninteractive
&& !inhibit_window_system
) {
2793 extern Lisp_Object Vwindow_system
, Vload_path
;
2794 Lisp_Object init_file
;
2797 init_file
= build_string ("term/w32-win");
2798 fd
= openp (Vload_path
, init_file
, ".el:.elc", NULL
, 0);
2800 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
2801 char *init_file_name
= XSTRING (init_file
)->data
;
2802 char *load_path
= XSTRING (load_path_print
)->data
;
2803 char *buffer
= alloca (1024);
2806 "The Emacs Windows initialization file \"%s.el\" "
2807 "could not be found in your Emacs installation. "
2808 "Emacs checked the following directories for this file:\n"
2810 "When Emacs cannot find this file, it usually means that it "
2811 "was not installed properly, or its distribution file was "
2812 "not unpacked properly.\nSee the README.W32 file in the "
2813 "top-level Emacs directory for more information.",
2814 init_file_name
, load_path
);
2817 "Emacs Abort Dialog",
2818 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
2821 /* Use the low-level Emacs abort. */
2832 /* shutdown the socket interface if necessary */
2836 /* Check whether we are shutting down because we cannot find the
2837 Windows initialization file. Do this during shutdown so that
2838 Emacs is initialized as possible, and so that it is out of the
2839 critical startup path. */
2840 check_windows_init_file ();
2847 /* Initialise the socket interface now if available and requested by
2848 the user by defining PRELOAD_WINSOCK; otherwise loading will be
2849 delayed until open-network-stream is called (w32-has-winsock can
2850 also be used to dynamically load or reload winsock).
2852 Conveniently, init_environment is called before us, so
2853 PRELOAD_WINSOCK can be set in the registry. */
2855 /* Always initialize this correctly. */
2858 if (getenv ("PRELOAD_WINSOCK") != NULL
)
2859 init_winsock (TRUE
);
2862 /* Initial preparation for subprocess support: replace our standard
2863 handles with non-inheritable versions. */
2866 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
2867 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
2868 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
2870 parent
= GetCurrentProcess ();
2872 /* ignore errors when duplicating and closing; typically the
2873 handles will be invalid when running as a gui program. */
2874 DuplicateHandle (parent
,
2875 GetStdHandle (STD_INPUT_HANDLE
),
2880 DUPLICATE_SAME_ACCESS
);
2882 DuplicateHandle (parent
,
2883 GetStdHandle (STD_OUTPUT_HANDLE
),
2888 DUPLICATE_SAME_ACCESS
);
2890 DuplicateHandle (parent
,
2891 GetStdHandle (STD_ERROR_HANDLE
),
2896 DUPLICATE_SAME_ACCESS
);
2902 if (stdin_save
!= INVALID_HANDLE_VALUE
)
2903 _open_osfhandle ((long) stdin_save
, O_TEXT
);
2905 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
2908 if (stdout_save
!= INVALID_HANDLE_VALUE
)
2909 _open_osfhandle ((long) stdout_save
, O_TEXT
);
2911 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2914 if (stderr_save
!= INVALID_HANDLE_VALUE
)
2915 _open_osfhandle ((long) stderr_save
, O_TEXT
);
2917 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2921 /* unfortunately, atexit depends on implementation of malloc */
2922 /* atexit (term_ntproc); */
2923 signal (SIGABRT
, term_ntproc
);
2925 /* determine which drives are fixed, for GetCachedVolumeInformation */
2927 /* GetDriveType must have trailing backslash. */
2928 char drive
[] = "A:\\";
2930 /* Loop over all possible drive letters */
2931 while (*drive
<= 'Z')
2933 /* Record if this drive letter refers to a fixed drive. */
2934 fixed_drives
[DRIVE_INDEX (*drive
)] =
2935 (GetDriveType (drive
) == DRIVE_FIXED
);