1 /* Utility and Unix shadow routines for XEmacs on Windows NT.
2 Copyright (C) 1994, 1995 Free Software Foundation, Inc.
4 This file is part of XEmacs.
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; see the file COPYING. If not, write to the Free
18 Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
22 Geoff Voelker (voelker@cs.washington.edu) 7-29-94 */
24 /* Adapted for XEmacs by David Hobley <david@spook-le0.cia.com.au> */
25 /* Sync'ed with Emacs 19.34.6 by Marc Paquette <marcpa@cam.org> */
35 #include "syssignal.h"
45 #include <stddef.h> /* for offsetof */
58 extern Lisp_Object Vmswindows_downcase_file_names;
60 extern Lisp_Object Vwin32_generate_fake_inodes;
62 extern Lisp_Object Vmswindows_get_true_file_attributes;
64 extern char *get_home_directory(void);
66 static char startup_dir[ MAXPATHLEN ];
68 /* Get the current working directory. */
73 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
77 /* Emacs doesn't actually change directory itself, and we want to
78 force our real wd to be where emacs.exe is to avoid unnecessary
79 conflicts when trying to rename or delete directories. */
80 strcpy (dir, startup_dir);
85 /* Emulate getloadavg. */
87 getloadavg (double loadavg[], int nelem)
91 /* A faithful emulation is going to have to be saved for a rainy day. */
92 for (i = 0; i < nelem; i++)
99 /* Emulate getpwuid, getpwnam and others. */
101 #define PASSWD_FIELD_SIZE 256
103 static char the_passwd_name[PASSWD_FIELD_SIZE];
104 static char the_passwd_passwd[PASSWD_FIELD_SIZE];
105 static char the_passwd_gecos[PASSWD_FIELD_SIZE];
106 static char the_passwd_dir[PASSWD_FIELD_SIZE];
107 static char the_passwd_shell[PASSWD_FIELD_SIZE];
109 static struct passwd the_passwd =
124 return the_passwd.pw_uid;
130 /* I could imagine arguing for checking to see whether the user is
131 in the Administrators group and returning a UID of 0 for that
132 case, but I don't know how wise that would be in the long run. */
139 return the_passwd.pw_gid;
151 if (uid == the_passwd.pw_uid)
157 getpwnam (const char *name)
161 pw = getpwuid (getuid ());
165 if (stricmp (name, pw->pw_name))
174 /* Find the user's real name by opening the process token and
175 looking up the name associated with the user-sid in that token.
177 Use the relative portion of the identifier authority value from
178 the user-sid as the user id value (same for group id using the
179 primary group sid from the process token). */
181 char user_sid[256], name[256], domain[256];
182 DWORD length = sizeof (name), dlength = sizeof (domain), trash;
184 SID_NAME_USE user_type;
186 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
187 && GetTokenInformation (token, TokenUser,
188 (PVOID) user_sid, sizeof (user_sid), &trash)
189 && LookupAccountSid (NULL, *((PSID *) user_sid), name, &length,
190 domain, &dlength, &user_type))
192 strcpy (the_passwd.pw_name, name);
193 /* Determine a reasonable uid value. */
194 if (stricmp ("administrator", name) == 0)
196 the_passwd.pw_uid = 0;
197 the_passwd.pw_gid = 0;
201 SID_IDENTIFIER_AUTHORITY * pSIA;
203 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
204 /* I believe the relative portion is the last 4 bytes (of 6)
206 the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
207 (pSIA->Value[3] << 16) +
208 (pSIA->Value[4] << 8) +
209 (pSIA->Value[5] << 0));
210 /* restrict to conventional uid range for normal users */
211 the_passwd.pw_uid = the_passwd.pw_uid % 60001;
214 if (GetTokenInformation (token, TokenPrimaryGroup,
215 (PVOID) user_sid, sizeof (user_sid), &trash))
217 SID_IDENTIFIER_AUTHORITY * pSIA;
219 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
220 the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
221 (pSIA->Value[3] << 16) +
222 (pSIA->Value[4] << 8) +
223 (pSIA->Value[5] << 0));
224 /* I don't know if this is necessary, but for safety... */
225 the_passwd.pw_gid = the_passwd.pw_gid % 60001;
228 the_passwd.pw_gid = the_passwd.pw_uid;
231 /* If security calls are not supported (presumably because we
232 are running under Windows 95), fallback to this. */
233 else if (GetUserName (name, &length))
235 strcpy (the_passwd.pw_name, name);
236 if (stricmp ("administrator", name) == 0)
237 the_passwd.pw_uid = 0;
239 the_passwd.pw_uid = 123;
240 the_passwd.pw_gid = the_passwd.pw_uid;
244 strcpy (the_passwd.pw_name, "unknown");
245 the_passwd.pw_uid = 123;
246 the_passwd.pw_gid = 123;
249 /* Ensure HOME and SHELL are defined. */
252 * With XEmacs, setting $HOME is deprecated.
254 if (getenv ("HOME") == NULL)
257 if (getenv ("SHELL") == NULL)
258 putenv ((GetVersion () & 0x80000000) ? "SHELL=command" : "SHELL=cmd");
260 /* Set dir and shell from environment variables. */
261 strcpy (the_passwd.pw_dir, get_home_directory());
262 strcpy (the_passwd.pw_shell, getenv ("SHELL"));
268 /* Normalize filename by converting all path separators to
269 the specified separator. Also conditionally convert upper
270 case path name components to lower case. */
273 normalize_filename (fp, path_sep)
280 /* Always lower-case drive letters a-z, even if the filesystem
281 preserves case in filenames.
282 This is so filenames can be compared by string comparison
283 functions that are case-sensitive. Even case-preserving filesystems
284 do not distinguish case in drive letters. */
285 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
291 if (NILP (Vmswindows_downcase_file_names))
295 if (*fp == '/' || *fp == '\\')
302 sep = path_sep; /* convert to this path separator */
303 elem = fp; /* start of current path element */
306 if (*fp >= 'a' && *fp <= 'z')
307 elem = 0; /* don't convert this element */
309 if (*fp == 0 || *fp == ':')
311 sep = *fp; /* restore current separator (or 0) */
312 *fp = '/'; /* after conversion of this element */
315 if (*fp == '/' || *fp == '\\')
317 if (elem && elem != fp)
319 *fp = 0; /* temporary end of string */
320 _strlwr (elem); /* while we convert to lower case */
322 *fp = sep; /* convert (or restore) path separator */
323 elem = fp + 1; /* next element starts after separator */
329 /* Destructively turn backslashes into slashes. */
331 dostounix_filename (p)
334 normalize_filename (p, '/');
337 /* Destructively turn slashes into backslashes. */
339 unixtodos_filename (p)
342 normalize_filename (p, '\\');
345 /* Remove all CR's that are followed by a LF.
346 (From msdos.c...probably should figure out a way to share it,
347 although this code isn't going to ever change.) */
349 crlf_to_lf (n, buf, lf_count)
351 REGISTER unsigned char *buf;
352 REGISTER unsigned *lf_count;
354 unsigned char *np = buf;
355 unsigned char *startp = buf;
356 unsigned char *endp = buf + n;
360 while (buf < endp - 1)
366 if (*(++buf) != 0x0a)
381 /* Parse the root part of file name, if present. Return length and
382 optionally store pointer to char after root. */
384 parse_root (char * name, char ** pPath)
391 /* find the root name of the volume if given */
392 if (isalpha (name[0]) && name[1] == ':')
394 /* skip past drive specifier */
396 if (IS_DIRECTORY_SEP (name[0]))
399 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
405 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
410 if (IS_DIRECTORY_SEP (name[0]))
420 /* Get long base name for name; name is assumed to be absolute. */
422 get_long_basename (char * name, char * buf, int size)
424 WIN32_FIND_DATA find_data;
430 /* If the last component of NAME has a wildcard character,
431 return it as the basename. */
432 p = name + strlen (name);
433 while (*p != '\\' && *p != ':' && p > name) p--;
435 if (strchr (p, '*') || strchr (p, '?'))
437 if ((len = strlen (p)) < size)
438 memcpy (buf, p, len + 1);
445 dir_handle = FindFirstFile (name, &find_data);
446 if (dir_handle != INVALID_HANDLE_VALUE)
448 if ((len = strlen (find_data.cFileName)) < size)
449 memcpy (buf, find_data.cFileName, len + 1);
452 FindClose (dir_handle);
457 /* Get long name for file, if possible (assumed to be absolute). */
459 win32_get_long_filename (char * name, char * buf, int size)
464 char full[ MAX_PATH ];
471 /* Use local copy for destructive modification. */
472 memcpy (full, name, len+1);
473 unixtodos_filename (full);
475 /* Copy root part verbatim. */
476 len = parse_root (full, &p);
477 memcpy (o, full, len);
484 p = strchr (q, '\\');
486 len = get_long_basename (full, o, size);
504 while (p != NULL && *p);
510 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
512 #if 0 /* #### We do not need those, do we? -kkm */
514 unrequest_sigio (void)
526 #define REG_ROOT "SOFTWARE\\GNU\\XEmacs"
529 nt_get_resource (key, lpdwtype)
534 HKEY hrootkey = NULL;
538 /* Check both the current user and the local machine to see if
539 we have any resources. */
541 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
545 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
546 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
547 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
552 if (lpvalue) xfree (lpvalue);
554 RegCloseKey (hrootkey);
557 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
561 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS &&
562 (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL &&
563 RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
568 if (lpvalue) xfree (lpvalue);
570 RegCloseKey (hrootkey);
579 /* Check for environment variables and use registry if they don't exist */
585 static char * env_vars[] =
600 for (i = 0; i < countof (env_vars); i++)
602 if (!getenv (env_vars[i]) &&
603 (lpval = nt_get_resource (env_vars[i], &dwType)) != NULL)
605 if (dwType == REG_EXPAND_SZ)
607 char buf1[500], buf2[500];
609 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, 500);
610 _snprintf (buf2, 499, "%s=%s", env_vars[i], buf1);
611 putenv (strdup (buf2));
613 else if (dwType == REG_SZ)
617 _snprintf (buf, 499, "%s=%s", env_vars[i], lpval);
618 putenv (strdup (buf));
626 /* Another special case: on NT, the PATH variable is actually named
627 "Path" although cmd.exe (perhaps NT itself) arranges for
628 environment variable lookup and setting to be case insensitive.
629 However, Emacs assumes a fully case sensitive environment, so we
630 need to change "Path" to "PATH" to match the expectations of
631 various elisp packages. We do this by the sneaky method of
632 modifying the string in the C runtime environ entry.
634 The same applies to COMSPEC. */
638 for (envp = environ; *envp; envp++)
639 if (_strnicmp (*envp, "PATH=", 5) == 0)
640 memcpy (*envp, "PATH=", 5);
641 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
642 memcpy (*envp, "COMSPEC=", 8);
645 /* Remember the initial working directory for getwd, then make the
646 real wd be the location of emacs.exe to avoid conflicts when
647 renaming or deleting directories. (We also don't call chdir when
648 running subprocesses for the same reason.) */
649 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
654 char modname[MAX_PATH];
656 if (!GetModuleFileName (NULL, modname, MAX_PATH))
658 if ((p = strrchr (modname, '\\')) == NULL)
662 SetCurrentDirectory (modname);
668 #ifndef HAVE_X_WINDOWS
669 /* X11R6 on NT provides the single parameter version of this command. */
671 #include <sys/timeb.h>
673 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
675 gettimeofday (struct timeval *tv, struct timezone *tz)
680 tv->tv_sec = tb.time;
681 tv->tv_usec = tb.millitm * 1000L;
684 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
685 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
689 #endif /* HAVE_X_WINDOWS */
691 /* ------------------------------------------------------------------------- */
692 /* IO support and wrapper functions for Win32 API. */
693 /* ------------------------------------------------------------------------- */
695 /* Place a wrapper around the MSVC version of ctime. It returns NULL
696 on network directories, so we handle that case here.
697 (Ulrich Leodolter, 1/11/95). */
699 sys_ctime (const time_t *t)
701 char *str = (char *) ctime (t);
702 return (str ? str : "Sun Jan 01 00:00:00 1970");
705 /* Emulate sleep...we could have done this with a define, but that
706 would necessitate including windows.h in the files that used it.
707 This is much easier. */
709 #ifndef HAVE_X_WINDOWS
711 sys_sleep (int seconds)
713 Sleep (seconds * 1000);
717 /* #### This is an evil dirty hack. We must get rid of it.
718 Word "munging" is not in XEmacs lexicon. - kkm */
720 /* Internal MSVC data and functions for low-level descriptor munging */
721 #if (_MSC_VER == 900)
722 extern char _osfile[];
724 extern int __cdecl _set_osfhnd (int fd, long h);
725 extern int __cdecl _free_osfhnd (int fd);
727 /* parallel array of private info on file handles */
728 filedesc fd_info [ MAXDESC ];
730 typedef struct volume_info_data {
731 struct volume_info_data * next;
733 /* time when info was obtained */
736 /* actual volume info */
745 /* Global referenced by various functions. */
746 static volume_info_data volume_info;
748 /* Vector to indicate which drives are local and fixed (for which cached
749 data never expires). */
750 static BOOL fixed_drives[26];
752 /* Consider cached volume information to be stale if older than 10s,
753 at least for non-local drives. Info for fixed drives is never stale. */
754 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
755 #define VOLINFO_STILL_VALID( root_dir, info ) \
756 ( ( isalpha (root_dir[0]) && \
757 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
758 || GetTickCount () - info->timestamp < 10000 )
760 /* Cache support functions. */
762 /* Simple linked list with linear search is sufficient. */
763 static volume_info_data *volume_cache = NULL;
765 static volume_info_data *
766 lookup_volume_info (char * root_dir)
768 volume_info_data * info;
770 for (info = volume_cache; info; info = info->next)
771 if (stricmp (info->root_dir, root_dir) == 0)
777 add_volume_info (char * root_dir, volume_info_data * info)
779 info->root_dir = xstrdup (root_dir);
780 info->next = volume_cache;
785 /* Wrapper for GetVolumeInformation, which uses caching to avoid
786 performance penalty (~2ms on 486 for local drives, 7.5ms for local
787 cdrom drive, ~5-10ms or more for remote drives on LAN). */
789 GetCachedVolumeInformation (char * root_dir)
791 volume_info_data * info;
792 char default_root[ MAX_PATH ];
794 /* NULL for root_dir means use root from current directory. */
795 if (root_dir == NULL)
797 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
799 parse_root (default_root, &root_dir);
801 root_dir = default_root;
804 /* Local fixed drives can be cached permanently. Removable drives
805 cannot be cached permanently, since the volume name and serial
806 number (if nothing else) can change. Remote drives should be
807 treated as if they are removable, since there is no sure way to
808 tell whether they are or not. Also, the UNC association of drive
809 letters mapped to remote volumes can be changed at any time (even
810 by other processes) without notice.
812 As a compromise, so we can benefit from caching info for remote
813 volumes, we use a simple expiry mechanism to invalidate cache
814 entries that are more than ten seconds old. */
817 /* No point doing this, because WNetGetConnection is even slower than
818 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
819 GetDriveType is about the only call of this type which does not
820 involve network access, and so is extremely quick). */
822 /* Map drive letter to UNC if remote. */
823 if ( isalpha( root_dir[0] ) && !fixed[ DRIVE_INDEX( root_dir[0] ) ] )
825 char remote_name[ 256 ];
826 char drive[3] = { root_dir[0], ':' };
828 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
834 info = lookup_volume_info (root_dir);
836 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
844 /* Info is not cached, or is stale. */
845 if (!GetVolumeInformation (root_dir,
850 type, sizeof (type)))
853 /* Cache the volume information for future use, overwriting existing
857 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
858 add_volume_info (root_dir, info);
866 info->name = xstrdup (name);
867 info->serialnum = serialnum;
868 info->maxcomp = maxcomp;
870 info->type = xstrdup (type);
871 info->timestamp = GetTickCount ();
877 /* Get information on the volume where name is held; set path pointer to
878 start of pathname in name (past UNC header\volume header if present). */
880 get_volume_info (const char * name, const char ** pPath)
883 char *rootname = NULL; /* default to current volume */
884 volume_info_data * info;
889 /* find the root name of the volume if given */
890 if (isalpha (name[0]) && name[1] == ':')
898 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
905 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
918 info = GetCachedVolumeInformation (rootname);
921 /* Set global referenced by other functions. */
928 /* Determine if volume is FAT format (ie. only supports short 8.3
929 names); also set path pointer to start of pathname in name. */
931 is_fat_volume (const char * name, const char ** pPath)
933 if (get_volume_info (name, pPath))
934 return (volume_info.maxcomp == 12);
938 /* Map filename to a legal 8.3 name if necessary. */
940 map_win32_filename (const char * name, const char ** pPath)
942 static char shortname[MAX_PATH];
943 char * str = shortname;
946 const char * save_name = name;
948 if (is_fat_volume (name, &path)) /* truncate to 8.3 */
950 REGISTER int left = 8; /* maximum number of chars in part */
951 REGISTER int extn = 0; /* extension added? */
952 REGISTER int dots = 2; /* maximum number of dots allowed */
955 *str++ = *name++; /* skip past UNC header */
957 while ((c = *name++))
964 extn = 0; /* reset extension flags */
965 dots = 2; /* max 2 dots */
966 left = 8; /* max length 8 for main part */
970 extn = 0; /* reset extension flags */
971 dots = 2; /* max 2 dots */
972 left = 8; /* max length 8 for main part */
977 /* Convert path components of the form .xxx to _xxx,
978 but leave . and .. as they are. This allows .emacs
979 to be read as _emacs, for example. */
983 IS_DIRECTORY_SEP (*name))
998 extn = 1; /* we've got an extension */
999 left = 3; /* 3 chars in extension */
1003 /* any embedded dots after the first are converted to _ */
1008 case '#': /* don't lose these, they're important */
1010 str[-1] = c; /* replace last character of part */
1015 *str++ = tolower (c); /* map to lower case (looks nicer) */
1017 dots = 0; /* started a path component */
1026 strcpy (shortname, name);
1027 unixtodos_filename (shortname);
1031 *pPath = shortname + (path - save_name);
1037 /* Emulate the Unix directory procedures opendir, closedir,
1038 and readdir. We can't use the procedures supplied in sysdep.c,
1039 so we provide them here. */
1041 struct direct dir_static; /* simulated directory contents */
1042 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
1043 static int dir_is_fat;
1044 static char dir_pathname[MAXPATHLEN+1];
1045 static WIN32_FIND_DATA dir_find_data;
1048 opendir (const char *filename)
1052 /* Opening is done by FindFirstFile. However, a read is inherent to
1053 this operation, so we defer the open until read time. */
1055 if (!(dirp = (DIR *) xmalloc (sizeof (DIR))))
1057 if (dir_find_handle != INVALID_HANDLE_VALUE)
1064 strncpy (dir_pathname, map_win32_filename (filename, NULL), MAXPATHLEN);
1065 dir_pathname[MAXPATHLEN] = '\0';
1066 dir_is_fat = is_fat_volume (filename, NULL);
1072 closedir (DIR *dirp)
1074 /* If we have a find-handle open, close it. */
1075 if (dir_find_handle != INVALID_HANDLE_VALUE)
1077 FindClose (dir_find_handle);
1078 dir_find_handle = INVALID_HANDLE_VALUE;
1080 xfree ((char *) dirp);
1086 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1087 if (dir_find_handle == INVALID_HANDLE_VALUE)
1089 char filename[MAXNAMLEN + 3];
1092 strcpy (filename, dir_pathname);
1093 ln = strlen (filename) - 1;
1094 if (!IS_DIRECTORY_SEP (filename[ln]))
1095 strcat (filename, "\\");
1096 strcat (filename, "*");
1098 dir_find_handle = FindFirstFile (filename, &dir_find_data);
1100 if (dir_find_handle == INVALID_HANDLE_VALUE)
1105 if (!FindNextFile (dir_find_handle, &dir_find_data))
1109 /* Emacs never uses this value, so don't bother making it match
1110 value returned by stat(). */
1111 dir_static.d_ino = 1;
1113 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
1114 dir_static.d_namlen - dir_static.d_namlen % 4;
1116 dir_static.d_namlen = strlen (dir_find_data.cFileName);
1117 strcpy (dir_static.d_name, dir_find_data.cFileName);
1119 _strlwr (dir_static.d_name);
1120 else if (!NILP (Vmswindows_downcase_file_names))
1123 for (p = dir_static.d_name; *p; p++)
1124 if (*p >= 'a' && *p <= 'z')
1127 _strlwr (dir_static.d_name);
1134 /* #### Have to check if all that sad story about '95 is true - kkm */
1136 sys_rename (const char * oldname, const char * newname)
1138 char temp[MAX_PATH];
1141 /* MoveFile on Win95 doesn't correctly change the short file name
1142 alias in a number of circumstances (it is not easy to predict when
1143 just by looking at oldname and newname, unfortunately). In these
1144 cases, renaming through a temporary name avoids the problem.
1146 A second problem on Win95 is that renaming through a temp name when
1147 newname is uppercase fails (the final long name ends up in
1148 lowercase, although the short alias might be uppercase) UNLESS the
1149 long temp name is not 8.3.
1151 So, on Win95 we always rename through a temp name, and we make sure
1152 the temp name has a long extension to ensure correct renaming. */
1154 strcpy (temp, map_win32_filename (oldname, NULL));
1156 if (GetVersion () & 0x80000000)
1160 if (p = strrchr (temp, '\\'))
1164 /* Force temp name to require a manufactured 8.3 alias - this
1165 seems to make the second rename work properly. */
1166 strcpy (p, "_rename_temp.XXXXXX");
1168 if (rename (map_win32_filename (oldname, NULL), temp) < 0)
1172 /* Emulate Unix behavior - newname is deleted if it already exists
1173 (at least if it is a file; don't do this for directories).
1174 However, don't do this if we are just changing the case of the file
1175 name - we will end up deleting the file we are trying to rename! */
1176 newname = map_win32_filename (newname, NULL);
1178 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1179 do not refer to the same file, eg. through share aliases. */
1180 if (stricmp (newname, temp) != 0
1181 && (attr = GetFileAttributes (newname)) != -1
1182 && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
1184 _chmod (newname, 0666);
1188 return rename (temp, newname);
1192 static FILETIME utc_base_ft;
1193 static long double utc_base;
1194 static int init = 0;
1197 convert_time (FILETIME ft)
1203 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1212 st.wMilliseconds = 0;
1214 SystemTimeToFileTime (&st, &utc_base_ft);
1215 utc_base = (long double) utc_base_ft.dwHighDateTime
1216 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1220 if (CompareFileTime (&ft, &utc_base_ft) < 0)
1223 ret = (long double) ft.dwHighDateTime * 4096 * 1024 * 1024 + ft.dwLowDateTime;
1225 return (time_t) (ret * 1e-7);
1229 /* in case we ever have need of this */
1231 convert_from_time_t (time_t time, FILETIME * pft)
1237 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1246 st.wMilliseconds = 0;
1248 SystemTimeToFileTime (&st, &utc_base_ft);
1249 utc_base = (long double) utc_base_ft.dwHighDateTime
1250 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1254 /* time in 100ns units since 1-Jan-1601 */
1255 tmp = (long double) time * 1e7 + utc_base;
1256 pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
1257 pft->dwLowDateTime = (DWORD) (tmp - pft->dwHighDateTime);
1262 /* No reason to keep this; faking inode values either by hashing or even
1263 using the file index from GetInformationByHandle, is not perfect and
1264 so by default Emacs doesn't use the inode values on Windows.
1265 Instead, we now determine file-truename correctly (except for
1266 possible drive aliasing etc). */
1268 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1270 hashval (const unsigned char * str)
1275 h = (h << 4) + *str++;
1281 /* Return the hash value of the canonical pathname, excluding the
1282 drive/UNC header, to get a hopefully unique inode number. */
1284 generate_inode_val (const char * name)
1286 char fullname[ MAX_PATH ];
1290 /* Get the truly canonical filename, if it exists. (Note: this
1291 doesn't resolve aliasing due to subst commands, or recognize hard
1293 if (!win32_get_long_filename ((char *)name, fullname, MAX_PATH))
1296 parse_root (fullname, &p);
1297 /* Normal Win32 filesystems are still case insensitive. */
1304 /* MSVC stat function can't cope with UNC names and has other bugs, so
1305 replace it with our own. This also allows us to calculate consistent
1306 inode values without hacks in the main Emacs code. */
1308 stat (const char * path, struct stat * buf)
1311 WIN32_FIND_DATA wfd;
1316 int rootdir = FALSE;
1318 if (path == NULL || buf == NULL)
1324 name = (char *) map_win32_filename (path, &path);
1325 /* must be valid filename, no wild cards */
1326 if (strchr (name, '*') || strchr (name, '?'))
1332 /* Remove trailing directory separator, unless name is the root
1333 directory of a drive or UNC volume in which case ensure there
1334 is a trailing separator. */
1335 len = strlen (name);
1336 rootdir = (path >= name + len - 1
1337 && (IS_DIRECTORY_SEP (*path) || *path == 0));
1338 name = strcpy (alloca (len + 2), name);
1342 if (!IS_DIRECTORY_SEP (name[len-1]))
1343 strcat (name, "\\");
1344 if (GetDriveType (name) < 2)
1349 memset (&wfd, 0, sizeof (wfd));
1350 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1351 wfd.ftCreationTime = utc_base_ft;
1352 wfd.ftLastAccessTime = utc_base_ft;
1353 wfd.ftLastWriteTime = utc_base_ft;
1354 strcpy (wfd.cFileName, name);
1358 if (IS_DIRECTORY_SEP (name[len-1]))
1361 /* (This is hacky, but helps when doing file completions on
1362 network drives.) Optimize by using information available from
1363 active readdir if possible. */
1364 if (dir_find_handle != INVALID_HANDLE_VALUE &&
1365 (len = strlen (dir_pathname)),
1366 strnicmp (name, dir_pathname, len) == 0 &&
1367 IS_DIRECTORY_SEP (name[len]) &&
1368 stricmp (name + len + 1, dir_static.d_name) == 0)
1370 /* This was the last entry returned by readdir. */
1371 wfd = dir_find_data;
1375 fh = FindFirstFile (name, &wfd);
1376 if (fh == INVALID_HANDLE_VALUE)
1385 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1387 buf->st_mode = _S_IFDIR;
1388 buf->st_nlink = 2; /* doesn't really matter */
1389 fake_inode = 0; /* this doesn't either I think */
1391 else if (!NILP (Vmswindows_get_true_file_attributes))
1393 /* This is more accurate in terms of getting the correct number
1394 of links, but is quite slow (it is noticeable when Emacs is
1395 making a list of file name completions). */
1396 BY_HANDLE_FILE_INFORMATION info;
1398 /* No access rights required to get info. */
1399 fh = CreateFile (name, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1400 OPEN_EXISTING, 0, NULL);
1402 if (GetFileInformationByHandle (fh, &info))
1404 switch (GetFileType (fh))
1406 case FILE_TYPE_DISK:
1407 buf->st_mode = _S_IFREG;
1409 case FILE_TYPE_PIPE:
1410 buf->st_mode = _S_IFIFO;
1412 case FILE_TYPE_CHAR:
1413 case FILE_TYPE_UNKNOWN:
1415 buf->st_mode = _S_IFCHR;
1417 buf->st_nlink = (short) info.nNumberOfLinks;
1418 /* Might as well use file index to fake inode values, but this
1419 is not guaranteed to be unique unless we keep a handle open
1420 all the time (even then there are situations where it is
1421 not unique). Reputedly, there are at most 48 bits of info
1422 (on NTFS, presumably less on FAT). */
1423 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
1434 /* Don't bother to make this information more accurate. */
1435 buf->st_mode = _S_IFREG;
1441 /* Not sure if there is any point in this. */
1442 if (!NILP (Vwin32_generate_fake_inodes))
1443 fake_inode = generate_inode_val (name);
1444 else if (fake_inode == 0)
1446 /* For want of something better, try to make everything unique. */
1447 static DWORD gen_num = 0;
1448 fake_inode = ++gen_num;
1452 /* #### MSVC defines _ino_t to be short; other libc's might not. */
1453 buf->st_ino = (unsigned short) (fake_inode ^ (fake_inode >> 16));
1455 /* consider files to belong to current user */
1456 buf->st_uid = the_passwd.pw_uid;
1457 buf->st_gid = the_passwd.pw_gid;
1459 /* volume_info is set indirectly by map_win32_filename */
1460 buf->st_dev = volume_info.serialnum;
1461 buf->st_rdev = volume_info.serialnum;
1464 buf->st_size = wfd.nFileSizeLow;
1466 /* Convert timestamps to Unix format. */
1467 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
1468 buf->st_atime = convert_time (wfd.ftLastAccessTime);
1469 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
1470 buf->st_ctime = convert_time (wfd.ftCreationTime);
1471 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
1473 /* determine rwx permissions */
1474 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
1475 permission = _S_IREAD;
1477 permission = _S_IREAD | _S_IWRITE;
1479 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1480 permission |= _S_IEXEC;
1483 char * p = strrchr (name, '.');
1485 (stricmp (p, ".exe") == 0 ||
1486 stricmp (p, ".com") == 0 ||
1487 stricmp (p, ".bat") == 0 ||
1488 stricmp (p, ".cmd") == 0))
1489 permission |= _S_IEXEC;
1492 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
1497 /* From callproc.c */
1498 extern Lisp_Object Vbinary_process_input;
1499 extern Lisp_Object Vbinary_process_output;
1501 /* Unix pipe() has only one arg */
1503 sys_pipe (int * phandles)
1508 /* make pipe handles non-inheritable; when we spawn a child, we
1509 replace the relevant handle with an inheritable one. Also put
1510 pipes into binary mode; we will do text mode translation ourselves
1512 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
1516 flags = FILE_PIPE | FILE_READ;
1517 if (!NILP (Vbinary_process_output))
1518 flags |= FILE_BINARY;
1519 fd_info[phandles[0]].flags = flags;
1521 flags = FILE_PIPE | FILE_WRITE;
1522 if (!NILP (Vbinary_process_input))
1523 flags |= FILE_BINARY;
1524 fd_info[phandles[1]].flags = flags;
1531 extern Lisp_Object Vwin32_pipe_read_delay;
1533 /* Function to do blocking read of one byte, needed to implement
1534 select. It is only allowed on sockets and pipes. */
1536 _sys_read_ahead (int fd)
1541 if (fd < 0 || fd >= MAXDESC)
1542 return STATUS_READ_ERROR;
1544 cp = fd_info[fd].cp;
1546 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
1547 return STATUS_READ_ERROR;
1549 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
1550 || (fd_info[fd].flags & FILE_READ) == 0)
1552 /* fd is not a pipe or socket */
1556 cp->status = STATUS_READ_IN_PROGRESS;
1558 if (fd_info[fd].flags & FILE_PIPE)
1560 rc = _read (fd, &cp->chr, sizeof (char));
1562 /* Give subprocess time to buffer some more output for us before
1563 reporting that input is available; we need this because Win95
1564 connects DOS programs to pipes by making the pipe appear to be
1565 the normal console stdout - as a result most DOS programs will
1566 write to stdout without buffering, ie. one character at a
1567 time. Even some Win32 programs do this - "dir" in a command
1568 shell on NT is very slow if we don't do this. */
1571 int wait = XINT (Vwin32_pipe_read_delay);
1577 /* Yield remainder of our time slice, effectively giving a
1578 temporary priority boost to the child process. */
1583 if (rc == sizeof (char))
1584 cp->status = STATUS_READ_SUCCEEDED;
1586 cp->status = STATUS_READ_FAILED;
1592 term_ntproc (int unused)
1599 /* Initial preparation for subprocess support: replace our standard
1600 handles with non-inheritable versions. */
1603 HANDLE stdin_save = INVALID_HANDLE_VALUE;
1604 HANDLE stdout_save = INVALID_HANDLE_VALUE;
1605 HANDLE stderr_save = INVALID_HANDLE_VALUE;
1607 parent = GetCurrentProcess ();
1609 /* ignore errors when duplicating and closing; typically the
1610 handles will be invalid when running as a gui program. */
1611 DuplicateHandle (parent,
1612 GetStdHandle (STD_INPUT_HANDLE),
1617 DUPLICATE_SAME_ACCESS);
1619 DuplicateHandle (parent,
1620 GetStdHandle (STD_OUTPUT_HANDLE),
1625 DUPLICATE_SAME_ACCESS);
1627 DuplicateHandle (parent,
1628 GetStdHandle (STD_ERROR_HANDLE),
1633 DUPLICATE_SAME_ACCESS);
1639 if (stdin_save != INVALID_HANDLE_VALUE)
1640 _open_osfhandle ((long) stdin_save, O_TEXT);
1642 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
1645 if (stdout_save != INVALID_HANDLE_VALUE)
1646 _open_osfhandle ((long) stdout_save, O_TEXT);
1648 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
1651 if (stderr_save != INVALID_HANDLE_VALUE)
1652 _open_osfhandle ((long) stderr_save, O_TEXT);
1654 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
1658 /* unfortunately, atexit depends on implementation of malloc */
1659 /* atexit (term_ntproc); */
1660 signal (SIGABRT, term_ntproc);
1662 /* determine which drives are fixed, for GetCachedVolumeInformation */
1664 /* GetDriveType must have trailing backslash. */
1665 char drive[] = "A:\\";
1667 /* Loop over all possible drive letters */
1668 while ( *drive <= 'Z' )
1670 /* Record if this drive letter refers to a fixed drive. */
1671 fixed_drives[ DRIVE_INDEX (*drive) ] =
1672 (GetDriveType (drive) == DRIVE_FIXED);
1680 tty_semi_canonicalize_console_connection (Lisp_Object connection,
1681 Error_behavior errb)
1687 tty_canonicalize_console_connection (Lisp_Object connection,
1688 Error_behavior errb)
1694 tty_semi_canonicalize_device_connection (Lisp_Object connection,
1695 Error_behavior errb)
1701 tty_canonicalize_device_connection (Lisp_Object connection,
1702 Error_behavior errb)
1708 /*--------------------------------------------------------------------*/
1709 /* Signal support */
1710 /*--------------------------------------------------------------------*/
1712 /* We need MS-defined signal and raise here */
1716 #define sigmask(nsig) (1U << nsig)
1718 /* We can support as many signals as fit into word */
1721 /* Signal handlers. Initial value = 0 = SIG_DFL */
1722 static void (__cdecl *signal_handlers[SIG_MAX])(int) = {0};
1724 /* Signal block mask: bit set to 1 means blocked */
1725 unsigned signal_block_mask = 0;
1727 /* Signal pending mask: bit set to 1 means sig is pending */
1728 unsigned signal_pending_mask = 0;
1730 msw_sighandler msw_sigset (int nsig, msw_sighandler handler)
1732 /* We delegate some signals to the system function */
1733 if (nsig == SIGFPE || nsig == SIGABRT || nsig == SIGINT)
1734 return signal (nsig, handler);
1736 if (nsig < 0 || nsig > SIG_MAX)
1742 /* Store handler ptr */
1744 msw_sighandler old_handler = signal_handlers[nsig];
1745 signal_handlers[nsig] = handler;
1750 int msw_sighold (int nsig)
1752 if (nsig < 0 || nsig > SIG_MAX)
1753 return errno = EINVAL;
1755 signal_block_mask |= sigmask(nsig);
1759 int msw_sigrelse (int nsig)
1761 if (nsig < 0 || nsig > SIG_MAX)
1762 return errno = EINVAL;
1764 signal_block_mask &= ~sigmask(nsig);
1766 if (signal_pending_mask & sigmask(nsig))
1772 int msw_sigpause (int nsig)
1774 /* This is currently not called, because the only
1775 call to sigpause inside XEmacs is with SIGCHLD
1776 parameter. Just in case, we put an assert here,
1777 so anyone who will add a call to sigpause will
1778 be surprised (or surprise someone else...) */
1783 int msw_raise (int nsig)
1785 /* We delegate some raises to the system routine */
1786 if (nsig == SIGFPE || nsig == SIGABRT || nsig == SIGINT)
1787 return raise (nsig);
1789 if (nsig < 0 || nsig > SIG_MAX)
1790 return errno = EINVAL;
1792 /* If the signal is blocked, remember to issue later */
1793 if (signal_block_mask & sigmask(nsig))
1795 signal_pending_mask |= sigmask(nsig);
1799 if (signal_handlers[nsig] == SIG_IGN)
1802 if (signal_handlers[nsig] != SIG_DFL)
1804 (*signal_handlers[nsig])(nsig);
1808 /* Default signal actions */
1809 if (nsig == SIGALRM || nsig == SIGPROF)
1812 /* Other signals are ignored by default */
1815 /*--------------------------------------------------------------------*/
1817 /*--------------------------------------------------------------------*/
1819 /* We emulate two timers, one for SIGALRM, another for SIGPROF.
1821 itimerproc() function has an implementation limitation: it does
1822 not allow to set *both* interval and period. If an attempt is
1823 made to set both, and then they are unequal, the function
1826 Minimum timer resolution on Win32 systems varies, and is greater
1827 than or equal than 1 ms. The resolution is always wrapped not to
1828 attempt to get below the system defined limit.
1831 /* Timer precision, denominator of one fraction: for 100 ms
1832 interval, request 10 ms precision
1834 const int timer_prec = 10;
1836 /* Last itimervals, as set by calls to setitimer */
1837 static struct itimerval it_alarm;
1838 static struct itimerval it_prof;
1840 /* Timer IDs as returned by MM */
1841 MMRESULT tid_alarm = 0;
1842 MMRESULT tid_prof = 0;
1844 static void CALLBACK timer_proc (UINT uID, UINT uMsg, DWORD dwUser,
1845 DWORD dw1, DWORD dw2)
1847 /* Just raise a signal indicated by dwUser parameter */
1851 /* Divide time in ms specified by IT by DENOM. Return 1 ms
1852 if division results in zero */
1853 static UINT period (const struct itimerval* it, UINT denom)
1855 static TIMECAPS time_caps;
1858 const struct timeval* tv =
1859 (it->it_value.tv_sec == 0 && it->it_value.tv_usec == 0)
1860 ? &it->it_interval : &it->it_value;
1862 /* Zero means stop timer */
1863 if (tv->tv_sec == 0 && tv->tv_usec == 0)
1866 /* Convert to ms and divide by denom */
1867 res = (tv->tv_sec * 1000 + (tv->tv_usec + 500) / 1000) / denom;
1869 /* Converge to minimum timer resolution */
1870 if (time_caps.wPeriodMin == 0)
1871 timeGetDevCaps (&time_caps, sizeof(time_caps));
1873 if (res < time_caps.wPeriodMin)
1874 res = time_caps.wPeriodMin;
1879 static int setitimer_helper (const struct itimerval* itnew,
1880 struct itimerval* itold, struct itimerval* itcurrent,
1881 MMRESULT* tid, DWORD sigkind)
1883 UINT delay, resolution, event_type;
1885 /* First stop the old timer */
1888 timeKillEvent (*tid);
1889 timeEndPeriod (period (itcurrent, timer_prec));
1893 /* Return old itimerval if requested */
1895 *itold = *itcurrent;
1897 *itcurrent = *itnew;
1899 /* Determine if to start new timer */
1900 delay = period (itnew, 1);
1903 resolution = period (itnew, timer_prec);
1904 event_type = (itnew->it_value.tv_sec == 0 && itnew->it_value.tv_usec == 0)
1905 ? TIME_ONESHOT : TIME_PERIODIC;
1906 timeBeginPeriod (resolution);
1907 *tid = timeSetEvent (delay, resolution, timer_proc, sigkind, event_type);
1910 return !delay || *tid;
1913 int setitimer (int kind, const struct itimerval* itnew,
1914 struct itimerval* itold)
1916 /* In this version, both interval and value are allowed
1917 only if they are equal. */
1918 assert ((itnew->it_value.tv_sec == 0 && itnew->it_value.tv_usec == 0)
1919 || (itnew->it_interval.tv_sec == 0 && itnew->it_interval.tv_usec == 0)
1920 || (itnew->it_value.tv_sec == itnew->it_interval.tv_sec &&
1921 itnew->it_value.tv_usec == itnew->it_interval.tv_usec));
1923 if (kind == ITIMER_REAL)
1924 return setitimer_helper (itnew, itold, &it_alarm, &tid_alarm, SIGALRM);
1925 else if (kind == ITIMER_PROF)
1926 return setitimer_helper (itnew, itold, &it_prof, &tid_prof, SIGPROF);
1928 return errno = EINVAL;