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 /* must include CRT headers *before* config.h */
64 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
65 #include <sys/socket.h>
84 #define min(x, y) (((x) < (y)) ? (x) : (y))
85 #define max(x, y) (((x) > (y)) ? (x) : (y))
87 extern Lisp_Object Vw32_downcase_file_names
;
88 extern Lisp_Object Vw32_generate_fake_inodes
;
89 extern Lisp_Object Vw32_get_true_file_attributes
;
91 static char startup_dir
[MAXPATHLEN
];
93 /* Get the current working directory. */
98 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
102 /* Emacs doesn't actually change directory itself, and we want to
103 force our real wd to be where emacs.exe is to avoid unnecessary
104 conflicts when trying to rename or delete directories. */
105 strcpy (dir
, startup_dir
);
111 /* Emulate gethostname. */
113 gethostname (char *buffer
, int size
)
115 /* NT only allows small host names, so the buffer is
116 certainly large enough. */
117 return !GetComputerName (buffer
, &size
);
119 #endif /* HAVE_SOCKETS */
121 /* Emulate getloadavg. */
123 getloadavg (double loadavg
[], int nelem
)
127 /* A faithful emulation is going to have to be saved for a rainy day. */
128 for (i
= 0; i
< nelem
; i
++)
135 /* Emulate getpwuid, getpwnam and others. */
137 #define PASSWD_FIELD_SIZE 256
139 static char the_passwd_name
[PASSWD_FIELD_SIZE
];
140 static char the_passwd_passwd
[PASSWD_FIELD_SIZE
];
141 static char the_passwd_gecos
[PASSWD_FIELD_SIZE
];
142 static char the_passwd_dir
[PASSWD_FIELD_SIZE
];
143 static char the_passwd_shell
[PASSWD_FIELD_SIZE
];
145 static struct passwd the_passwd
=
160 return the_passwd
.pw_uid
;
166 /* I could imagine arguing for checking to see whether the user is
167 in the Administrators group and returning a UID of 0 for that
168 case, but I don't know how wise that would be in the long run. */
175 return the_passwd
.pw_gid
;
187 if (uid
== the_passwd
.pw_uid
)
193 getpwnam (char *name
)
197 pw
= getpwuid (getuid ());
201 if (stricmp (name
, pw
->pw_name
))
210 /* Find the user's real name by opening the process token and
211 looking up the name associated with the user-sid in that token.
213 Use the relative portion of the identifier authority value from
214 the user-sid as the user id value (same for group id using the
215 primary group sid from the process token). */
217 char user_sid
[256], name
[256], domain
[256];
218 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
220 SID_NAME_USE user_type
;
222 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &token
)
223 && GetTokenInformation (token
, TokenUser
,
224 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
225 && LookupAccountSid (NULL
, *((PSID
*) user_sid
), name
, &length
,
226 domain
, &dlength
, &user_type
))
228 strcpy (the_passwd
.pw_name
, name
);
229 /* Determine a reasonable uid value. */
230 if (stricmp ("administrator", name
) == 0)
232 the_passwd
.pw_uid
= 0;
233 the_passwd
.pw_gid
= 0;
237 SID_IDENTIFIER_AUTHORITY
* pSIA
;
239 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
240 /* I believe the relative portion is the last 4 bytes (of 6)
242 the_passwd
.pw_uid
= ((pSIA
->Value
[2] << 24) +
243 (pSIA
->Value
[3] << 16) +
244 (pSIA
->Value
[4] << 8) +
245 (pSIA
->Value
[5] << 0));
246 /* restrict to conventional uid range for normal users */
247 the_passwd
.pw_uid
= the_passwd
.pw_uid
% 60001;
250 if (GetTokenInformation (token
, TokenPrimaryGroup
,
251 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
253 SID_IDENTIFIER_AUTHORITY
* pSIA
;
255 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
256 the_passwd
.pw_gid
= ((pSIA
->Value
[2] << 24) +
257 (pSIA
->Value
[3] << 16) +
258 (pSIA
->Value
[4] << 8) +
259 (pSIA
->Value
[5] << 0));
260 /* I don't know if this is necessary, but for safety... */
261 the_passwd
.pw_gid
= the_passwd
.pw_gid
% 60001;
264 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
267 /* If security calls are not supported (presumably because we
268 are running under Windows 95), fallback to this. */
269 else if (GetUserName (name
, &length
))
271 strcpy (the_passwd
.pw_name
, name
);
272 if (stricmp ("administrator", name
) == 0)
273 the_passwd
.pw_uid
= 0;
275 the_passwd
.pw_uid
= 123;
276 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
280 strcpy (the_passwd
.pw_name
, "unknown");
281 the_passwd
.pw_uid
= 123;
282 the_passwd
.pw_gid
= 123;
285 /* Ensure HOME and SHELL are defined. */
286 if (getenv ("HOME") == NULL
)
288 if (getenv ("SHELL") == NULL
)
289 putenv (os_subtype
== OS_WIN95
? "SHELL=command" : "SHELL=cmd");
291 /* Set dir and shell from environment variables. */
292 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
293 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
302 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
303 return ((rand () << 15) | rand ());
313 /* Normalize filename by converting all path separators to
314 the specified separator. Also conditionally convert upper
315 case path name components to lower case. */
318 normalize_filename (fp
, path_sep
)
325 /* Always lower-case drive letters a-z, even if the filesystem
326 preserves case in filenames.
327 This is so filenames can be compared by string comparison
328 functions that are case-sensitive. Even case-preserving filesystems
329 do not distinguish case in drive letters. */
330 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
336 if (NILP (Vw32_downcase_file_names
))
340 if (*fp
== '/' || *fp
== '\\')
347 sep
= path_sep
; /* convert to this path separator */
348 elem
= fp
; /* start of current path element */
351 if (*fp
>= 'a' && *fp
<= 'z')
352 elem
= 0; /* don't convert this element */
354 if (*fp
== 0 || *fp
== ':')
356 sep
= *fp
; /* restore current separator (or 0) */
357 *fp
= '/'; /* after conversion of this element */
360 if (*fp
== '/' || *fp
== '\\')
362 if (elem
&& elem
!= fp
)
364 *fp
= 0; /* temporary end of string */
365 _strlwr (elem
); /* while we convert to lower case */
367 *fp
= sep
; /* convert (or restore) path separator */
368 elem
= fp
+ 1; /* next element starts after separator */
374 /* Destructively turn backslashes into slashes. */
376 dostounix_filename (p
)
379 normalize_filename (p
, '/');
382 /* Destructively turn slashes into backslashes. */
384 unixtodos_filename (p
)
387 normalize_filename (p
, '\\');
390 /* Remove all CR's that are followed by a LF.
391 (From msdos.c...probably should figure out a way to share it,
392 although this code isn't going to ever change.) */
396 register unsigned char *buf
;
398 unsigned char *np
= buf
;
399 unsigned char *startp
= buf
;
400 unsigned char *endp
= buf
+ n
;
404 while (buf
< endp
- 1)
408 if (*(++buf
) != 0x0a)
419 /* Parse the root part of file name, if present. Return length and
420 optionally store pointer to char after root. */
422 parse_root (char * name
, char ** pPath
)
429 /* find the root name of the volume if given */
430 if (isalpha (name
[0]) && name
[1] == ':')
432 /* skip past drive specifier */
434 if (IS_DIRECTORY_SEP (name
[0]))
437 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
443 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
448 if (IS_DIRECTORY_SEP (name
[0]))
458 /* Get long base name for name; name is assumed to be absolute. */
460 get_long_basename (char * name
, char * buf
, int size
)
462 WIN32_FIND_DATA find_data
;
466 dir_handle
= FindFirstFile (name
, &find_data
);
467 if (dir_handle
!= INVALID_HANDLE_VALUE
)
469 if ((len
= strlen (find_data
.cFileName
)) < size
)
470 memcpy (buf
, find_data
.cFileName
, len
+ 1);
473 FindClose (dir_handle
);
478 /* Get long name for file, if possible (assumed to be absolute). */
480 w32_get_long_filename (char * name
, char * buf
, int size
)
485 char full
[ MAX_PATH
];
492 /* Use local copy for destructive modification. */
493 memcpy (full
, name
, len
+1);
494 unixtodos_filename (full
);
496 /* Copy root part verbatim. */
497 len
= parse_root (full
, &p
);
498 memcpy (o
, full
, len
);
505 p
= strchr (q
, '\\');
507 len
= get_long_basename (full
, o
, size
);
525 while (p
!= NULL
&& *p
);
531 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
534 sigsetmask (int signal_mask
)
546 setpgrp (int pid
, int gid
)
558 unrequest_sigio (void)
569 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
572 w32_get_resource (key
, lpdwtype
)
577 HKEY hrootkey
= NULL
;
581 /* Check both the current user and the local machine to see if
582 we have any resources. */
584 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
588 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
589 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
590 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
595 if (lpvalue
) xfree (lpvalue
);
597 RegCloseKey (hrootkey
);
600 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
604 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
605 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
606 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
611 if (lpvalue
) xfree (lpvalue
);
613 RegCloseKey (hrootkey
);
619 char *get_emacs_configuration (void);
620 extern Lisp_Object Vsystem_configuration
;
625 /* Check for environment variables and use registry if they don't exist */
631 static char * env_vars
[] =
642 /* We no longer set INFOPATH because Info-default-directory-list
643 is then ignored. We use a hook in winnt.el instead. */
649 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
651 if (!getenv (env_vars
[i
])
652 && (lpval
= w32_get_resource (env_vars
[i
], &dwType
)) != NULL
)
654 if (dwType
== REG_EXPAND_SZ
)
656 char buf1
[500], buf2
[500];
658 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, 500);
659 _snprintf (buf2
, 499, "%s=%s", env_vars
[i
], buf1
);
660 putenv (strdup (buf2
));
662 else if (dwType
== REG_SZ
)
666 _snprintf (buf
, 499, "%s=%s", env_vars
[i
], lpval
);
667 putenv (strdup (buf
));
675 /* Rebuild system configuration to reflect invoking system. */
676 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
678 /* Another special case: on NT, the PATH variable is actually named
679 "Path" although cmd.exe (perhaps NT itself) arranges for
680 environment variable lookup and setting to be case insensitive.
681 However, Emacs assumes a fully case sensitive environment, so we
682 need to change "Path" to "PATH" to match the expectations of
683 various elisp packages. We do this by the sneaky method of
684 modifying the string in the C runtime environ entry.
686 The same applies to COMSPEC. */
690 for (envp
= environ
; *envp
; envp
++)
691 if (_strnicmp (*envp
, "PATH=", 5) == 0)
692 memcpy (*envp
, "PATH=", 5);
693 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
694 memcpy (*envp
, "COMSPEC=", 8);
697 /* Remember the initial working directory for getwd, then make the
698 real wd be the location of emacs.exe to avoid conflicts when
699 renaming or deleting directories. (We also don't call chdir when
700 running subprocesses for the same reason.) */
701 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
706 char modname
[MAX_PATH
];
708 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
710 if ((p
= strrchr (modname
, '\\')) == NULL
)
714 SetCurrentDirectory (modname
);
720 /* We don't have scripts to automatically determine the system configuration
721 for Emacs before it's compiled, and we don't want to have to make the
722 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
725 static char configuration_buffer
[32];
728 get_emacs_configuration (void)
730 char *arch
, *oem
, *os
;
732 /* Determine the processor type. */
733 switch (get_processor_type ())
736 #ifdef PROCESSOR_INTEL_386
737 case PROCESSOR_INTEL_386
:
738 case PROCESSOR_INTEL_486
:
739 case PROCESSOR_INTEL_PENTIUM
:
744 #ifdef PROCESSOR_INTEL_860
745 case PROCESSOR_INTEL_860
:
750 #ifdef PROCESSOR_MIPS_R2000
751 case PROCESSOR_MIPS_R2000
:
752 case PROCESSOR_MIPS_R3000
:
753 case PROCESSOR_MIPS_R4000
:
758 #ifdef PROCESSOR_ALPHA_21064
759 case PROCESSOR_ALPHA_21064
:
769 /* Let oem be "*" until we figure out how to decode the OEM field. */
772 os
= (GetVersion () & OS_WIN95
) ? "windows95" : "nt";
774 sprintf (configuration_buffer
, "%s-%s-%s%d.%d", arch
, oem
, os
,
775 get_w32_major_version (), get_w32_minor_version ());
776 return configuration_buffer
;
779 #include <sys/timeb.h>
781 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
783 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
788 tv
->tv_sec
= tb
.time
;
789 tv
->tv_usec
= tb
.millitm
* 1000L;
792 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
793 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
797 /* ------------------------------------------------------------------------- */
798 /* IO support and wrapper functions for W32 API. */
799 /* ------------------------------------------------------------------------- */
801 /* Place a wrapper around the MSVC version of ctime. It returns NULL
802 on network directories, so we handle that case here.
803 (Ulrich Leodolter, 1/11/95). */
805 sys_ctime (const time_t *t
)
807 char *str
= (char *) ctime (t
);
808 return (str
? str
: "Sun Jan 01 00:00:00 1970");
811 /* Emulate sleep...we could have done this with a define, but that
812 would necessitate including windows.h in the files that used it.
813 This is much easier. */
815 sys_sleep (int seconds
)
817 Sleep (seconds
* 1000);
820 /* Internal MSVC functions for low-level descriptor munging */
821 extern int __cdecl
_set_osfhnd (int fd
, long h
);
822 extern int __cdecl
_free_osfhnd (int fd
);
824 /* parallel array of private info on file handles */
825 filedesc fd_info
[ MAXDESC
];
827 typedef struct volume_info_data
{
828 struct volume_info_data
* next
;
830 /* time when info was obtained */
833 /* actual volume info */
842 /* Global referenced by various functions. */
843 static volume_info_data volume_info
;
845 /* Vector to indicate which drives are local and fixed (for which cached
846 data never expires). */
847 static BOOL fixed_drives
[26];
849 /* Consider cached volume information to be stale if older than 10s,
850 at least for non-local drives. Info for fixed drives is never stale. */
851 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
852 #define VOLINFO_STILL_VALID( root_dir, info ) \
853 ( ( isalpha (root_dir[0]) && \
854 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
855 || GetTickCount () - info->timestamp < 10000 )
857 /* Cache support functions. */
859 /* Simple linked list with linear search is sufficient. */
860 static volume_info_data
*volume_cache
= NULL
;
862 static volume_info_data
*
863 lookup_volume_info (char * root_dir
)
865 volume_info_data
* info
;
867 for (info
= volume_cache
; info
; info
= info
->next
)
868 if (stricmp (info
->root_dir
, root_dir
) == 0)
874 add_volume_info (char * root_dir
, volume_info_data
* info
)
876 info
->root_dir
= strdup (root_dir
);
877 info
->next
= volume_cache
;
882 /* Wrapper for GetVolumeInformation, which uses caching to avoid
883 performance penalty (~2ms on 486 for local drives, 7.5ms for local
884 cdrom drive, ~5-10ms or more for remote drives on LAN). */
886 GetCachedVolumeInformation (char * root_dir
)
888 volume_info_data
* info
;
889 char default_root
[ MAX_PATH
];
891 /* NULL for root_dir means use root from current directory. */
892 if (root_dir
== NULL
)
894 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
896 parse_root (default_root
, &root_dir
);
898 root_dir
= default_root
;
901 /* Local fixed drives can be cached permanently. Removable drives
902 cannot be cached permanently, since the volume name and serial
903 number (if nothing else) can change. Remote drives should be
904 treated as if they are removable, since there is no sure way to
905 tell whether they are or not. Also, the UNC association of drive
906 letters mapped to remote volumes can be changed at any time (even
907 by other processes) without notice.
909 As a compromise, so we can benefit from caching info for remote
910 volumes, we use a simple expiry mechanism to invalidate cache
911 entries that are more than ten seconds old. */
914 /* No point doing this, because WNetGetConnection is even slower than
915 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
916 GetDriveType is about the only call of this type which does not
917 involve network access, and so is extremely quick). */
919 /* Map drive letter to UNC if remote. */
920 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
922 char remote_name
[ 256 ];
923 char drive
[3] = { root_dir
[0], ':' };
925 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
931 info
= lookup_volume_info (root_dir
);
933 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
941 /* Info is not cached, or is stale. */
942 if (!GetVolumeInformation (root_dir
,
947 type
, sizeof (type
)))
950 /* Cache the volume information for future use, overwriting existing
954 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
955 add_volume_info (root_dir
, info
);
963 info
->name
= strdup (name
);
964 info
->serialnum
= serialnum
;
965 info
->maxcomp
= maxcomp
;
967 info
->type
= strdup (type
);
968 info
->timestamp
= GetTickCount ();
974 /* Get information on the volume where name is held; set path pointer to
975 start of pathname in name (past UNC header\volume header if present). */
977 get_volume_info (const char * name
, const char ** pPath
)
980 char *rootname
= NULL
; /* default to current volume */
981 volume_info_data
* info
;
986 /* find the root name of the volume if given */
987 if (isalpha (name
[0]) && name
[1] == ':')
995 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1002 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1015 info
= GetCachedVolumeInformation (rootname
);
1018 /* Set global referenced by other functions. */
1019 volume_info
= *info
;
1025 /* Determine if volume is FAT format (ie. only supports short 8.3
1026 names); also set path pointer to start of pathname in name. */
1028 is_fat_volume (const char * name
, const char ** pPath
)
1030 if (get_volume_info (name
, pPath
))
1031 return (volume_info
.maxcomp
== 12);
1035 /* Map filename to a legal 8.3 name if necessary. */
1037 map_w32_filename (const char * name
, const char ** pPath
)
1039 static char shortname
[MAX_PATH
];
1040 char * str
= shortname
;
1043 const char * save_name
= name
;
1045 if (is_fat_volume (name
, &path
)) /* truncate to 8.3 */
1047 register int left
= 8; /* maximum number of chars in part */
1048 register int extn
= 0; /* extension added? */
1049 register int dots
= 2; /* maximum number of dots allowed */
1052 *str
++ = *name
++; /* skip past UNC header */
1054 while ((c
= *name
++))
1061 extn
= 0; /* reset extension flags */
1062 dots
= 2; /* max 2 dots */
1063 left
= 8; /* max length 8 for main part */
1067 extn
= 0; /* reset extension flags */
1068 dots
= 2; /* max 2 dots */
1069 left
= 8; /* max length 8 for main part */
1074 /* Convert path components of the form .xxx to _xxx,
1075 but leave . and .. as they are. This allows .emacs
1076 to be read as _emacs, for example. */
1080 IS_DIRECTORY_SEP (*name
))
1095 extn
= 1; /* we've got an extension */
1096 left
= 3; /* 3 chars in extension */
1100 /* any embedded dots after the first are converted to _ */
1105 case '#': /* don't lose these, they're important */
1107 str
[-1] = c
; /* replace last character of part */
1112 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1114 dots
= 0; /* started a path component */
1123 strcpy (shortname
, name
);
1124 unixtodos_filename (shortname
);
1128 *pPath
= shortname
+ (path
- save_name
);
1133 /* Emulate the Unix directory procedures opendir, closedir,
1134 and readdir. We can't use the procedures supplied in sysdep.c,
1135 so we provide them here. */
1137 struct direct dir_static
; /* simulated directory contents */
1138 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1139 static int dir_is_fat
;
1140 static char dir_pathname
[MAXPATHLEN
+1];
1141 static WIN32_FIND_DATA dir_find_data
;
1144 opendir (char *filename
)
1148 /* Opening is done by FindFirstFile. However, a read is inherent to
1149 this operation, so we defer the open until read time. */
1151 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1153 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1160 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1161 dir_pathname
[MAXPATHLEN
] = '\0';
1162 dir_is_fat
= is_fat_volume (filename
, NULL
);
1168 closedir (DIR *dirp
)
1170 /* If we have a find-handle open, close it. */
1171 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1173 FindClose (dir_find_handle
);
1174 dir_find_handle
= INVALID_HANDLE_VALUE
;
1176 xfree ((char *) dirp
);
1182 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1183 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1185 char filename
[MAXNAMLEN
+ 3];
1188 strcpy (filename
, dir_pathname
);
1189 ln
= strlen (filename
) - 1;
1190 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1191 strcat (filename
, "\\");
1192 strcat (filename
, "*");
1194 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1196 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1201 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1205 /* Emacs never uses this value, so don't bother making it match
1206 value returned by stat(). */
1207 dir_static
.d_ino
= 1;
1209 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1210 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1212 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1213 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1215 _strlwr (dir_static
.d_name
);
1216 else if (!NILP (Vw32_downcase_file_names
))
1219 for (p
= dir_static
.d_name
; *p
; p
++)
1220 if (*p
>= 'a' && *p
<= 'z')
1223 _strlwr (dir_static
.d_name
);
1230 /* Shadow some MSVC runtime functions to map requests for long filenames
1231 to reasonable short names if necessary. This was originally added to
1232 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1236 sys_access (const char * path
, int mode
)
1238 return _access (map_w32_filename (path
, NULL
), mode
);
1242 sys_chdir (const char * path
)
1244 return _chdir (map_w32_filename (path
, NULL
));
1248 sys_chmod (const char * path
, int mode
)
1250 return _chmod (map_w32_filename (path
, NULL
), mode
);
1254 sys_creat (const char * path
, int mode
)
1256 return _creat (map_w32_filename (path
, NULL
), mode
);
1260 sys_fopen(const char * path
, const char * mode
)
1264 const char * mode_save
= mode
;
1266 /* Force all file handles to be non-inheritable. This is necessary to
1267 ensure child processes don't unwittingly inherit handles that might
1268 prevent future file access. */
1272 else if (mode
[0] == 'w' || mode
[0] == 'a')
1273 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1277 /* Only do simplistic option parsing. */
1281 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1284 else if (mode
[0] == 'b')
1289 else if (mode
[0] == 't')
1296 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1300 return _fdopen (fd
, mode_save
);
1303 /* This only works on NTFS volumes, but is useful to have. */
1305 sys_link (const char * old
, const char * new)
1309 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
1311 if (old
== NULL
|| new == NULL
)
1317 strcpy (oldname
, map_w32_filename (old
, NULL
));
1318 strcpy (newname
, map_w32_filename (new, NULL
));
1320 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
1321 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1322 if (fileh
!= INVALID_HANDLE_VALUE
)
1326 /* Confusingly, the "alternate" stream name field does not apply
1327 when restoring a hard link, and instead contains the actual
1328 stream data for the link (ie. the name of the link to create).
1329 The WIN32_STREAM_ID structure before the cStreamName field is
1330 the stream header, which is then immediately followed by the
1334 WIN32_STREAM_ID wid
;
1335 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
1338 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
1339 data
.wid
.cStreamName
, MAX_PATH
);
1342 LPVOID context
= NULL
;
1345 data
.wid
.dwStreamId
= BACKUP_LINK
;
1346 data
.wid
.dwStreamAttributes
= 0;
1347 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
1348 data
.wid
.Size
.HighPart
= 0;
1349 data
.wid
.dwStreamNameSize
= 0;
1351 if (BackupWrite (fileh
, (LPBYTE
)&data
,
1352 offsetof (WIN32_STREAM_ID
, cStreamName
)
1353 + data
.wid
.Size
.LowPart
,
1354 &wbytes
, FALSE
, FALSE
, &context
)
1355 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
1362 /* Should try mapping GetLastError to errno; for now just
1363 indicate a general error (eg. links not supported). */
1364 errno
= EINVAL
; // perhaps EMLINK?
1368 CloseHandle (fileh
);
1377 sys_mkdir (const char * path
)
1379 return _mkdir (map_w32_filename (path
, NULL
));
1382 /* Because of long name mapping issues, we need to implement this
1383 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1384 a unique name, instead of setting the input template to an empty
1387 Standard algorithm seems to be use pid or tid with a letter on the
1388 front (in place of the 6 X's) and cycle through the letters to find a
1389 unique name. We extend that to allow any reasonable character as the
1390 first of the 6 X's. */
1392 sys_mktemp (char * template)
1396 unsigned uid
= GetCurrentThreadId ();
1397 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1399 if (template == NULL
)
1401 p
= template + strlen (template);
1403 /* replace up to the last 5 X's with uid in decimal */
1404 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
1406 p
[0] = '0' + uid
% 10;
1410 if (i
< 0 && p
[0] == 'X')
1415 int save_errno
= errno
;
1416 p
[0] = first_char
[i
];
1417 if (sys_access (template, 0) < 0)
1423 while (++i
< sizeof (first_char
));
1426 /* Template is badly formed or else we can't generate a unique name,
1427 so return empty string */
1433 sys_open (const char * path
, int oflag
, int mode
)
1435 /* Force all file handles to be non-inheritable. */
1436 return _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, mode
);
1440 sys_rename (const char * oldname
, const char * newname
)
1442 char temp
[MAX_PATH
];
1445 /* MoveFile on Windows 95 doesn't correctly change the short file name
1446 alias in a number of circumstances (it is not easy to predict when
1447 just by looking at oldname and newname, unfortunately). In these
1448 cases, renaming through a temporary name avoids the problem.
1450 A second problem on Windows 95 is that renaming through a temp name when
1451 newname is uppercase fails (the final long name ends up in
1452 lowercase, although the short alias might be uppercase) UNLESS the
1453 long temp name is not 8.3.
1455 So, on Windows 95 we always rename through a temp name, and we make sure
1456 the temp name has a long extension to ensure correct renaming. */
1458 strcpy (temp
, map_w32_filename (oldname
, NULL
));
1460 if (os_subtype
== OS_WIN95
)
1464 if (p
= strrchr (temp
, '\\'))
1468 /* Force temp name to require a manufactured 8.3 alias - this
1469 seems to make the second rename work properly. */
1470 strcpy (p
, "_rename_temp.XXXXXX");
1472 if (rename (map_w32_filename (oldname
, NULL
), temp
) < 0)
1476 /* Emulate Unix behaviour - newname is deleted if it already exists
1477 (at least if it is a file; don't do this for directories).
1478 However, don't do this if we are just changing the case of the file
1479 name - we will end up deleting the file we are trying to rename! */
1480 newname
= map_w32_filename (newname
, NULL
);
1482 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1483 do not refer to the same file, eg. through share aliases. */
1484 if (stricmp (newname
, temp
) != 0
1485 && (attr
= GetFileAttributes (newname
)) != -1
1486 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1488 _chmod (newname
, 0666);
1492 return rename (temp
, newname
);
1496 sys_rmdir (const char * path
)
1498 return _rmdir (map_w32_filename (path
, NULL
));
1502 sys_unlink (const char * path
)
1504 return _unlink (map_w32_filename (path
, NULL
));
1507 static FILETIME utc_base_ft
;
1508 static long double utc_base
;
1509 static int init
= 0;
1512 convert_time (FILETIME ft
)
1518 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1527 st
.wMilliseconds
= 0;
1529 SystemTimeToFileTime (&st
, &utc_base_ft
);
1530 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1531 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1535 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
1538 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
1540 return (time_t) (ret
* 1e-7);
1544 /* in case we ever have need of this */
1546 convert_from_time_t (time_t time
, FILETIME
* pft
)
1552 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1561 st
.wMilliseconds
= 0;
1563 SystemTimeToFileTime (&st
, &utc_base_ft
);
1564 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1565 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1569 /* time in 100ns units since 1-Jan-1601 */
1570 tmp
= (long double) time
* 1e7
+ utc_base
;
1571 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
1572 pft
->dwLowDateTime
= (DWORD
) (tmp
- pft
->dwHighDateTime
);
1577 /* No reason to keep this; faking inode values either by hashing or even
1578 using the file index from GetInformationByHandle, is not perfect and
1579 so by default Emacs doesn't use the inode values on Windows.
1580 Instead, we now determine file-truename correctly (except for
1581 possible drive aliasing etc). */
1583 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1585 hashval (const unsigned char * str
)
1590 h
= (h
<< 4) + *str
++;
1596 /* Return the hash value of the canonical pathname, excluding the
1597 drive/UNC header, to get a hopefully unique inode number. */
1599 generate_inode_val (const char * name
)
1601 char fullname
[ MAX_PATH
];
1605 /* Get the truly canonical filename, if it exists. (Note: this
1606 doesn't resolve aliasing due to subst commands, or recognise hard
1608 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
1611 parse_root (fullname
, &p
);
1612 /* Normal W32 filesystems are still case insensitive. */
1619 /* MSVC stat function can't cope with UNC names and has other bugs, so
1620 replace it with our own. This also allows us to calculate consistent
1621 inode values without hacks in the main Emacs code. */
1623 stat (const char * path
, struct stat
* buf
)
1626 WIN32_FIND_DATA wfd
;
1631 int rootdir
= FALSE
;
1633 if (path
== NULL
|| buf
== NULL
)
1639 name
= (char *) map_w32_filename (path
, &path
);
1640 /* must be valid filename, no wild cards */
1641 if (strchr (name
, '*') || strchr (name
, '?'))
1647 /* Remove trailing directory separator, unless name is the root
1648 directory of a drive or UNC volume in which case ensure there
1649 is a trailing separator. */
1650 len
= strlen (name
);
1651 rootdir
= (path
>= name
+ len
- 1
1652 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
1653 name
= strcpy (alloca (len
+ 2), name
);
1657 if (!IS_DIRECTORY_SEP (name
[len
-1]))
1658 strcat (name
, "\\");
1659 if (GetDriveType (name
) < 2)
1664 memset (&wfd
, 0, sizeof (wfd
));
1665 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
1666 wfd
.ftCreationTime
= utc_base_ft
;
1667 wfd
.ftLastAccessTime
= utc_base_ft
;
1668 wfd
.ftLastWriteTime
= utc_base_ft
;
1669 strcpy (wfd
.cFileName
, name
);
1673 if (IS_DIRECTORY_SEP (name
[len
-1]))
1676 /* (This is hacky, but helps when doing file completions on
1677 network drives.) Optimize by using information available from
1678 active readdir if possible. */
1679 if (dir_find_handle
!= INVALID_HANDLE_VALUE
1680 && (len
= strlen (dir_pathname
)),
1681 strnicmp (name
, dir_pathname
, len
) == 0
1682 && IS_DIRECTORY_SEP (name
[len
])
1683 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
1685 /* This was the last entry returned by readdir. */
1686 wfd
= dir_find_data
;
1690 fh
= FindFirstFile (name
, &wfd
);
1691 if (fh
== INVALID_HANDLE_VALUE
)
1700 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1702 buf
->st_mode
= _S_IFDIR
;
1703 buf
->st_nlink
= 2; /* doesn't really matter */
1704 fake_inode
= 0; /* this doesn't either I think */
1706 else if (!NILP (Vw32_get_true_file_attributes
))
1708 /* This is more accurate in terms of gettting the correct number
1709 of links, but is quite slow (it is noticable when Emacs is
1710 making a list of file name completions). */
1711 BY_HANDLE_FILE_INFORMATION info
;
1713 /* No access rights required to get info. */
1714 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
1716 if (GetFileInformationByHandle (fh
, &info
))
1718 switch (GetFileType (fh
))
1720 case FILE_TYPE_DISK
:
1721 buf
->st_mode
= _S_IFREG
;
1723 case FILE_TYPE_PIPE
:
1724 buf
->st_mode
= _S_IFIFO
;
1726 case FILE_TYPE_CHAR
:
1727 case FILE_TYPE_UNKNOWN
:
1729 buf
->st_mode
= _S_IFCHR
;
1731 buf
->st_nlink
= info
.nNumberOfLinks
;
1732 /* Might as well use file index to fake inode values, but this
1733 is not guaranteed to be unique unless we keep a handle open
1734 all the time (even then there are situations where it is
1735 not unique). Reputedly, there are at most 48 bits of info
1736 (on NTFS, presumably less on FAT). */
1737 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
1748 /* Don't bother to make this information more accurate. */
1749 buf
->st_mode
= _S_IFREG
;
1755 /* Not sure if there is any point in this. */
1756 if (!NILP (Vw32_generate_fake_inodes
))
1757 fake_inode
= generate_inode_val (name
);
1758 else if (fake_inode
== 0)
1760 /* For want of something better, try to make everything unique. */
1761 static DWORD gen_num
= 0;
1762 fake_inode
= ++gen_num
;
1766 /* MSVC defines _ino_t to be short; other libc's might not. */
1767 if (sizeof (buf
->st_ino
) == 2)
1768 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
1770 buf
->st_ino
= fake_inode
;
1772 /* consider files to belong to current user */
1773 buf
->st_uid
= the_passwd
.pw_uid
;
1774 buf
->st_gid
= the_passwd
.pw_gid
;
1776 /* volume_info is set indirectly by map_w32_filename */
1777 buf
->st_dev
= volume_info
.serialnum
;
1778 buf
->st_rdev
= volume_info
.serialnum
;
1781 buf
->st_size
= wfd
.nFileSizeLow
;
1783 /* Convert timestamps to Unix format. */
1784 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
1785 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
1786 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
1787 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
1788 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
1790 /* determine rwx permissions */
1791 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
1792 permission
= _S_IREAD
;
1794 permission
= _S_IREAD
| _S_IWRITE
;
1796 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1797 permission
|= _S_IEXEC
;
1800 char * p
= strrchr (name
, '.');
1802 && (stricmp (p
, ".exe") == 0 ||
1803 stricmp (p
, ".com") == 0 ||
1804 stricmp (p
, ".bat") == 0 ||
1805 stricmp (p
, ".cmd") == 0))
1806 permission
|= _S_IEXEC
;
1809 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
1816 /* Wrappers for winsock functions to map between our file descriptors
1817 and winsock's handles; also set h_errno for convenience.
1819 To allow Emacs to run on systems which don't have winsock support
1820 installed, we dynamically link to winsock on startup if present, and
1821 otherwise provide the minimum necessary functionality
1822 (eg. gethostname). */
1824 /* function pointers for relevant socket functions */
1825 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
1826 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
1827 int (PASCAL
*pfn_WSAGetLastError
) (void);
1828 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
1829 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1830 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1831 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
1832 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
1833 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
1834 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
1835 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
1836 int (PASCAL
*pfn_WSACleanup
) (void);
1838 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
1839 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
1840 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
1841 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
1842 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
1843 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
1845 /* SetHandleInformation is only needed to make sockets non-inheritable. */
1846 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
1847 #ifndef HANDLE_FLAG_INHERIT
1848 #define HANDLE_FLAG_INHERIT 1
1852 static int winsock_inuse
;
1857 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
1859 /* Not sure what would cause WSAENETDOWN, or even if it can happen
1860 after WSAStartup returns successfully, but it seems reasonable
1861 to allow unloading winsock anyway in that case. */
1862 if (pfn_WSACleanup () == 0 ||
1863 pfn_WSAGetLastError () == WSAENETDOWN
)
1865 if (FreeLibrary (winsock_lib
))
1874 init_winsock (int load_now
)
1876 WSADATA winsockData
;
1878 if (winsock_lib
!= NULL
)
1881 pfn_SetHandleInformation
= NULL
;
1882 pfn_SetHandleInformation
1883 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1884 "SetHandleInformation");
1886 winsock_lib
= LoadLibrary ("wsock32.dll");
1888 if (winsock_lib
!= NULL
)
1890 /* dynamically link to socket functions */
1892 #define LOAD_PROC(fn) \
1893 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
1896 LOAD_PROC( WSAStartup
);
1897 LOAD_PROC( WSASetLastError
);
1898 LOAD_PROC( WSAGetLastError
);
1899 LOAD_PROC( socket
);
1901 LOAD_PROC( connect
);
1902 LOAD_PROC( ioctlsocket
);
1905 LOAD_PROC( closesocket
);
1906 LOAD_PROC( shutdown
);
1909 LOAD_PROC( inet_addr
);
1910 LOAD_PROC( gethostname
);
1911 LOAD_PROC( gethostbyname
);
1912 LOAD_PROC( getservbyname
);
1913 LOAD_PROC( WSACleanup
);
1917 /* specify version 1.1 of winsock */
1918 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
1920 if (winsockData
.wVersion
!= 0x101)
1925 /* Report that winsock exists and is usable, but leave
1926 socket functions disabled. I am assuming that calling
1927 WSAStartup does not require any network interaction,
1928 and in particular does not cause or require a dial-up
1929 connection to be established. */
1932 FreeLibrary (winsock_lib
);
1940 FreeLibrary (winsock_lib
);
1950 /* function to set h_errno for compatability; map winsock error codes to
1951 normal system codes where they overlap (non-overlapping definitions
1952 are already in <sys/socket.h> */
1953 static void set_errno ()
1955 if (winsock_lib
== NULL
)
1958 h_errno
= pfn_WSAGetLastError ();
1962 case WSAEACCES
: h_errno
= EACCES
; break;
1963 case WSAEBADF
: h_errno
= EBADF
; break;
1964 case WSAEFAULT
: h_errno
= EFAULT
; break;
1965 case WSAEINTR
: h_errno
= EINTR
; break;
1966 case WSAEINVAL
: h_errno
= EINVAL
; break;
1967 case WSAEMFILE
: h_errno
= EMFILE
; break;
1968 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
1969 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
1974 static void check_errno ()
1976 if (h_errno
== 0 && winsock_lib
!= NULL
)
1977 pfn_WSASetLastError (0);
1980 /* [andrewi 3-May-96] I've had conflicting results using both methods,
1981 but I believe the method of keeping the socket handle separate (and
1982 insuring it is not inheritable) is the correct one. */
1984 //#define SOCK_REPLACE_HANDLE
1986 #ifdef SOCK_REPLACE_HANDLE
1987 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
1989 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
1993 sys_socket(int af
, int type
, int protocol
)
1999 if (winsock_lib
== NULL
)
2002 return INVALID_SOCKET
;
2007 /* call the real socket function */
2008 s
= (long) pfn_socket (af
, type
, protocol
);
2010 if (s
!= INVALID_SOCKET
)
2012 /* Although under NT 3.5 _open_osfhandle will accept a socket
2013 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2014 that does not work under NT 3.1. However, we can get the same
2015 effect by using a backdoor function to replace an existing
2016 descriptor handle with the one we want. */
2018 /* allocate a file descriptor (with appropriate flags) */
2019 fd
= _open ("NUL:", _O_RDWR
);
2022 #ifdef SOCK_REPLACE_HANDLE
2023 /* now replace handle to NUL with our socket handle */
2024 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
2026 _set_osfhnd (fd
, s
);
2027 /* setmode (fd, _O_BINARY); */
2029 /* Make a non-inheritable copy of the socket handle. */
2032 HANDLE new_s
= INVALID_HANDLE_VALUE
;
2034 parent
= GetCurrentProcess ();
2036 /* Apparently there is a bug in NT 3.51 with some service
2037 packs, which prevents using DuplicateHandle to make a
2038 socket handle non-inheritable (causes WSACleanup to
2039 hang). The work-around is to use SetHandleInformation
2040 instead if it is available and implemented. */
2041 if (!pfn_SetHandleInformation
2042 || !pfn_SetHandleInformation ((HANDLE
) s
,
2043 HANDLE_FLAG_INHERIT
,
2044 HANDLE_FLAG_INHERIT
))
2046 DuplicateHandle (parent
,
2052 DUPLICATE_SAME_ACCESS
);
2053 pfn_closesocket (s
);
2056 fd_info
[fd
].hnd
= (HANDLE
) s
;
2060 /* set our own internal flags */
2061 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
2067 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2069 /* attach child_process to fd_info */
2070 if (fd_info
[ fd
].cp
!= NULL
)
2072 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
2076 fd_info
[ fd
].cp
= cp
;
2079 winsock_inuse
++; /* count open sockets */
2086 pfn_closesocket (s
);
2096 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
2098 if (winsock_lib
== NULL
)
2101 return SOCKET_ERROR
;
2105 if (fd_info
[s
].flags
& FILE_SOCKET
)
2107 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
2108 if (rc
== SOCKET_ERROR
)
2113 return SOCKET_ERROR
;
2118 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
2120 if (winsock_lib
== NULL
)
2123 return SOCKET_ERROR
;
2127 if (fd_info
[s
].flags
& FILE_SOCKET
)
2129 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
2130 if (rc
== SOCKET_ERROR
)
2135 return SOCKET_ERROR
;
2139 sys_htons (u_short hostshort
)
2141 return (winsock_lib
!= NULL
) ?
2142 pfn_htons (hostshort
) : hostshort
;
2146 sys_ntohs (u_short netshort
)
2148 return (winsock_lib
!= NULL
) ?
2149 pfn_ntohs (netshort
) : netshort
;
2153 sys_inet_addr (const char * cp
)
2155 return (winsock_lib
!= NULL
) ?
2156 pfn_inet_addr (cp
) : INADDR_NONE
;
2160 sys_gethostname (char * name
, int namelen
)
2162 if (winsock_lib
!= NULL
)
2163 return pfn_gethostname (name
, namelen
);
2165 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
2166 return !GetComputerName (name
, &namelen
);
2169 return SOCKET_ERROR
;
2173 sys_gethostbyname(const char * name
)
2175 struct hostent
* host
;
2177 if (winsock_lib
== NULL
)
2184 host
= pfn_gethostbyname (name
);
2191 sys_getservbyname(const char * name
, const char * proto
)
2193 struct servent
* serv
;
2195 if (winsock_lib
== NULL
)
2202 serv
= pfn_getservbyname (name
, proto
);
2209 sys_shutdown (int s
, int how
)
2213 if (winsock_lib
== NULL
)
2216 return SOCKET_ERROR
;
2220 if (fd_info
[s
].flags
& FILE_SOCKET
)
2222 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
2223 if (rc
== SOCKET_ERROR
)
2228 return SOCKET_ERROR
;
2231 #endif /* HAVE_SOCKETS */
2234 /* Shadow main io functions: we need to handle pipes and sockets more
2235 intelligently, and implement non-blocking mode as well. */
2242 if (fd
< 0 || fd
>= MAXDESC
)
2250 child_process
* cp
= fd_info
[fd
].cp
;
2252 fd_info
[fd
].cp
= NULL
;
2254 if (CHILD_ACTIVE (cp
))
2256 /* if last descriptor to active child_process then cleanup */
2258 for (i
= 0; i
< MAXDESC
; i
++)
2262 if (fd_info
[i
].cp
== cp
)
2268 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2270 #ifndef SOCK_REPLACE_HANDLE
2271 if (winsock_lib
== NULL
) abort ();
2273 pfn_shutdown (SOCK_HANDLE (fd
), 2);
2274 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
2276 winsock_inuse
--; /* count open sockets */
2284 /* Note that sockets do not need special treatment here (at least on
2285 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2286 closesocket is equivalent to CloseHandle, which is to be expected
2287 because socket handles are fully fledged kernel handles. */
2291 fd_info
[fd
].flags
= 0;
2304 /* duplicate our internal info as well */
2305 fd_info
[new_fd
] = fd_info
[fd
];
2312 sys_dup2 (int src
, int dst
)
2316 if (dst
< 0 || dst
>= MAXDESC
)
2322 /* make sure we close the destination first if it's a pipe or socket */
2323 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
2326 rc
= _dup2 (src
, dst
);
2329 /* duplicate our internal info as well */
2330 fd_info
[dst
] = fd_info
[src
];
2335 /* Unix pipe() has only one arg */
2337 sys_pipe (int * phandles
)
2343 /* make pipe handles non-inheritable; when we spawn a child, we
2344 replace the relevant handle with an inheritable one. Also put
2345 pipes into binary mode; we will do text mode translation ourselves
2347 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
2351 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
2352 fd_info
[phandles
[0]].flags
= flags
;
2354 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
2355 fd_info
[phandles
[1]].flags
= flags
;
2362 extern Lisp_Object Vw32_pipe_read_delay
;
2364 /* Function to do blocking read of one byte, needed to implement
2365 select. It is only allowed on sockets and pipes. */
2367 _sys_read_ahead (int fd
)
2372 if (fd
< 0 || fd
>= MAXDESC
)
2373 return STATUS_READ_ERROR
;
2375 cp
= fd_info
[fd
].cp
;
2377 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
2378 return STATUS_READ_ERROR
;
2380 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
2381 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
2383 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
2387 cp
->status
= STATUS_READ_IN_PROGRESS
;
2389 if (fd_info
[fd
].flags
& FILE_PIPE
)
2391 rc
= _read (fd
, &cp
->chr
, sizeof (char));
2393 /* Give subprocess time to buffer some more output for us before
2394 reporting that input is available; we need this because Windows 95
2395 connects DOS programs to pipes by making the pipe appear to be
2396 the normal console stdout - as a result most DOS programs will
2397 write to stdout without buffering, ie. one character at a
2398 time. Even some W32 programs do this - "dir" in a command
2399 shell on NT is very slow if we don't do this. */
2402 int wait
= XINT (Vw32_pipe_read_delay
);
2408 /* Yield remainder of our time slice, effectively giving a
2409 temporary priority boost to the child process. */
2414 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
2415 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
2418 if (rc
== sizeof (char))
2419 cp
->status
= STATUS_READ_SUCCEEDED
;
2421 cp
->status
= STATUS_READ_FAILED
;
2427 sys_read (int fd
, char * buffer
, unsigned int count
)
2432 char * orig_buffer
= buffer
;
2434 if (fd
< 0 || fd
>= MAXDESC
)
2440 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2442 child_process
*cp
= fd_info
[fd
].cp
;
2444 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
2452 /* re-read CR carried over from last read */
2453 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
2455 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
2459 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
2462 /* presence of a child_process structure means we are operating in
2463 non-blocking mode - otherwise we just call _read directly.
2464 Note that the child_process structure might be missing because
2465 reap_subprocess has been called; in this case the pipe is
2466 already broken, so calling _read on it is okay. */
2469 int current_status
= cp
->status
;
2471 switch (current_status
)
2473 case STATUS_READ_FAILED
:
2474 case STATUS_READ_ERROR
:
2475 /* report normal EOF if nothing in buffer */
2477 fd_info
[fd
].flags
|= FILE_AT_EOF
;
2480 case STATUS_READ_READY
:
2481 case STATUS_READ_IN_PROGRESS
:
2482 DebPrint (("sys_read called when read is in progress\n"));
2483 errno
= EWOULDBLOCK
;
2486 case STATUS_READ_SUCCEEDED
:
2487 /* consume read-ahead char */
2488 *buffer
++ = cp
->chr
;
2491 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2492 ResetEvent (cp
->char_avail
);
2494 case STATUS_READ_ACKNOWLEDGED
:
2498 DebPrint (("sys_read: bad status %d\n", current_status
));
2503 if (fd_info
[fd
].flags
& FILE_PIPE
)
2505 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
2506 to_read
= min (waiting
, (DWORD
) count
);
2509 nchars
+= _read (fd
, buffer
, to_read
);
2512 else /* FILE_SOCKET */
2514 if (winsock_lib
== NULL
) abort ();
2516 /* do the equivalent of a non-blocking read */
2517 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
2518 if (waiting
== 0 && nchars
== 0)
2520 h_errno
= errno
= EWOULDBLOCK
;
2526 /* always use binary mode for sockets */
2527 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
2528 if (res
== SOCKET_ERROR
)
2530 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
2531 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2542 int nread
= _read (fd
, buffer
, count
);
2545 else if (nchars
== 0)
2550 fd_info
[fd
].flags
|= FILE_AT_EOF
;
2551 /* Perform text mode translation if required. */
2552 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2554 nchars
= crlf_to_lf (nchars
, orig_buffer
);
2555 /* If buffer contains only CR, return that. To be absolutely
2556 sure we should attempt to read the next char, but in
2557 practice a CR to be followed by LF would not appear by
2558 itself in the buffer. */
2559 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
2561 fd_info
[fd
].flags
|= FILE_LAST_CR
;
2567 nchars
= _read (fd
, buffer
, count
);
2572 /* For now, don't bother with a non-blocking mode */
2574 sys_write (int fd
, const void * buffer
, unsigned int count
)
2578 if (fd
< 0 || fd
>= MAXDESC
)
2584 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2586 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
2592 /* Perform text mode translation if required. */
2593 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2595 char * tmpbuf
= alloca (count
* 2);
2596 unsigned char * src
= (void *)buffer
;
2597 unsigned char * dst
= tmpbuf
;
2602 unsigned char *next
;
2603 /* copy next line or remaining bytes */
2604 next
= _memccpy (dst
, src
, '\n', nbytes
);
2607 /* copied one line ending with '\n' */
2608 int copied
= next
- dst
;
2611 /* insert '\r' before '\n' */
2618 /* copied remaining partial line -> now finished */
2626 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2628 if (winsock_lib
== NULL
) abort ();
2629 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
2630 if (nchars
== SOCKET_ERROR
)
2632 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
2633 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2639 nchars
= _write (fd
, buffer
, count
);
2645 check_windows_init_file ()
2647 extern int noninteractive
, inhibit_window_system
;
2649 /* A common indication that Emacs is not installed properly is when
2650 it cannot find the Windows installation file. If this file does
2651 not exist in the expected place, tell the user. */
2653 if (!noninteractive
&& !inhibit_window_system
) {
2654 extern Lisp_Object Vwindow_system
, Vload_path
;
2655 Lisp_Object init_file
;
2658 init_file
= build_string ("term/w32-win");
2659 fd
= openp (Vload_path
, init_file
, ".el:.elc", NULL
, 0);
2661 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
2662 char *init_file_name
= XSTRING (init_file
)->data
;
2663 char *load_path
= XSTRING (load_path_print
)->data
;
2664 char *buffer
= alloca (1024);
2667 "The Emacs Windows initialization file \"%s.el\" "
2668 "could not be found in your Emacs installation. "
2669 "Emacs checked the following directories for this file:\n"
2671 "When Emacs cannot find this file, it usually means that it "
2672 "was not installed properly, or its distribution file was "
2673 "not unpacked properly.\nSee the README.W32 file in the "
2674 "top-level Emacs directory for more information.",
2675 init_file_name
, load_path
);
2678 "Emacs Abort Dialog",
2679 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
2682 /* Use the low-level Emacs abort. */
2693 /* shutdown the socket interface if necessary */
2697 /* Check whether we are shutting down because we cannot find the
2698 Windows initialization file. Do this during shutdown so that
2699 Emacs is initialized as possible, and so that it is out of the
2700 critical startup path. */
2701 check_windows_init_file ();
2708 /* Initialise the socket interface now if available and requested by
2709 the user by defining PRELOAD_WINSOCK; otherwise loading will be
2710 delayed until open-network-stream is called (w32-has-winsock can
2711 also be used to dynamically load or reload winsock).
2713 Conveniently, init_environment is called before us, so
2714 PRELOAD_WINSOCK can be set in the registry. */
2716 /* Always initialize this correctly. */
2719 if (getenv ("PRELOAD_WINSOCK") != NULL
)
2720 init_winsock (TRUE
);
2723 /* Initial preparation for subprocess support: replace our standard
2724 handles with non-inheritable versions. */
2727 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
2728 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
2729 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
2731 parent
= GetCurrentProcess ();
2733 /* ignore errors when duplicating and closing; typically the
2734 handles will be invalid when running as a gui program. */
2735 DuplicateHandle (parent
,
2736 GetStdHandle (STD_INPUT_HANDLE
),
2741 DUPLICATE_SAME_ACCESS
);
2743 DuplicateHandle (parent
,
2744 GetStdHandle (STD_OUTPUT_HANDLE
),
2749 DUPLICATE_SAME_ACCESS
);
2751 DuplicateHandle (parent
,
2752 GetStdHandle (STD_ERROR_HANDLE
),
2757 DUPLICATE_SAME_ACCESS
);
2763 if (stdin_save
!= INVALID_HANDLE_VALUE
)
2764 _open_osfhandle ((long) stdin_save
, O_TEXT
);
2766 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
2769 if (stdout_save
!= INVALID_HANDLE_VALUE
)
2770 _open_osfhandle ((long) stdout_save
, O_TEXT
);
2772 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2775 if (stderr_save
!= INVALID_HANDLE_VALUE
)
2776 _open_osfhandle ((long) stderr_save
, O_TEXT
);
2778 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2782 /* unfortunately, atexit depends on implementation of malloc */
2783 /* atexit (term_ntproc); */
2784 signal (SIGABRT
, term_ntproc
);
2786 /* determine which drives are fixed, for GetCachedVolumeInformation */
2788 /* GetDriveType must have trailing backslash. */
2789 char drive
[] = "A:\\";
2791 /* Loop over all possible drive letters */
2792 while (*drive
<= 'Z')
2794 /* Record if this drive letter refers to a fixed drive. */
2795 fixed_drives
[DRIVE_INDEX (*drive
)] =
2796 (GetDriveType (drive
) == DRIVE_FIXED
);