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>
82 extern Lisp_Object Vw32_downcase_file_names
;
83 extern Lisp_Object Vw32_generate_fake_inodes
;
84 extern Lisp_Object Vw32_get_true_file_attributes
;
86 static char startup_dir
[MAXPATHLEN
];
88 /* Get the current working directory. */
93 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
97 /* Emacs doesn't actually change directory itself, and we want to
98 force our real wd to be where emacs.exe is to avoid unnecessary
99 conflicts when trying to rename or delete directories. */
100 strcpy (dir
, startup_dir
);
106 /* Emulate gethostname. */
108 gethostname (char *buffer
, int size
)
110 /* NT only allows small host names, so the buffer is
111 certainly large enough. */
112 return !GetComputerName (buffer
, &size
);
114 #endif /* HAVE_SOCKETS */
116 /* Emulate getloadavg. */
118 getloadavg (double loadavg
[], int nelem
)
122 /* A faithful emulation is going to have to be saved for a rainy day. */
123 for (i
= 0; i
< nelem
; i
++)
130 /* Emulate getpwuid, getpwnam and others. */
132 #define PASSWD_FIELD_SIZE 256
134 static char the_passwd_name
[PASSWD_FIELD_SIZE
];
135 static char the_passwd_passwd
[PASSWD_FIELD_SIZE
];
136 static char the_passwd_gecos
[PASSWD_FIELD_SIZE
];
137 static char the_passwd_dir
[PASSWD_FIELD_SIZE
];
138 static char the_passwd_shell
[PASSWD_FIELD_SIZE
];
140 static struct passwd the_passwd
=
155 return the_passwd
.pw_uid
;
161 /* I could imagine arguing for checking to see whether the user is
162 in the Administrators group and returning a UID of 0 for that
163 case, but I don't know how wise that would be in the long run. */
170 return the_passwd
.pw_gid
;
182 if (uid
== the_passwd
.pw_uid
)
188 getpwnam (char *name
)
192 pw
= getpwuid (getuid ());
196 if (stricmp (name
, pw
->pw_name
))
205 /* Find the user's real name by opening the process token and
206 looking up the name associated with the user-sid in that token.
208 Use the relative portion of the identifier authority value from
209 the user-sid as the user id value (same for group id using the
210 primary group sid from the process token). */
212 char user_sid
[256], name
[256], domain
[256];
213 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
215 SID_NAME_USE user_type
;
217 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY
, &token
)
218 && GetTokenInformation (token
, TokenUser
,
219 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
220 && LookupAccountSid (NULL
, *((PSID
*) user_sid
), name
, &length
,
221 domain
, &dlength
, &user_type
))
223 strcpy (the_passwd
.pw_name
, name
);
224 /* Determine a reasonable uid value. */
225 if (stricmp ("administrator", name
) == 0)
227 the_passwd
.pw_uid
= 0;
228 the_passwd
.pw_gid
= 0;
232 SID_IDENTIFIER_AUTHORITY
* pSIA
;
234 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
235 /* I believe the relative portion is the last 4 bytes (of 6)
237 the_passwd
.pw_uid
= ((pSIA
->Value
[2] << 24) +
238 (pSIA
->Value
[3] << 16) +
239 (pSIA
->Value
[4] << 8) +
240 (pSIA
->Value
[5] << 0));
241 /* restrict to conventional uid range for normal users */
242 the_passwd
.pw_uid
= the_passwd
.pw_uid
% 60001;
245 if (GetTokenInformation (token
, TokenPrimaryGroup
,
246 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
248 SID_IDENTIFIER_AUTHORITY
* pSIA
;
250 pSIA
= GetSidIdentifierAuthority (*((PSID
*) user_sid
));
251 the_passwd
.pw_gid
= ((pSIA
->Value
[2] << 24) +
252 (pSIA
->Value
[3] << 16) +
253 (pSIA
->Value
[4] << 8) +
254 (pSIA
->Value
[5] << 0));
255 /* I don't know if this is necessary, but for safety... */
256 the_passwd
.pw_gid
= the_passwd
.pw_gid
% 60001;
259 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
262 /* If security calls are not supported (presumably because we
263 are running under Windows 95), fallback to this. */
264 else if (GetUserName (name
, &length
))
266 strcpy (the_passwd
.pw_name
, name
);
267 if (stricmp ("administrator", name
) == 0)
268 the_passwd
.pw_uid
= 0;
270 the_passwd
.pw_uid
= 123;
271 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
275 strcpy (the_passwd
.pw_name
, "unknown");
276 the_passwd
.pw_uid
= 123;
277 the_passwd
.pw_gid
= 123;
280 /* Ensure HOME and SHELL are defined. */
281 if (getenv ("HOME") == NULL
)
283 if (getenv ("SHELL") == NULL
)
284 putenv (os_subtype
== OS_WIN95
? "SHELL=command" : "SHELL=cmd");
286 /* Set dir and shell from environment variables. */
287 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
288 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
297 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
298 return ((rand () << 15) | rand ());
308 /* Normalize filename by converting all path separators to
309 the specified separator. Also conditionally convert upper
310 case path name components to lower case. */
313 normalize_filename (fp
, path_sep
)
320 /* Always lower-case drive letters a-z, even if the filesystem
321 preserves case in filenames.
322 This is so filenames can be compared by string comparison
323 functions that are case-sensitive. Even case-preserving filesystems
324 do not distinguish case in drive letters. */
325 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
331 if (NILP (Vw32_downcase_file_names
))
335 if (*fp
== '/' || *fp
== '\\')
342 sep
= path_sep
; /* convert to this path separator */
343 elem
= fp
; /* start of current path element */
346 if (*fp
>= 'a' && *fp
<= 'z')
347 elem
= 0; /* don't convert this element */
349 if (*fp
== 0 || *fp
== ':')
351 sep
= *fp
; /* restore current separator (or 0) */
352 *fp
= '/'; /* after conversion of this element */
355 if (*fp
== '/' || *fp
== '\\')
357 if (elem
&& elem
!= fp
)
359 *fp
= 0; /* temporary end of string */
360 _strlwr (elem
); /* while we convert to lower case */
362 *fp
= sep
; /* convert (or restore) path separator */
363 elem
= fp
+ 1; /* next element starts after separator */
369 /* Destructively turn backslashes into slashes. */
371 dostounix_filename (p
)
374 normalize_filename (p
, '/');
377 /* Destructively turn slashes into backslashes. */
379 unixtodos_filename (p
)
382 normalize_filename (p
, '\\');
385 /* Remove all CR's that are followed by a LF.
386 (From msdos.c...probably should figure out a way to share it,
387 although this code isn't going to ever change.) */
391 register unsigned char *buf
;
393 unsigned char *np
= buf
;
394 unsigned char *startp
= buf
;
395 unsigned char *endp
= buf
+ n
;
399 while (buf
< endp
- 1)
403 if (*(++buf
) != 0x0a)
414 /* Parse the root part of file name, if present. Return length and
415 optionally store pointer to char after root. */
417 parse_root (char * name
, char ** pPath
)
424 /* find the root name of the volume if given */
425 if (isalpha (name
[0]) && name
[1] == ':')
427 /* skip past drive specifier */
429 if (IS_DIRECTORY_SEP (name
[0]))
432 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
438 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
443 if (IS_DIRECTORY_SEP (name
[0]))
453 /* Get long base name for name; name is assumed to be absolute. */
455 get_long_basename (char * name
, char * buf
, int size
)
457 WIN32_FIND_DATA find_data
;
461 dir_handle
= FindFirstFile (name
, &find_data
);
462 if (dir_handle
!= INVALID_HANDLE_VALUE
)
464 if ((len
= strlen (find_data
.cFileName
)) < size
)
465 memcpy (buf
, find_data
.cFileName
, len
+ 1);
468 FindClose (dir_handle
);
473 /* Get long name for file, if possible (assumed to be absolute). */
475 w32_get_long_filename (char * name
, char * buf
, int size
)
480 char full
[ MAX_PATH
];
487 /* Use local copy for destructive modification. */
488 memcpy (full
, name
, len
+1);
489 unixtodos_filename (full
);
491 /* Copy root part verbatim. */
492 len
= parse_root (full
, &p
);
493 memcpy (o
, full
, len
);
500 p
= strchr (q
, '\\');
502 len
= get_long_basename (full
, o
, size
);
520 while (p
!= NULL
&& *p
);
526 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
529 sigsetmask (int signal_mask
)
541 setpgrp (int pid
, int gid
)
553 unrequest_sigio (void)
564 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
567 w32_get_resource (key
, lpdwtype
)
572 HKEY hrootkey
= NULL
;
576 /* Check both the current user and the local machine to see if
577 we have any resources. */
579 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
583 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
584 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
585 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
590 if (lpvalue
) xfree (lpvalue
);
592 RegCloseKey (hrootkey
);
595 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
599 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
600 && (lpvalue
= (LPBYTE
) xmalloc (cbData
)) != NULL
601 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
606 if (lpvalue
) xfree (lpvalue
);
608 RegCloseKey (hrootkey
);
614 char *get_emacs_configuration (void);
615 extern Lisp_Object Vsystem_configuration
;
620 /* Check for environment variables and use registry if they don't exist */
626 static char * env_vars
[] =
637 /* We no longer set INFOPATH because Info-default-directory-list
638 is then ignored. We use a hook in winnt.el instead. */
644 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
646 if (!getenv (env_vars
[i
])
647 && (lpval
= w32_get_resource (env_vars
[i
], &dwType
)) != NULL
)
649 if (dwType
== REG_EXPAND_SZ
)
651 char buf1
[500], buf2
[500];
653 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, 500);
654 _snprintf (buf2
, 499, "%s=%s", env_vars
[i
], buf1
);
655 putenv (strdup (buf2
));
657 else if (dwType
== REG_SZ
)
661 _snprintf (buf
, 499, "%s=%s", env_vars
[i
], lpval
);
662 putenv (strdup (buf
));
670 /* Rebuild system configuration to reflect invoking system. */
671 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
673 /* Another special case: on NT, the PATH variable is actually named
674 "Path" although cmd.exe (perhaps NT itself) arranges for
675 environment variable lookup and setting to be case insensitive.
676 However, Emacs assumes a fully case sensitive environment, so we
677 need to change "Path" to "PATH" to match the expectations of
678 various elisp packages. We do this by the sneaky method of
679 modifying the string in the C runtime environ entry.
681 The same applies to COMSPEC. */
685 for (envp
= environ
; *envp
; envp
++)
686 if (_strnicmp (*envp
, "PATH=", 5) == 0)
687 memcpy (*envp
, "PATH=", 5);
688 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
689 memcpy (*envp
, "COMSPEC=", 8);
692 /* Remember the initial working directory for getwd, then make the
693 real wd be the location of emacs.exe to avoid conflicts when
694 renaming or deleting directories. (We also don't call chdir when
695 running subprocesses for the same reason.) */
696 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
701 char modname
[MAX_PATH
];
703 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
705 if ((p
= strrchr (modname
, '\\')) == NULL
)
709 SetCurrentDirectory (modname
);
715 /* We don't have scripts to automatically determine the system configuration
716 for Emacs before it's compiled, and we don't want to have to make the
717 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
720 static char configuration_buffer
[32];
723 get_emacs_configuration (void)
725 char *arch
, *oem
, *os
;
727 /* Determine the processor type. */
728 switch (get_processor_type ())
731 #ifdef PROCESSOR_INTEL_386
732 case PROCESSOR_INTEL_386
:
733 case PROCESSOR_INTEL_486
:
734 case PROCESSOR_INTEL_PENTIUM
:
739 #ifdef PROCESSOR_INTEL_860
740 case PROCESSOR_INTEL_860
:
745 #ifdef PROCESSOR_MIPS_R2000
746 case PROCESSOR_MIPS_R2000
:
747 case PROCESSOR_MIPS_R3000
:
748 case PROCESSOR_MIPS_R4000
:
753 #ifdef PROCESSOR_ALPHA_21064
754 case PROCESSOR_ALPHA_21064
:
764 /* Let oem be "*" until we figure out how to decode the OEM field. */
767 os
= (GetVersion () & OS_WIN95
) ? "windows95" : "nt";
769 sprintf (configuration_buffer
, "%s-%s-%s%d.%d", arch
, oem
, os
,
770 get_w32_major_version (), get_w32_minor_version ());
771 return configuration_buffer
;
774 #include <sys/timeb.h>
776 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
778 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
783 tv
->tv_sec
= tb
.time
;
784 tv
->tv_usec
= tb
.millitm
* 1000L;
787 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
788 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
792 /* ------------------------------------------------------------------------- */
793 /* IO support and wrapper functions for W32 API. */
794 /* ------------------------------------------------------------------------- */
796 /* Place a wrapper around the MSVC version of ctime. It returns NULL
797 on network directories, so we handle that case here.
798 (Ulrich Leodolter, 1/11/95). */
800 sys_ctime (const time_t *t
)
802 char *str
= (char *) ctime (t
);
803 return (str
? str
: "Sun Jan 01 00:00:00 1970");
806 /* Emulate sleep...we could have done this with a define, but that
807 would necessitate including windows.h in the files that used it.
808 This is much easier. */
810 sys_sleep (int seconds
)
812 Sleep (seconds
* 1000);
815 /* Internal MSVC functions for low-level descriptor munging */
816 extern int __cdecl
_set_osfhnd (int fd
, long h
);
817 extern int __cdecl
_free_osfhnd (int fd
);
819 /* parallel array of private info on file handles */
820 filedesc fd_info
[ MAXDESC
];
822 typedef struct volume_info_data
{
823 struct volume_info_data
* next
;
825 /* time when info was obtained */
828 /* actual volume info */
837 /* Global referenced by various functions. */
838 static volume_info_data volume_info
;
840 /* Vector to indicate which drives are local and fixed (for which cached
841 data never expires). */
842 static BOOL fixed_drives
[26];
844 /* Consider cached volume information to be stale if older than 10s,
845 at least for non-local drives. Info for fixed drives is never stale. */
846 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
847 #define VOLINFO_STILL_VALID( root_dir, info ) \
848 ( ( isalpha (root_dir[0]) && \
849 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
850 || GetTickCount () - info->timestamp < 10000 )
852 /* Cache support functions. */
854 /* Simple linked list with linear search is sufficient. */
855 static volume_info_data
*volume_cache
= NULL
;
857 static volume_info_data
*
858 lookup_volume_info (char * root_dir
)
860 volume_info_data
* info
;
862 for (info
= volume_cache
; info
; info
= info
->next
)
863 if (stricmp (info
->root_dir
, root_dir
) == 0)
869 add_volume_info (char * root_dir
, volume_info_data
* info
)
871 info
->root_dir
= strdup (root_dir
);
872 info
->next
= volume_cache
;
877 /* Wrapper for GetVolumeInformation, which uses caching to avoid
878 performance penalty (~2ms on 486 for local drives, 7.5ms for local
879 cdrom drive, ~5-10ms or more for remote drives on LAN). */
881 GetCachedVolumeInformation (char * root_dir
)
883 volume_info_data
* info
;
884 char default_root
[ MAX_PATH
];
886 /* NULL for root_dir means use root from current directory. */
887 if (root_dir
== NULL
)
889 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
891 parse_root (default_root
, &root_dir
);
893 root_dir
= default_root
;
896 /* Local fixed drives can be cached permanently. Removable drives
897 cannot be cached permanently, since the volume name and serial
898 number (if nothing else) can change. Remote drives should be
899 treated as if they are removable, since there is no sure way to
900 tell whether they are or not. Also, the UNC association of drive
901 letters mapped to remote volumes can be changed at any time (even
902 by other processes) without notice.
904 As a compromise, so we can benefit from caching info for remote
905 volumes, we use a simple expiry mechanism to invalidate cache
906 entries that are more than ten seconds old. */
909 /* No point doing this, because WNetGetConnection is even slower than
910 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
911 GetDriveType is about the only call of this type which does not
912 involve network access, and so is extremely quick). */
914 /* Map drive letter to UNC if remote. */
915 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
917 char remote_name
[ 256 ];
918 char drive
[3] = { root_dir
[0], ':' };
920 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
926 info
= lookup_volume_info (root_dir
);
928 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
936 /* Info is not cached, or is stale. */
937 if (!GetVolumeInformation (root_dir
,
942 type
, sizeof (type
)))
945 /* Cache the volume information for future use, overwriting existing
949 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
950 add_volume_info (root_dir
, info
);
958 info
->name
= strdup (name
);
959 info
->serialnum
= serialnum
;
960 info
->maxcomp
= maxcomp
;
962 info
->type
= strdup (type
);
963 info
->timestamp
= GetTickCount ();
969 /* Get information on the volume where name is held; set path pointer to
970 start of pathname in name (past UNC header\volume header if present). */
972 get_volume_info (const char * name
, const char ** pPath
)
975 char *rootname
= NULL
; /* default to current volume */
976 volume_info_data
* info
;
981 /* find the root name of the volume if given */
982 if (isalpha (name
[0]) && name
[1] == ':')
990 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
997 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1010 info
= GetCachedVolumeInformation (rootname
);
1013 /* Set global referenced by other functions. */
1014 volume_info
= *info
;
1020 /* Determine if volume is FAT format (ie. only supports short 8.3
1021 names); also set path pointer to start of pathname in name. */
1023 is_fat_volume (const char * name
, const char ** pPath
)
1025 if (get_volume_info (name
, pPath
))
1026 return (volume_info
.maxcomp
== 12);
1030 /* Map filename to a legal 8.3 name if necessary. */
1032 map_w32_filename (const char * name
, const char ** pPath
)
1034 static char shortname
[MAX_PATH
];
1035 char * str
= shortname
;
1038 const char * save_name
= name
;
1040 if (is_fat_volume (name
, &path
)) /* truncate to 8.3 */
1042 register int left
= 8; /* maximum number of chars in part */
1043 register int extn
= 0; /* extension added? */
1044 register int dots
= 2; /* maximum number of dots allowed */
1047 *str
++ = *name
++; /* skip past UNC header */
1049 while ((c
= *name
++))
1056 extn
= 0; /* reset extension flags */
1057 dots
= 2; /* max 2 dots */
1058 left
= 8; /* max length 8 for main part */
1062 extn
= 0; /* reset extension flags */
1063 dots
= 2; /* max 2 dots */
1064 left
= 8; /* max length 8 for main part */
1069 /* Convert path components of the form .xxx to _xxx,
1070 but leave . and .. as they are. This allows .emacs
1071 to be read as _emacs, for example. */
1075 IS_DIRECTORY_SEP (*name
))
1090 extn
= 1; /* we've got an extension */
1091 left
= 3; /* 3 chars in extension */
1095 /* any embedded dots after the first are converted to _ */
1100 case '#': /* don't lose these, they're important */
1102 str
[-1] = c
; /* replace last character of part */
1107 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1109 dots
= 0; /* started a path component */
1118 strcpy (shortname
, name
);
1119 unixtodos_filename (shortname
);
1123 *pPath
= shortname
+ (path
- save_name
);
1128 /* Emulate the Unix directory procedures opendir, closedir,
1129 and readdir. We can't use the procedures supplied in sysdep.c,
1130 so we provide them here. */
1132 struct direct dir_static
; /* simulated directory contents */
1133 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
1134 static int dir_is_fat
;
1135 static char dir_pathname
[MAXPATHLEN
+1];
1136 static WIN32_FIND_DATA dir_find_data
;
1139 opendir (char *filename
)
1143 /* Opening is done by FindFirstFile. However, a read is inherent to
1144 this operation, so we defer the open until read time. */
1146 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1148 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1155 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1156 dir_pathname
[MAXPATHLEN
] = '\0';
1157 dir_is_fat
= is_fat_volume (filename
, NULL
);
1163 closedir (DIR *dirp
)
1165 /* If we have a find-handle open, close it. */
1166 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1168 FindClose (dir_find_handle
);
1169 dir_find_handle
= INVALID_HANDLE_VALUE
;
1171 xfree ((char *) dirp
);
1177 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1178 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1180 char filename
[MAXNAMLEN
+ 3];
1183 strcpy (filename
, dir_pathname
);
1184 ln
= strlen (filename
) - 1;
1185 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1186 strcat (filename
, "\\");
1187 strcat (filename
, "*");
1189 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1191 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1196 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1200 /* Emacs never uses this value, so don't bother making it match
1201 value returned by stat(). */
1202 dir_static
.d_ino
= 1;
1204 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1205 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1207 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1208 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1210 _strlwr (dir_static
.d_name
);
1211 else if (!NILP (Vw32_downcase_file_names
))
1214 for (p
= dir_static
.d_name
; *p
; p
++)
1215 if (*p
>= 'a' && *p
<= 'z')
1218 _strlwr (dir_static
.d_name
);
1225 /* Shadow some MSVC runtime functions to map requests for long filenames
1226 to reasonable short names if necessary. This was originally added to
1227 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1231 sys_access (const char * path
, int mode
)
1233 return _access (map_w32_filename (path
, NULL
), mode
);
1237 sys_chdir (const char * path
)
1239 return _chdir (map_w32_filename (path
, NULL
));
1243 sys_chmod (const char * path
, int mode
)
1245 return _chmod (map_w32_filename (path
, NULL
), mode
);
1249 sys_creat (const char * path
, int mode
)
1251 return _creat (map_w32_filename (path
, NULL
), mode
);
1255 sys_fopen(const char * path
, const char * mode
)
1259 const char * mode_save
= mode
;
1261 /* Force all file handles to be non-inheritable. This is necessary to
1262 ensure child processes don't unwittingly inherit handles that might
1263 prevent future file access. */
1267 else if (mode
[0] == 'w' || mode
[0] == 'a')
1268 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1272 /* Only do simplistic option parsing. */
1276 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1279 else if (mode
[0] == 'b')
1284 else if (mode
[0] == 't')
1291 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1295 return _fdopen (fd
, mode_save
);
1298 /* This only works on NTFS volumes, but is useful to have. */
1300 sys_link (const char * old
, const char * new)
1304 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
1306 if (old
== NULL
|| new == NULL
)
1312 strcpy (oldname
, map_w32_filename (old
, NULL
));
1313 strcpy (newname
, map_w32_filename (new, NULL
));
1315 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
1316 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
1317 if (fileh
!= INVALID_HANDLE_VALUE
)
1321 /* Confusingly, the "alternate" stream name field does not apply
1322 when restoring a hard link, and instead contains the actual
1323 stream data for the link (ie. the name of the link to create).
1324 The WIN32_STREAM_ID structure before the cStreamName field is
1325 the stream header, which is then immediately followed by the
1329 WIN32_STREAM_ID wid
;
1330 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
1333 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
1334 data
.wid
.cStreamName
, MAX_PATH
);
1337 LPVOID context
= NULL
;
1340 data
.wid
.dwStreamId
= BACKUP_LINK
;
1341 data
.wid
.dwStreamAttributes
= 0;
1342 data
.wid
.Size
.LowPart
= wlen
* sizeof(WCHAR
);
1343 data
.wid
.Size
.HighPart
= 0;
1344 data
.wid
.dwStreamNameSize
= 0;
1346 if (BackupWrite (fileh
, (LPBYTE
)&data
,
1347 offsetof (WIN32_STREAM_ID
, cStreamName
)
1348 + data
.wid
.Size
.LowPart
,
1349 &wbytes
, FALSE
, FALSE
, &context
)
1350 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
1357 /* Should try mapping GetLastError to errno; for now just
1358 indicate a general error (eg. links not supported). */
1359 errno
= EINVAL
; // perhaps EMLINK?
1363 CloseHandle (fileh
);
1372 sys_mkdir (const char * path
)
1374 return _mkdir (map_w32_filename (path
, NULL
));
1377 /* Because of long name mapping issues, we need to implement this
1378 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1379 a unique name, instead of setting the input template to an empty
1382 Standard algorithm seems to be use pid or tid with a letter on the
1383 front (in place of the 6 X's) and cycle through the letters to find a
1384 unique name. We extend that to allow any reasonable character as the
1385 first of the 6 X's. */
1387 sys_mktemp (char * template)
1391 unsigned uid
= GetCurrentThreadId ();
1392 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1394 if (template == NULL
)
1396 p
= template + strlen (template);
1398 /* replace up to the last 5 X's with uid in decimal */
1399 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
1401 p
[0] = '0' + uid
% 10;
1405 if (i
< 0 && p
[0] == 'X')
1410 int save_errno
= errno
;
1411 p
[0] = first_char
[i
];
1412 if (sys_access (template, 0) < 0)
1418 while (++i
< sizeof (first_char
));
1421 /* Template is badly formed or else we can't generate a unique name,
1422 so return empty string */
1428 sys_open (const char * path
, int oflag
, int mode
)
1430 /* Force all file handles to be non-inheritable. */
1431 return _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, mode
);
1435 sys_rename (const char * oldname
, const char * newname
)
1437 char temp
[MAX_PATH
];
1440 /* MoveFile on Windows 95 doesn't correctly change the short file name
1441 alias in a number of circumstances (it is not easy to predict when
1442 just by looking at oldname and newname, unfortunately). In these
1443 cases, renaming through a temporary name avoids the problem.
1445 A second problem on Windows 95 is that renaming through a temp name when
1446 newname is uppercase fails (the final long name ends up in
1447 lowercase, although the short alias might be uppercase) UNLESS the
1448 long temp name is not 8.3.
1450 So, on Windows 95 we always rename through a temp name, and we make sure
1451 the temp name has a long extension to ensure correct renaming. */
1453 strcpy (temp
, map_w32_filename (oldname
, NULL
));
1455 if (os_subtype
== OS_WIN95
)
1459 if (p
= strrchr (temp
, '\\'))
1463 /* Force temp name to require a manufactured 8.3 alias - this
1464 seems to make the second rename work properly. */
1465 strcpy (p
, "_rename_temp.XXXXXX");
1467 if (rename (map_w32_filename (oldname
, NULL
), temp
) < 0)
1471 /* Emulate Unix behaviour - newname is deleted if it already exists
1472 (at least if it is a file; don't do this for directories).
1473 However, don't do this if we are just changing the case of the file
1474 name - we will end up deleting the file we are trying to rename! */
1475 newname
= map_w32_filename (newname
, NULL
);
1477 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1478 do not refer to the same file, eg. through share aliases. */
1479 if (stricmp (newname
, temp
) != 0
1480 && (attr
= GetFileAttributes (newname
)) != -1
1481 && (attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1483 _chmod (newname
, 0666);
1487 return rename (temp
, newname
);
1491 sys_rmdir (const char * path
)
1493 return _rmdir (map_w32_filename (path
, NULL
));
1497 sys_unlink (const char * path
)
1499 return _unlink (map_w32_filename (path
, NULL
));
1502 static FILETIME utc_base_ft
;
1503 static long double utc_base
;
1504 static int init
= 0;
1507 convert_time (FILETIME ft
)
1513 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1522 st
.wMilliseconds
= 0;
1524 SystemTimeToFileTime (&st
, &utc_base_ft
);
1525 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1526 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1530 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
1533 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
1535 return (time_t) (ret
* 1e-7);
1539 /* in case we ever have need of this */
1541 convert_from_time_t (time_t time
, FILETIME
* pft
)
1547 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1556 st
.wMilliseconds
= 0;
1558 SystemTimeToFileTime (&st
, &utc_base_ft
);
1559 utc_base
= (long double) utc_base_ft
.dwHighDateTime
1560 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
1564 /* time in 100ns units since 1-Jan-1601 */
1565 tmp
= (long double) time
* 1e7
+ utc_base
;
1566 pft
->dwHighDateTime
= (DWORD
) (tmp
/ (4096.0 * 1024 * 1024));
1567 pft
->dwLowDateTime
= (DWORD
) (tmp
- pft
->dwHighDateTime
);
1572 /* No reason to keep this; faking inode values either by hashing or even
1573 using the file index from GetInformationByHandle, is not perfect and
1574 so by default Emacs doesn't use the inode values on Windows.
1575 Instead, we now determine file-truename correctly (except for
1576 possible drive aliasing etc). */
1578 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1580 hashval (const unsigned char * str
)
1585 h
= (h
<< 4) + *str
++;
1591 /* Return the hash value of the canonical pathname, excluding the
1592 drive/UNC header, to get a hopefully unique inode number. */
1594 generate_inode_val (const char * name
)
1596 char fullname
[ MAX_PATH
];
1600 /* Get the truly canonical filename, if it exists. (Note: this
1601 doesn't resolve aliasing due to subst commands, or recognise hard
1603 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
1606 parse_root (fullname
, &p
);
1607 /* Normal W32 filesystems are still case insensitive. */
1614 /* MSVC stat function can't cope with UNC names and has other bugs, so
1615 replace it with our own. This also allows us to calculate consistent
1616 inode values without hacks in the main Emacs code. */
1618 stat (const char * path
, struct stat
* buf
)
1621 WIN32_FIND_DATA wfd
;
1626 int rootdir
= FALSE
;
1628 if (path
== NULL
|| buf
== NULL
)
1634 name
= (char *) map_w32_filename (path
, &path
);
1635 /* must be valid filename, no wild cards */
1636 if (strchr (name
, '*') || strchr (name
, '?'))
1642 /* Remove trailing directory separator, unless name is the root
1643 directory of a drive or UNC volume in which case ensure there
1644 is a trailing separator. */
1645 len
= strlen (name
);
1646 rootdir
= (path
>= name
+ len
- 1
1647 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
1648 name
= strcpy (alloca (len
+ 2), name
);
1652 if (!IS_DIRECTORY_SEP (name
[len
-1]))
1653 strcat (name
, "\\");
1654 if (GetDriveType (name
) < 2)
1659 memset (&wfd
, 0, sizeof (wfd
));
1660 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
1661 wfd
.ftCreationTime
= utc_base_ft
;
1662 wfd
.ftLastAccessTime
= utc_base_ft
;
1663 wfd
.ftLastWriteTime
= utc_base_ft
;
1664 strcpy (wfd
.cFileName
, name
);
1668 if (IS_DIRECTORY_SEP (name
[len
-1]))
1671 /* (This is hacky, but helps when doing file completions on
1672 network drives.) Optimize by using information available from
1673 active readdir if possible. */
1674 if (dir_find_handle
!= INVALID_HANDLE_VALUE
1675 && (len
= strlen (dir_pathname
)),
1676 strnicmp (name
, dir_pathname
, len
) == 0
1677 && IS_DIRECTORY_SEP (name
[len
])
1678 && stricmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
1680 /* This was the last entry returned by readdir. */
1681 wfd
= dir_find_data
;
1685 fh
= FindFirstFile (name
, &wfd
);
1686 if (fh
== INVALID_HANDLE_VALUE
)
1695 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1697 buf
->st_mode
= _S_IFDIR
;
1698 buf
->st_nlink
= 2; /* doesn't really matter */
1699 fake_inode
= 0; /* this doesn't either I think */
1701 else if (!NILP (Vw32_get_true_file_attributes
))
1703 /* This is more accurate in terms of gettting the correct number
1704 of links, but is quite slow (it is noticable when Emacs is
1705 making a list of file name completions). */
1706 BY_HANDLE_FILE_INFORMATION info
;
1708 /* No access rights required to get info. */
1709 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
1711 if (GetFileInformationByHandle (fh
, &info
))
1713 switch (GetFileType (fh
))
1715 case FILE_TYPE_DISK
:
1716 buf
->st_mode
= _S_IFREG
;
1718 case FILE_TYPE_PIPE
:
1719 buf
->st_mode
= _S_IFIFO
;
1721 case FILE_TYPE_CHAR
:
1722 case FILE_TYPE_UNKNOWN
:
1724 buf
->st_mode
= _S_IFCHR
;
1726 buf
->st_nlink
= info
.nNumberOfLinks
;
1727 /* Might as well use file index to fake inode values, but this
1728 is not guaranteed to be unique unless we keep a handle open
1729 all the time (even then there are situations where it is
1730 not unique). Reputedly, there are at most 48 bits of info
1731 (on NTFS, presumably less on FAT). */
1732 fake_inode
= info
.nFileIndexLow
^ info
.nFileIndexHigh
;
1743 /* Don't bother to make this information more accurate. */
1744 buf
->st_mode
= _S_IFREG
;
1750 /* Not sure if there is any point in this. */
1751 if (!NILP (Vw32_generate_fake_inodes
))
1752 fake_inode
= generate_inode_val (name
);
1753 else if (fake_inode
== 0)
1755 /* For want of something better, try to make everything unique. */
1756 static DWORD gen_num
= 0;
1757 fake_inode
= ++gen_num
;
1761 /* MSVC defines _ino_t to be short; other libc's might not. */
1762 if (sizeof (buf
->st_ino
) == 2)
1763 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
1765 buf
->st_ino
= fake_inode
;
1767 /* consider files to belong to current user */
1768 buf
->st_uid
= the_passwd
.pw_uid
;
1769 buf
->st_gid
= the_passwd
.pw_gid
;
1771 /* volume_info is set indirectly by map_w32_filename */
1772 buf
->st_dev
= volume_info
.serialnum
;
1773 buf
->st_rdev
= volume_info
.serialnum
;
1776 buf
->st_size
= wfd
.nFileSizeLow
;
1778 /* Convert timestamps to Unix format. */
1779 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
1780 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
1781 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
1782 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
1783 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
1785 /* determine rwx permissions */
1786 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
1787 permission
= _S_IREAD
;
1789 permission
= _S_IREAD
| _S_IWRITE
;
1791 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1792 permission
|= _S_IEXEC
;
1795 char * p
= strrchr (name
, '.');
1797 && (stricmp (p
, ".exe") == 0 ||
1798 stricmp (p
, ".com") == 0 ||
1799 stricmp (p
, ".bat") == 0 ||
1800 stricmp (p
, ".cmd") == 0))
1801 permission
|= _S_IEXEC
;
1804 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
1811 /* Wrappers for winsock functions to map between our file descriptors
1812 and winsock's handles; also set h_errno for convenience.
1814 To allow Emacs to run on systems which don't have winsock support
1815 installed, we dynamically link to winsock on startup if present, and
1816 otherwise provide the minimum necessary functionality
1817 (eg. gethostname). */
1819 /* function pointers for relevant socket functions */
1820 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
1821 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
1822 int (PASCAL
*pfn_WSAGetLastError
) (void);
1823 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
1824 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1825 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
1826 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
1827 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
1828 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
1829 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
1830 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
1831 int (PASCAL
*pfn_WSACleanup
) (void);
1833 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
1834 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
1835 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
1836 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
1837 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
1838 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
1840 /* SetHandleInformation is only needed to make sockets non-inheritable. */
1841 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
1842 #ifndef HANDLE_FLAG_INHERIT
1843 #define HANDLE_FLAG_INHERIT 1
1847 static int winsock_inuse
;
1852 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
1854 /* Not sure what would cause WSAENETDOWN, or even if it can happen
1855 after WSAStartup returns successfully, but it seems reasonable
1856 to allow unloading winsock anyway in that case. */
1857 if (pfn_WSACleanup () == 0 ||
1858 pfn_WSAGetLastError () == WSAENETDOWN
)
1860 if (FreeLibrary (winsock_lib
))
1869 init_winsock (int load_now
)
1871 WSADATA winsockData
;
1873 if (winsock_lib
!= NULL
)
1876 pfn_SetHandleInformation
= NULL
;
1877 pfn_SetHandleInformation
1878 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1879 "SetHandleInformation");
1881 winsock_lib
= LoadLibrary ("wsock32.dll");
1883 if (winsock_lib
!= NULL
)
1885 /* dynamically link to socket functions */
1887 #define LOAD_PROC(fn) \
1888 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
1891 LOAD_PROC( WSAStartup
);
1892 LOAD_PROC( WSASetLastError
);
1893 LOAD_PROC( WSAGetLastError
);
1894 LOAD_PROC( socket
);
1896 LOAD_PROC( connect
);
1897 LOAD_PROC( ioctlsocket
);
1900 LOAD_PROC( closesocket
);
1901 LOAD_PROC( shutdown
);
1904 LOAD_PROC( inet_addr
);
1905 LOAD_PROC( gethostname
);
1906 LOAD_PROC( gethostbyname
);
1907 LOAD_PROC( getservbyname
);
1908 LOAD_PROC( WSACleanup
);
1912 /* specify version 1.1 of winsock */
1913 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
1915 if (winsockData
.wVersion
!= 0x101)
1920 /* Report that winsock exists and is usable, but leave
1921 socket functions disabled. I am assuming that calling
1922 WSAStartup does not require any network interaction,
1923 and in particular does not cause or require a dial-up
1924 connection to be established. */
1927 FreeLibrary (winsock_lib
);
1935 FreeLibrary (winsock_lib
);
1945 /* function to set h_errno for compatability; map winsock error codes to
1946 normal system codes where they overlap (non-overlapping definitions
1947 are already in <sys/socket.h> */
1948 static void set_errno ()
1950 if (winsock_lib
== NULL
)
1953 h_errno
= pfn_WSAGetLastError ();
1957 case WSAEACCES
: h_errno
= EACCES
; break;
1958 case WSAEBADF
: h_errno
= EBADF
; break;
1959 case WSAEFAULT
: h_errno
= EFAULT
; break;
1960 case WSAEINTR
: h_errno
= EINTR
; break;
1961 case WSAEINVAL
: h_errno
= EINVAL
; break;
1962 case WSAEMFILE
: h_errno
= EMFILE
; break;
1963 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
1964 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
1969 static void check_errno ()
1971 if (h_errno
== 0 && winsock_lib
!= NULL
)
1972 pfn_WSASetLastError (0);
1975 /* [andrewi 3-May-96] I've had conflicting results using both methods,
1976 but I believe the method of keeping the socket handle separate (and
1977 insuring it is not inheritable) is the correct one. */
1979 //#define SOCK_REPLACE_HANDLE
1981 #ifdef SOCK_REPLACE_HANDLE
1982 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
1984 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
1988 sys_socket(int af
, int type
, int protocol
)
1994 if (winsock_lib
== NULL
)
1997 return INVALID_SOCKET
;
2002 /* call the real socket function */
2003 s
= (long) pfn_socket (af
, type
, protocol
);
2005 if (s
!= INVALID_SOCKET
)
2007 /* Although under NT 3.5 _open_osfhandle will accept a socket
2008 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2009 that does not work under NT 3.1. However, we can get the same
2010 effect by using a backdoor function to replace an existing
2011 descriptor handle with the one we want. */
2013 /* allocate a file descriptor (with appropriate flags) */
2014 fd
= _open ("NUL:", _O_RDWR
);
2017 #ifdef SOCK_REPLACE_HANDLE
2018 /* now replace handle to NUL with our socket handle */
2019 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
2021 _set_osfhnd (fd
, s
);
2022 /* setmode (fd, _O_BINARY); */
2024 /* Make a non-inheritable copy of the socket handle. */
2027 HANDLE new_s
= INVALID_HANDLE_VALUE
;
2029 parent
= GetCurrentProcess ();
2031 /* Apparently there is a bug in NT 3.51 with some service
2032 packs, which prevents using DuplicateHandle to make a
2033 socket handle non-inheritable (causes WSACleanup to
2034 hang). The work-around is to use SetHandleInformation
2035 instead if it is available and implemented. */
2036 if (!pfn_SetHandleInformation
2037 || !pfn_SetHandleInformation ((HANDLE
) s
,
2038 HANDLE_FLAG_INHERIT
,
2039 HANDLE_FLAG_INHERIT
))
2041 DuplicateHandle (parent
,
2047 DUPLICATE_SAME_ACCESS
);
2048 pfn_closesocket (s
);
2051 fd_info
[fd
].hnd
= (HANDLE
) s
;
2055 /* set our own internal flags */
2056 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
2062 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
2064 /* attach child_process to fd_info */
2065 if (fd_info
[ fd
].cp
!= NULL
)
2067 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
2071 fd_info
[ fd
].cp
= cp
;
2074 winsock_inuse
++; /* count open sockets */
2081 pfn_closesocket (s
);
2091 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
2093 if (winsock_lib
== NULL
)
2096 return SOCKET_ERROR
;
2100 if (fd_info
[s
].flags
& FILE_SOCKET
)
2102 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
2103 if (rc
== SOCKET_ERROR
)
2108 return SOCKET_ERROR
;
2113 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
2115 if (winsock_lib
== NULL
)
2118 return SOCKET_ERROR
;
2122 if (fd_info
[s
].flags
& FILE_SOCKET
)
2124 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
2125 if (rc
== SOCKET_ERROR
)
2130 return SOCKET_ERROR
;
2134 sys_htons (u_short hostshort
)
2136 return (winsock_lib
!= NULL
) ?
2137 pfn_htons (hostshort
) : hostshort
;
2141 sys_ntohs (u_short netshort
)
2143 return (winsock_lib
!= NULL
) ?
2144 pfn_ntohs (netshort
) : netshort
;
2148 sys_inet_addr (const char * cp
)
2150 return (winsock_lib
!= NULL
) ?
2151 pfn_inet_addr (cp
) : INADDR_NONE
;
2155 sys_gethostname (char * name
, int namelen
)
2157 if (winsock_lib
!= NULL
)
2158 return pfn_gethostname (name
, namelen
);
2160 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
2161 return !GetComputerName (name
, &namelen
);
2164 return SOCKET_ERROR
;
2168 sys_gethostbyname(const char * name
)
2170 struct hostent
* host
;
2172 if (winsock_lib
== NULL
)
2179 host
= pfn_gethostbyname (name
);
2186 sys_getservbyname(const char * name
, const char * proto
)
2188 struct servent
* serv
;
2190 if (winsock_lib
== NULL
)
2197 serv
= pfn_getservbyname (name
, proto
);
2204 sys_shutdown (int s
, int how
)
2208 if (winsock_lib
== NULL
)
2211 return SOCKET_ERROR
;
2215 if (fd_info
[s
].flags
& FILE_SOCKET
)
2217 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
2218 if (rc
== SOCKET_ERROR
)
2223 return SOCKET_ERROR
;
2226 #endif /* HAVE_SOCKETS */
2229 /* Shadow main io functions: we need to handle pipes and sockets more
2230 intelligently, and implement non-blocking mode as well. */
2237 if (fd
< 0 || fd
>= MAXDESC
)
2245 child_process
* cp
= fd_info
[fd
].cp
;
2247 fd_info
[fd
].cp
= NULL
;
2249 if (CHILD_ACTIVE (cp
))
2251 /* if last descriptor to active child_process then cleanup */
2253 for (i
= 0; i
< MAXDESC
; i
++)
2257 if (fd_info
[i
].cp
== cp
)
2263 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2265 #ifndef SOCK_REPLACE_HANDLE
2266 if (winsock_lib
== NULL
) abort ();
2268 pfn_shutdown (SOCK_HANDLE (fd
), 2);
2269 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
2271 winsock_inuse
--; /* count open sockets */
2279 /* Note that sockets do not need special treatment here (at least on
2280 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2281 closesocket is equivalent to CloseHandle, which is to be expected
2282 because socket handles are fully fledged kernel handles. */
2286 fd_info
[fd
].flags
= 0;
2299 /* duplicate our internal info as well */
2300 fd_info
[new_fd
] = fd_info
[fd
];
2307 sys_dup2 (int src
, int dst
)
2311 if (dst
< 0 || dst
>= MAXDESC
)
2317 /* make sure we close the destination first if it's a pipe or socket */
2318 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
2321 rc
= _dup2 (src
, dst
);
2324 /* duplicate our internal info as well */
2325 fd_info
[dst
] = fd_info
[src
];
2330 /* From callproc.c */
2331 extern Lisp_Object Vbinary_process_input
;
2332 extern Lisp_Object Vbinary_process_output
;
2334 /* Unix pipe() has only one arg */
2336 sys_pipe (int * phandles
)
2342 /* make pipe handles non-inheritable; when we spawn a child, we
2343 replace the relevant handle with an inheritable one. Also put
2344 pipes into binary mode; we will do text mode translation ourselves
2346 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
2350 flags
= FILE_PIPE
| FILE_READ
;
2351 if (!NILP (Vbinary_process_output
))
2352 flags
|= FILE_BINARY
;
2353 fd_info
[phandles
[0]].flags
= flags
;
2355 flags
= FILE_PIPE
| FILE_WRITE
;
2356 if (!NILP (Vbinary_process_input
))
2357 flags
|= FILE_BINARY
;
2358 fd_info
[phandles
[1]].flags
= flags
;
2365 extern Lisp_Object Vw32_pipe_read_delay
;
2367 /* Function to do blocking read of one byte, needed to implement
2368 select. It is only allowed on sockets and pipes. */
2370 _sys_read_ahead (int fd
)
2375 if (fd
< 0 || fd
>= MAXDESC
)
2376 return STATUS_READ_ERROR
;
2378 cp
= fd_info
[fd
].cp
;
2380 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
2381 return STATUS_READ_ERROR
;
2383 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
2384 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
2386 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
2390 cp
->status
= STATUS_READ_IN_PROGRESS
;
2392 if (fd_info
[fd
].flags
& FILE_PIPE
)
2394 rc
= _read (fd
, &cp
->chr
, sizeof (char));
2396 /* Give subprocess time to buffer some more output for us before
2397 reporting that input is available; we need this because Windows 95
2398 connects DOS programs to pipes by making the pipe appear to be
2399 the normal console stdout - as a result most DOS programs will
2400 write to stdout without buffering, ie. one character at a
2401 time. Even some W32 programs do this - "dir" in a command
2402 shell on NT is very slow if we don't do this. */
2405 int wait
= XINT (Vw32_pipe_read_delay
);
2411 /* Yield remainder of our time slice, effectively giving a
2412 temporary priority boost to the child process. */
2417 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
2418 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
2421 if (rc
== sizeof (char))
2422 cp
->status
= STATUS_READ_SUCCEEDED
;
2424 cp
->status
= STATUS_READ_FAILED
;
2430 sys_read (int fd
, char * buffer
, unsigned int count
)
2435 char * orig_buffer
= buffer
;
2437 if (fd
< 0 || fd
>= MAXDESC
)
2443 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2445 child_process
*cp
= fd_info
[fd
].cp
;
2447 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
2455 /* re-read CR carried over from last read */
2456 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
2458 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
2464 /* presence of a child_process structure means we are operating in
2465 non-blocking mode - otherwise we just call _read directly.
2466 Note that the child_process structure might be missing because
2467 reap_subprocess has been called; in this case the pipe is
2468 already broken, so calling _read on it is okay. */
2471 int current_status
= cp
->status
;
2473 switch (current_status
)
2475 case STATUS_READ_FAILED
:
2476 case STATUS_READ_ERROR
:
2477 /* report normal 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
);
2508 nchars
+= _read (fd
, buffer
, to_read
);
2511 else /* FILE_SOCKET */
2513 if (winsock_lib
== NULL
) abort ();
2515 /* do the equivalent of a non-blocking read */
2516 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
2517 if (waiting
== 0 && nchars
== 0)
2519 h_errno
= errno
= EWOULDBLOCK
;
2525 /* always use binary mode for sockets */
2526 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
2527 if (res
== SOCKET_ERROR
)
2529 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
2530 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2540 nchars
+= _read (fd
, buffer
, count
);
2542 /* Perform text mode translation if required. */
2543 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2545 nchars
= crlf_to_lf (nchars
, orig_buffer
);
2546 /* If buffer contains only CR, return that. To be absolutely
2547 sure we should attempt to read the next char, but in
2548 practice a CR to be followed by LF would not appear by
2549 itself in the buffer. */
2550 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
2552 fd_info
[fd
].flags
|= FILE_LAST_CR
;
2556 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
2560 nchars
= _read (fd
, buffer
, count
);
2565 /* For now, don't bother with a non-blocking mode */
2567 sys_write (int fd
, const void * buffer
, unsigned int count
)
2571 if (fd
< 0 || fd
>= MAXDESC
)
2577 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
2579 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
2585 /* Perform text mode translation if required. */
2586 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
2588 char * tmpbuf
= alloca (count
* 2);
2589 unsigned char * src
= (void *)buffer
;
2590 unsigned char * dst
= tmpbuf
;
2595 unsigned char *next
;
2596 /* copy next line or remaining bytes */
2597 next
= _memccpy (dst
, src
, '\n', nbytes
);
2600 /* copied one line ending with '\n' */
2601 int copied
= next
- dst
;
2604 /* insert '\r' before '\n' */
2611 /* copied remaining partial line -> now finished */
2619 if (fd_info
[fd
].flags
& FILE_SOCKET
)
2621 if (winsock_lib
== NULL
) abort ();
2622 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
2623 if (nchars
== SOCKET_ERROR
)
2625 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
2626 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
2632 nchars
= _write (fd
, buffer
, count
);
2642 /* shutdown the socket interface if necessary */
2651 /* Initialise the socket interface now if available and requested by
2652 the user by defining PRELOAD_WINSOCK; otherwise loading will be
2653 delayed until open-network-stream is called (w32-has-winsock can
2654 also be used to dynamically load or reload winsock).
2656 Conveniently, init_environment is called before us, so
2657 PRELOAD_WINSOCK can be set in the registry. */
2659 /* Always initialize this correctly. */
2662 if (getenv ("PRELOAD_WINSOCK") != NULL
)
2663 init_winsock (TRUE
);
2666 /* Initial preparation for subprocess support: replace our standard
2667 handles with non-inheritable versions. */
2670 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
2671 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
2672 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
2674 parent
= GetCurrentProcess ();
2676 /* ignore errors when duplicating and closing; typically the
2677 handles will be invalid when running as a gui program. */
2678 DuplicateHandle (parent
,
2679 GetStdHandle (STD_INPUT_HANDLE
),
2684 DUPLICATE_SAME_ACCESS
);
2686 DuplicateHandle (parent
,
2687 GetStdHandle (STD_OUTPUT_HANDLE
),
2692 DUPLICATE_SAME_ACCESS
);
2694 DuplicateHandle (parent
,
2695 GetStdHandle (STD_ERROR_HANDLE
),
2700 DUPLICATE_SAME_ACCESS
);
2706 if (stdin_save
!= INVALID_HANDLE_VALUE
)
2707 _open_osfhandle ((long) stdin_save
, O_TEXT
);
2709 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
2712 if (stdout_save
!= INVALID_HANDLE_VALUE
)
2713 _open_osfhandle ((long) stdout_save
, O_TEXT
);
2715 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2718 if (stderr_save
!= INVALID_HANDLE_VALUE
)
2719 _open_osfhandle ((long) stderr_save
, O_TEXT
);
2721 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
2725 /* unfortunately, atexit depends on implementation of malloc */
2726 /* atexit (term_ntproc); */
2727 signal (SIGABRT
, term_ntproc
);
2729 /* determine which drives are fixed, for GetCachedVolumeInformation */
2731 /* GetDriveType must have trailing backslash. */
2732 char drive
[] = "A:\\";
2734 /* Loop over all possible drive letters */
2735 while (*drive
<= 'Z')
2737 /* Record if this drive letter refers to a fixed drive. */
2738 fixed_drives
[DRIVE_INDEX (*drive
)] =
2739 (GetDriveType (drive
) == DRIVE_FIXED
);