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"
54 typedef void (CALLBACK TIMECALLBACK)(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);
56 typedef TIMECALLBACK FAR *LPTIMECALLBACK;
57 DWORD WINAPI timeGetTime(void);
58 MMRESULT WINAPI timeSetEvent(UINT uDelay, UINT uResolution,
59 LPTIMECALLBACK fptc, DWORD dwUser, UINT fuEvent);
60 MMRESULT WINAPI timeKillEvent(UINT uTimerID);
61 MMRESULT WINAPI timeGetDevCaps(TIMECAPS* ptc, UINT cbtc);
62 MMRESULT WINAPI timeBeginPeriod(UINT uPeriod);
63 MMRESULT WINAPI timeEndPeriod(UINT uPeriod);
71 extern Lisp_Object Vmswindows_downcase_file_names;
73 extern Lisp_Object Vwin32_generate_fake_inodes;
75 extern Lisp_Object Vmswindows_get_true_file_attributes;
77 extern char *get_home_directory(void);
79 static char startup_dir[ MAXPATHLEN ];
81 /* Get the current working directory. */
86 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
90 /* Emacs doesn't actually change directory itself, and we want to
91 force our real wd to be where emacs.exe is to avoid unnecessary
92 conflicts when trying to rename or delete directories. */
93 strcpy (dir, startup_dir);
98 /* Emulate getloadavg. */
100 getloadavg (double loadavg[], int nelem)
104 /* A faithful emulation is going to have to be saved for a rainy day. */
105 for (i = 0; i < nelem; i++)
112 /* Emulate getpwuid, getpwnam and others. */
114 #define PASSWD_FIELD_SIZE 256
116 static char the_passwd_name[PASSWD_FIELD_SIZE];
117 static char the_passwd_passwd[PASSWD_FIELD_SIZE];
118 static char the_passwd_gecos[PASSWD_FIELD_SIZE];
119 static char the_passwd_dir[PASSWD_FIELD_SIZE];
120 static char the_passwd_shell[PASSWD_FIELD_SIZE];
122 static struct passwd the_passwd =
137 return the_passwd.pw_uid;
143 /* I could imagine arguing for checking to see whether the user is
144 in the Administrators group and returning a UID of 0 for that
145 case, but I don't know how wise that would be in the long run. */
152 return the_passwd.pw_gid;
164 if (uid == the_passwd.pw_uid)
170 getpwnam (const char *name)
174 pw = getpwuid (getuid ());
178 if (stricmp (name, pw->pw_name))
187 /* Find the user's real name by opening the process token and
188 looking up the name associated with the user-sid in that token.
190 Use the relative portion of the identifier authority value from
191 the user-sid as the user id value (same for group id using the
192 primary group sid from the process token). */
194 char user_sid[256], name[256], domain[256];
195 DWORD length = sizeof (name), dlength = sizeof (domain), trash;
197 SID_NAME_USE user_type;
199 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
200 && GetTokenInformation (token, TokenUser,
201 (PVOID) user_sid, sizeof (user_sid), &trash)
202 && LookupAccountSid (NULL, *((PSID *) user_sid), name, &length,
203 domain, &dlength, &user_type))
205 strcpy (the_passwd.pw_name, name);
206 /* Determine a reasonable uid value. */
207 if (stricmp ("administrator", name) == 0)
209 the_passwd.pw_uid = 0;
210 the_passwd.pw_gid = 0;
214 SID_IDENTIFIER_AUTHORITY * pSIA;
216 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
217 /* I believe the relative portion is the last 4 bytes (of 6)
219 the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
220 (pSIA->Value[3] << 16) +
221 (pSIA->Value[4] << 8) +
222 (pSIA->Value[5] << 0));
223 /* restrict to conventional uid range for normal users */
224 the_passwd.pw_uid = the_passwd.pw_uid % 60001;
227 if (GetTokenInformation (token, TokenPrimaryGroup,
228 (PVOID) user_sid, sizeof (user_sid), &trash))
230 SID_IDENTIFIER_AUTHORITY * pSIA;
232 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
233 the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
234 (pSIA->Value[3] << 16) +
235 (pSIA->Value[4] << 8) +
236 (pSIA->Value[5] << 0));
237 /* I don't know if this is necessary, but for safety... */
238 the_passwd.pw_gid = the_passwd.pw_gid % 60001;
241 the_passwd.pw_gid = the_passwd.pw_uid;
244 /* If security calls are not supported (presumably because we
245 are running under Windows 95), fallback to this. */
246 else if (GetUserName (name, &length))
248 strcpy (the_passwd.pw_name, name);
249 if (stricmp ("administrator", name) == 0)
250 the_passwd.pw_uid = 0;
252 the_passwd.pw_uid = 123;
253 the_passwd.pw_gid = the_passwd.pw_uid;
257 strcpy (the_passwd.pw_name, "unknown");
258 the_passwd.pw_uid = 123;
259 the_passwd.pw_gid = 123;
262 /* Ensure HOME and SHELL are defined. */
265 * With XEmacs, setting $HOME is deprecated.
267 if (getenv ("HOME") == NULL)
270 if (getenv ("SHELL") == NULL)
271 putenv ((GetVersion () & 0x80000000) ? "SHELL=command" : "SHELL=cmd");
273 /* Set dir and shell from environment variables. */
274 strcpy (the_passwd.pw_dir, get_home_directory());
275 strcpy (the_passwd.pw_shell, getenv ("SHELL"));
281 /* Normalize filename by converting all path separators to
282 the specified separator. Also conditionally convert upper
283 case path name components to lower case. */
286 normalize_filename (fp, path_sep)
293 /* Always lower-case drive letters a-z, even if the filesystem
294 preserves case in filenames.
295 This is so filenames can be compared by string comparison
296 functions that are case-sensitive. Even case-preserving filesystems
297 do not distinguish case in drive letters. */
298 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
304 if (NILP (Vmswindows_downcase_file_names))
308 if (*fp == '/' || *fp == '\\')
315 sep = path_sep; /* convert to this path separator */
316 elem = fp; /* start of current path element */
319 if (*fp >= 'a' && *fp <= 'z')
320 elem = 0; /* don't convert this element */
322 if (*fp == 0 || *fp == ':')
324 sep = *fp; /* restore current separator (or 0) */
325 *fp = '/'; /* after conversion of this element */
328 if (*fp == '/' || *fp == '\\')
330 if (elem && elem != fp)
332 *fp = 0; /* temporary end of string */
333 _strlwr (elem); /* while we convert to lower case */
335 *fp = sep; /* convert (or restore) path separator */
336 elem = fp + 1; /* next element starts after separator */
342 /* Destructively turn backslashes into slashes. */
344 dostounix_filename (p)
347 normalize_filename (p, '/');
350 /* Destructively turn slashes into backslashes. */
352 unixtodos_filename (p)
355 normalize_filename (p, '\\');
358 /* Remove all CR's that are followed by a LF.
359 (From msdos.c...probably should figure out a way to share it,
360 although this code isn't going to ever change.) */
362 crlf_to_lf (n, buf, lf_count)
364 REGISTER unsigned char *buf;
365 REGISTER unsigned *lf_count;
367 unsigned char *np = buf;
368 unsigned char *startp = buf;
369 unsigned char *endp = buf + n;
373 while (buf < endp - 1)
379 if (*(++buf) != 0x0a)
394 /* Parse the root part of file name, if present. Return length and
395 optionally store pointer to char after root. */
397 parse_root (char * name, char ** pPath)
404 /* find the root name of the volume if given */
405 if (isalpha (name[0]) && name[1] == ':')
407 /* skip past drive specifier */
409 if (IS_DIRECTORY_SEP (name[0]))
412 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
418 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
423 if (IS_DIRECTORY_SEP (name[0]))
433 /* Get long base name for name; name is assumed to be absolute. */
435 get_long_basename (char * name, char * buf, int size)
437 WIN32_FIND_DATA find_data;
443 /* If the last component of NAME has a wildcard character,
444 return it as the basename. */
445 p = name + strlen (name);
446 while (*p != '\\' && *p != ':' && p > name) p--;
448 if (strchr (p, '*') || strchr (p, '?'))
450 if ((len = strlen (p)) < size)
451 memcpy (buf, p, len + 1);
458 dir_handle = FindFirstFile (name, &find_data);
459 if (dir_handle != INVALID_HANDLE_VALUE)
461 if ((len = strlen (find_data.cFileName)) < size)
462 memcpy (buf, find_data.cFileName, len + 1);
465 FindClose (dir_handle);
470 /* Get long name for file, if possible (assumed to be absolute). */
472 win32_get_long_filename (char * name, char * buf, int size)
477 char full[ MAX_PATH ];
484 /* Use local copy for destructive modification. */
485 memcpy (full, name, len+1);
486 unixtodos_filename (full);
488 /* Copy root part verbatim. */
489 len = parse_root (full, &p);
490 memcpy (o, full, len);
497 p = strchr (q, '\\');
499 len = get_long_basename (full, o, size);
517 while (p != NULL && *p);
523 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
525 #if 0 /* #### We do not need those, do we? -kkm */
527 unrequest_sigio (void)
539 #define REG_ROOT "SOFTWARE\\GNU\\XEmacs"
542 nt_get_resource (key, lpdwtype)
547 HKEY hrootkey = NULL;
550 /* Check both the current user and the local machine to see if
551 we have any resources. */
553 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
557 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
558 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
559 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
564 if (lpvalue) xfree (lpvalue);
566 RegCloseKey (hrootkey);
569 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
573 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS &&
574 (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL &&
575 RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
580 if (lpvalue) xfree (lpvalue);
582 RegCloseKey (hrootkey);
591 /* Check for environment variables and use registry if they don't exist */
597 static char * env_vars[] =
612 for (i = 0; i < countof (env_vars); i++)
614 if (!getenv (env_vars[i]) &&
615 (lpval = nt_get_resource (env_vars[i], &dwType)) != NULL)
617 if (dwType == REG_EXPAND_SZ)
619 char buf1[500], buf2[500];
621 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, 500);
622 _snprintf (buf2, 499, "%s=%s", env_vars[i], buf1);
623 putenv (strdup (buf2));
625 else if (dwType == REG_SZ)
629 _snprintf (buf, 499, "%s=%s", env_vars[i], lpval);
630 putenv (strdup (buf));
638 /* Another special case: on NT, the PATH variable is actually named
639 "Path" although cmd.exe (perhaps NT itself) arranges for
640 environment variable lookup and setting to be case insensitive.
641 However, Emacs assumes a fully case sensitive environment, so we
642 need to change "Path" to "PATH" to match the expectations of
643 various elisp packages. We do this by the sneaky method of
644 modifying the string in the C runtime environ entry.
646 The same applies to COMSPEC. */
650 for (envp = environ; *envp; envp++)
651 if (_strnicmp (*envp, "PATH=", 5) == 0)
652 memcpy (*envp, "PATH=", 5);
653 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
654 memcpy (*envp, "COMSPEC=", 8);
657 /* Remember the initial working directory for getwd, then make the
658 real wd be the location of emacs.exe to avoid conflicts when
659 renaming or deleting directories. (We also don't call chdir when
660 running subprocesses for the same reason.) */
661 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
666 char modname[MAX_PATH];
668 if (!GetModuleFileName (NULL, modname, MAX_PATH))
670 if ((p = strrchr (modname, '\\')) == NULL)
674 SetCurrentDirectory (modname);
680 #ifndef HAVE_X_WINDOWS
681 /* X11R6 on NT provides the single parameter version of this command. */
683 #include <sys/timeb.h>
685 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
687 gettimeofday (struct timeval *tv, struct timezone *tz)
692 tv->tv_sec = tb.time;
693 tv->tv_usec = tb.millitm * 1000L;
696 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
697 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
701 #endif /* HAVE_X_WINDOWS */
703 /* ------------------------------------------------------------------------- */
704 /* IO support and wrapper functions for Win32 API. */
705 /* ------------------------------------------------------------------------- */
707 /* Place a wrapper around the MSVC version of ctime. It returns NULL
708 on network directories, so we handle that case here.
709 (Ulrich Leodolter, 1/11/95). */
711 sys_ctime (const time_t *t)
713 char *str = (char *) ctime (t);
714 return (str ? str : "Sun Jan 01 00:00:00 1970");
717 /* Emulate sleep...we could have done this with a define, but that
718 would necessitate including windows.h in the files that used it.
719 This is much easier. */
721 #ifndef HAVE_X_WINDOWS
723 sys_sleep (int seconds)
725 Sleep (seconds * 1000);
729 /* #### This is an evil dirty hack. We must get rid of it.
730 Word "munging" is not in XEmacs lexicon. - kkm */
732 /* Internal MSVC data and functions for low-level descriptor munging */
733 #if (_MSC_VER == 900)
734 extern char _osfile[];
736 extern int __cdecl _set_osfhnd (int fd, long h);
737 extern int __cdecl _free_osfhnd (int fd);
739 /* parallel array of private info on file handles */
740 filedesc fd_info [ MAXDESC ];
742 typedef struct volume_info_data {
743 struct volume_info_data * next;
745 /* time when info was obtained */
748 /* actual volume info */
757 /* Global referenced by various functions. */
758 static volume_info_data volume_info;
760 /* Vector to indicate which drives are local and fixed (for which cached
761 data never expires). */
762 static BOOL fixed_drives[26];
764 /* Consider cached volume information to be stale if older than 10s,
765 at least for non-local drives. Info for fixed drives is never stale. */
766 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
767 #define VOLINFO_STILL_VALID( root_dir, info ) \
768 ( ( isalpha (root_dir[0]) && \
769 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
770 || GetTickCount () - info->timestamp < 10000 )
772 /* Cache support functions. */
774 /* Simple linked list with linear search is sufficient. */
775 static volume_info_data *volume_cache = NULL;
777 static volume_info_data *
778 lookup_volume_info (char * root_dir)
780 volume_info_data * info;
782 for (info = volume_cache; info; info = info->next)
783 if (stricmp (info->root_dir, root_dir) == 0)
789 add_volume_info (char * root_dir, volume_info_data * info)
791 info->root_dir = xstrdup (root_dir);
792 info->next = volume_cache;
797 /* Wrapper for GetVolumeInformation, which uses caching to avoid
798 performance penalty (~2ms on 486 for local drives, 7.5ms for local
799 cdrom drive, ~5-10ms or more for remote drives on LAN). */
801 GetCachedVolumeInformation (char * root_dir)
803 volume_info_data * info;
804 char default_root[ MAX_PATH ];
806 /* NULL for root_dir means use root from current directory. */
807 if (root_dir == NULL)
809 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
811 parse_root (default_root, &root_dir);
813 root_dir = default_root;
816 /* Local fixed drives can be cached permanently. Removable drives
817 cannot be cached permanently, since the volume name and serial
818 number (if nothing else) can change. Remote drives should be
819 treated as if they are removable, since there is no sure way to
820 tell whether they are or not. Also, the UNC association of drive
821 letters mapped to remote volumes can be changed at any time (even
822 by other processes) without notice.
824 As a compromise, so we can benefit from caching info for remote
825 volumes, we use a simple expiry mechanism to invalidate cache
826 entries that are more than ten seconds old. */
829 /* No point doing this, because WNetGetConnection is even slower than
830 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
831 GetDriveType is about the only call of this type which does not
832 involve network access, and so is extremely quick). */
834 /* Map drive letter to UNC if remote. */
835 if ( isalpha( root_dir[0] ) && !fixed[ DRIVE_INDEX( root_dir[0] ) ] )
837 char remote_name[ 256 ];
838 char drive[3] = { root_dir[0], ':' };
840 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
846 info = lookup_volume_info (root_dir);
848 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
856 /* Info is not cached, or is stale. */
857 if (!GetVolumeInformation (root_dir,
862 type, sizeof (type)))
865 /* Cache the volume information for future use, overwriting existing
869 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
870 add_volume_info (root_dir, info);
878 info->name = xstrdup (name);
879 info->serialnum = serialnum;
880 info->maxcomp = maxcomp;
882 info->type = xstrdup (type);
883 info->timestamp = GetTickCount ();
889 /* Get information on the volume where name is held; set path pointer to
890 start of pathname in name (past UNC header\volume header if present). */
892 get_volume_info (const char * name, const char ** pPath)
895 char *rootname = NULL; /* default to current volume */
896 volume_info_data * info;
901 /* find the root name of the volume if given */
902 if (isalpha (name[0]) && name[1] == ':')
910 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
917 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
930 info = GetCachedVolumeInformation (rootname);
933 /* Set global referenced by other functions. */
940 /* Determine if volume is FAT format (ie. only supports short 8.3
941 names); also set path pointer to start of pathname in name. */
943 is_fat_volume (const char * name, const char ** pPath)
945 if (get_volume_info (name, pPath))
946 return (volume_info.maxcomp == 12);
950 /* Map filename to a legal 8.3 name if necessary. */
952 map_win32_filename (const char * name, const char ** pPath)
954 static char shortname[MAX_PATH];
955 char * str = shortname;
958 const char * save_name = name;
960 if (is_fat_volume (name, &path)) /* truncate to 8.3 */
962 REGISTER int left = 8; /* maximum number of chars in part */
963 REGISTER int extn = 0; /* extension added? */
964 REGISTER int dots = 2; /* maximum number of dots allowed */
967 *str++ = *name++; /* skip past UNC header */
969 while ((c = *name++))
976 extn = 0; /* reset extension flags */
977 dots = 2; /* max 2 dots */
978 left = 8; /* max length 8 for main part */
982 extn = 0; /* reset extension flags */
983 dots = 2; /* max 2 dots */
984 left = 8; /* max length 8 for main part */
989 /* Convert path components of the form .xxx to _xxx,
990 but leave . and .. as they are. This allows .emacs
991 to be read as _emacs, for example. */
995 IS_DIRECTORY_SEP (*name))
1010 extn = 1; /* we've got an extension */
1011 left = 3; /* 3 chars in extension */
1015 /* any embedded dots after the first are converted to _ */
1020 case '#': /* don't lose these, they're important */
1022 str[-1] = c; /* replace last character of part */
1027 *str++ = tolower (c); /* map to lower case (looks nicer) */
1029 dots = 0; /* started a path component */
1038 strcpy (shortname, name);
1039 unixtodos_filename (shortname);
1043 *pPath = shortname + (path - save_name);
1049 /* Emulate the Unix directory procedures opendir, closedir,
1050 and readdir. We can't use the procedures supplied in sysdep.c,
1051 so we provide them here. */
1053 struct direct dir_static; /* simulated directory contents */
1054 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
1055 static int dir_is_fat;
1056 static char dir_pathname[MAXPATHLEN+1];
1057 static WIN32_FIND_DATA dir_find_data;
1060 opendir (const char *filename)
1064 /* Opening is done by FindFirstFile. However, a read is inherent to
1065 this operation, so we defer the open until read time. */
1067 if (!(dirp = xnew_and_zero(DIR)))
1069 if (dir_find_handle != INVALID_HANDLE_VALUE)
1076 strncpy (dir_pathname, map_win32_filename (filename, NULL), MAXPATHLEN);
1077 dir_pathname[MAXPATHLEN] = '\0';
1078 dir_is_fat = is_fat_volume (filename, NULL);
1084 closedir (DIR *dirp)
1086 /* If we have a find-handle open, close it. */
1087 if (dir_find_handle != INVALID_HANDLE_VALUE)
1089 FindClose (dir_find_handle);
1090 dir_find_handle = INVALID_HANDLE_VALUE;
1098 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1099 if (dir_find_handle == INVALID_HANDLE_VALUE)
1101 char filename[MAXNAMLEN + 3];
1104 strcpy (filename, dir_pathname);
1105 ln = strlen (filename) - 1;
1106 if (!IS_DIRECTORY_SEP (filename[ln]))
1107 strcat (filename, "\\");
1108 strcat (filename, "*");
1110 dir_find_handle = FindFirstFile (filename, &dir_find_data);
1112 if (dir_find_handle == INVALID_HANDLE_VALUE)
1117 if (!FindNextFile (dir_find_handle, &dir_find_data))
1121 /* Emacs never uses this value, so don't bother making it match
1122 value returned by stat(). */
1123 dir_static.d_ino = 1;
1125 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
1126 dir_static.d_namlen - dir_static.d_namlen % 4;
1128 dir_static.d_namlen = strlen (dir_find_data.cFileName);
1129 strcpy (dir_static.d_name, dir_find_data.cFileName);
1131 _strlwr (dir_static.d_name);
1132 else if (!NILP (Vmswindows_downcase_file_names))
1135 for (p = dir_static.d_name; *p; p++)
1136 if (*p >= 'a' && *p <= 'z')
1139 _strlwr (dir_static.d_name);
1146 /* #### Have to check if all that sad story about '95 is true - kkm */
1148 sys_rename (const char * oldname, const char * newname)
1150 char temp[MAX_PATH];
1153 /* MoveFile on Win95 doesn't correctly change the short file name
1154 alias in a number of circumstances (it is not easy to predict when
1155 just by looking at oldname and newname, unfortunately). In these
1156 cases, renaming through a temporary name avoids the problem.
1158 A second problem on Win95 is that renaming through a temp name when
1159 newname is uppercase fails (the final long name ends up in
1160 lowercase, although the short alias might be uppercase) UNLESS the
1161 long temp name is not 8.3.
1163 So, on Win95 we always rename through a temp name, and we make sure
1164 the temp name has a long extension to ensure correct renaming. */
1166 strcpy (temp, map_win32_filename (oldname, NULL));
1168 if (GetVersion () & 0x80000000)
1172 if (p = strrchr (temp, '\\'))
1176 /* Force temp name to require a manufactured 8.3 alias - this
1177 seems to make the second rename work properly. */
1178 strcpy (p, "_rename_temp.XXXXXX");
1180 if (rename (map_win32_filename (oldname, NULL), temp) < 0)
1184 /* Emulate Unix behavior - newname is deleted if it already exists
1185 (at least if it is a file; don't do this for directories).
1186 However, don't do this if we are just changing the case of the file
1187 name - we will end up deleting the file we are trying to rename! */
1188 newname = map_win32_filename (newname, NULL);
1190 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1191 do not refer to the same file, eg. through share aliases. */
1192 if (stricmp (newname, temp) != 0
1193 && (attr = GetFileAttributes (newname)) != -1
1194 && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
1196 _chmod (newname, 0666);
1200 return rename (temp, newname);
1204 static FILETIME utc_base_ft;
1205 static long double utc_base;
1206 static int init = 0;
1209 convert_time (FILETIME ft)
1215 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1224 st.wMilliseconds = 0;
1226 SystemTimeToFileTime (&st, &utc_base_ft);
1227 utc_base = (long double) utc_base_ft.dwHighDateTime
1228 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1232 if (CompareFileTime (&ft, &utc_base_ft) < 0)
1235 ret = (long double) ft.dwHighDateTime * 4096 * 1024 * 1024 + ft.dwLowDateTime;
1237 return (time_t) (ret * 1e-7);
1241 /* in case we ever have need of this */
1243 convert_from_time_t (time_t time, FILETIME * pft)
1249 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1258 st.wMilliseconds = 0;
1260 SystemTimeToFileTime (&st, &utc_base_ft);
1261 utc_base = (long double) utc_base_ft.dwHighDateTime
1262 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1266 /* time in 100ns units since 1-Jan-1601 */
1267 tmp = (long double) time * 1e7 + utc_base;
1268 pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
1269 pft->dwLowDateTime = (DWORD) (tmp - pft->dwHighDateTime);
1274 /* No reason to keep this; faking inode values either by hashing or even
1275 using the file index from GetInformationByHandle, is not perfect and
1276 so by default Emacs doesn't use the inode values on Windows.
1277 Instead, we now determine file-truename correctly (except for
1278 possible drive aliasing etc). */
1280 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1282 hashval (const unsigned char * str)
1287 h = (h << 4) + *str++;
1293 /* Return the hash value of the canonical pathname, excluding the
1294 drive/UNC header, to get a hopefully unique inode number. */
1296 generate_inode_val (const char * name)
1298 char fullname[ MAX_PATH ];
1302 /* Get the truly canonical filename, if it exists. (Note: this
1303 doesn't resolve aliasing due to subst commands, or recognize hard
1305 if (!win32_get_long_filename ((char *)name, fullname, MAX_PATH))
1308 parse_root (fullname, &p);
1309 /* Normal Win32 filesystems are still case insensitive. */
1316 /* MSVC stat function can't cope with UNC names and has other bugs, so
1317 replace it with our own. This also allows us to calculate consistent
1318 inode values without hacks in the main Emacs code. */
1320 stat (const char * path, struct stat * buf)
1323 WIN32_FIND_DATA wfd;
1328 int rootdir = FALSE;
1330 if (path == NULL || buf == NULL)
1336 name = (char *) map_win32_filename (path, &path);
1337 /* must be valid filename, no wild cards */
1338 if (strchr (name, '*') || strchr (name, '?'))
1344 /* Remove trailing directory separator, unless name is the root
1345 directory of a drive or UNC volume in which case ensure there
1346 is a trailing separator. */
1347 len = strlen (name);
1348 rootdir = (path >= name + len - 1
1349 && (IS_DIRECTORY_SEP (*path) || *path == 0));
1350 name = strcpy (alloca (len + 2), name);
1354 if (!IS_DIRECTORY_SEP (name[len-1]))
1355 strcat (name, "\\");
1356 if (GetDriveType (name) < 2)
1361 memset (&wfd, 0, sizeof (wfd));
1362 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1363 wfd.ftCreationTime = utc_base_ft;
1364 wfd.ftLastAccessTime = utc_base_ft;
1365 wfd.ftLastWriteTime = utc_base_ft;
1366 strcpy (wfd.cFileName, name);
1370 if (IS_DIRECTORY_SEP (name[len-1]))
1373 /* (This is hacky, but helps when doing file completions on
1374 network drives.) Optimize by using information available from
1375 active readdir if possible. */
1376 if (dir_find_handle != INVALID_HANDLE_VALUE &&
1377 (len = strlen (dir_pathname)),
1378 strnicmp (name, dir_pathname, len) == 0 &&
1379 IS_DIRECTORY_SEP (name[len]) &&
1380 stricmp (name + len + 1, dir_static.d_name) == 0)
1382 /* This was the last entry returned by readdir. */
1383 wfd = dir_find_data;
1387 fh = FindFirstFile (name, &wfd);
1388 if (fh == INVALID_HANDLE_VALUE)
1397 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1399 buf->st_mode = _S_IFDIR;
1400 buf->st_nlink = 2; /* doesn't really matter */
1401 fake_inode = 0; /* this doesn't either I think */
1403 else if (!NILP (Vmswindows_get_true_file_attributes))
1405 /* This is more accurate in terms of getting the correct number
1406 of links, but is quite slow (it is noticeable when Emacs is
1407 making a list of file name completions). */
1408 BY_HANDLE_FILE_INFORMATION info;
1410 /* No access rights required to get info. */
1411 fh = CreateFile (name, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1412 OPEN_EXISTING, 0, NULL);
1414 if (GetFileInformationByHandle (fh, &info))
1416 switch (GetFileType (fh))
1418 case FILE_TYPE_DISK:
1419 buf->st_mode = _S_IFREG;
1421 case FILE_TYPE_PIPE:
1422 buf->st_mode = _S_IFIFO;
1424 case FILE_TYPE_CHAR:
1425 case FILE_TYPE_UNKNOWN:
1427 buf->st_mode = _S_IFCHR;
1429 buf->st_nlink = (short) info.nNumberOfLinks;
1430 /* Might as well use file index to fake inode values, but this
1431 is not guaranteed to be unique unless we keep a handle open
1432 all the time (even then there are situations where it is
1433 not unique). Reputedly, there are at most 48 bits of info
1434 (on NTFS, presumably less on FAT). */
1435 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
1446 /* Don't bother to make this information more accurate. */
1447 buf->st_mode = _S_IFREG;
1453 /* Not sure if there is any point in this. */
1454 if (!NILP (Vwin32_generate_fake_inodes))
1455 fake_inode = generate_inode_val (name);
1456 else if (fake_inode == 0)
1458 /* For want of something better, try to make everything unique. */
1459 static DWORD gen_num = 0;
1460 fake_inode = ++gen_num;
1464 /* #### MSVC defines _ino_t to be short; other libc's might not. */
1465 buf->st_ino = (unsigned short) (fake_inode ^ (fake_inode >> 16));
1467 /* consider files to belong to current user */
1468 buf->st_uid = the_passwd.pw_uid;
1469 buf->st_gid = the_passwd.pw_gid;
1471 /* volume_info is set indirectly by map_win32_filename */
1472 buf->st_dev = volume_info.serialnum;
1473 buf->st_rdev = volume_info.serialnum;
1476 buf->st_size = wfd.nFileSizeLow;
1478 /* Convert timestamps to Unix format. */
1479 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
1480 buf->st_atime = convert_time (wfd.ftLastAccessTime);
1481 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
1482 buf->st_ctime = convert_time (wfd.ftCreationTime);
1483 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
1485 /* determine rwx permissions */
1486 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
1487 permission = _S_IREAD;
1489 permission = _S_IREAD | _S_IWRITE;
1491 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1492 permission |= _S_IEXEC;
1495 char * p = strrchr (name, '.');
1497 (stricmp (p, ".exe") == 0 ||
1498 stricmp (p, ".com") == 0 ||
1499 stricmp (p, ".bat") == 0 ||
1500 stricmp (p, ".cmd") == 0))
1501 permission |= _S_IEXEC;
1504 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
1509 /* From callproc.c */
1510 extern Lisp_Object Vbinary_process_input;
1511 extern Lisp_Object Vbinary_process_output;
1513 /* Unix pipe() has only one arg */
1515 sys_pipe (int * phandles)
1520 /* make pipe handles non-inheritable; when we spawn a child, we
1521 replace the relevant handle with an inheritable one. Also put
1522 pipes into binary mode; we will do text mode translation ourselves
1524 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
1528 flags = FILE_PIPE | FILE_READ;
1529 if (!NILP (Vbinary_process_output))
1530 flags |= FILE_BINARY;
1531 fd_info[phandles[0]].flags = flags;
1533 flags = FILE_PIPE | FILE_WRITE;
1534 if (!NILP (Vbinary_process_input))
1535 flags |= FILE_BINARY;
1536 fd_info[phandles[1]].flags = flags;
1543 term_ntproc (int unused)
1550 /* Initial preparation for subprocess support: replace our standard
1551 handles with non-inheritable versions. */
1554 HANDLE stdin_save = INVALID_HANDLE_VALUE;
1555 HANDLE stdout_save = INVALID_HANDLE_VALUE;
1556 HANDLE stderr_save = INVALID_HANDLE_VALUE;
1558 parent = GetCurrentProcess ();
1560 /* ignore errors when duplicating and closing; typically the
1561 handles will be invalid when running as a gui program. */
1562 DuplicateHandle (parent,
1563 GetStdHandle (STD_INPUT_HANDLE),
1568 DUPLICATE_SAME_ACCESS);
1570 DuplicateHandle (parent,
1571 GetStdHandle (STD_OUTPUT_HANDLE),
1576 DUPLICATE_SAME_ACCESS);
1578 DuplicateHandle (parent,
1579 GetStdHandle (STD_ERROR_HANDLE),
1584 DUPLICATE_SAME_ACCESS);
1590 if (stdin_save != INVALID_HANDLE_VALUE)
1591 _open_osfhandle ((long) stdin_save, O_TEXT);
1593 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
1596 if (stdout_save != INVALID_HANDLE_VALUE)
1597 _open_osfhandle ((long) stdout_save, O_TEXT);
1599 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
1602 if (stderr_save != INVALID_HANDLE_VALUE)
1603 _open_osfhandle ((long) stderr_save, O_TEXT);
1605 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
1609 /* unfortunately, atexit depends on implementation of malloc */
1610 /* atexit (term_ntproc); */
1611 signal (SIGABRT, term_ntproc);
1613 /* determine which drives are fixed, for GetCachedVolumeInformation */
1615 /* GetDriveType must have trailing backslash. */
1616 char drive[] = "A:\\";
1618 /* Loop over all possible drive letters */
1619 while ( *drive <= 'Z' )
1621 /* Record if this drive letter refers to a fixed drive. */
1622 fixed_drives[ DRIVE_INDEX (*drive) ] =
1623 (GetDriveType (drive) == DRIVE_FIXED);
1631 tty_semi_canonicalize_console_connection (Lisp_Object connection,
1632 Error_behavior errb)
1638 tty_canonicalize_console_connection (Lisp_Object connection,
1639 Error_behavior errb)
1645 tty_semi_canonicalize_device_connection (Lisp_Object connection,
1646 Error_behavior errb)
1652 tty_canonicalize_device_connection (Lisp_Object connection,
1653 Error_behavior errb)
1659 /*--------------------------------------------------------------------*/
1660 /* Signal support */
1661 /*--------------------------------------------------------------------*/
1663 /* We need MS-defined signal and raise here */
1667 #define sigmask(nsig) (1U << nsig)
1669 /* We can support as many signals as fit into word */
1672 /* Signal handlers. Initial value = 0 = SIG_DFL */
1673 static void (__cdecl *signal_handlers[SIG_MAX])(int) = {0};
1675 /* Signal block mask: bit set to 1 means blocked */
1676 unsigned signal_block_mask = 0;
1678 /* Signal pending mask: bit set to 1 means sig is pending */
1679 unsigned signal_pending_mask = 0;
1681 msw_sighandler msw_sigset (int nsig, msw_sighandler handler)
1683 /* We delegate some signals to the system function */
1684 if (nsig == SIGFPE || nsig == SIGABRT || nsig == SIGINT)
1685 return signal (nsig, handler);
1687 if (nsig < 0 || nsig > SIG_MAX)
1693 /* Store handler ptr */
1695 msw_sighandler old_handler = signal_handlers[nsig];
1696 signal_handlers[nsig] = handler;
1701 int msw_sighold (int nsig)
1703 if (nsig < 0 || nsig > SIG_MAX)
1704 return errno = EINVAL;
1706 signal_block_mask |= sigmask(nsig);
1710 int msw_sigrelse (int nsig)
1712 if (nsig < 0 || nsig > SIG_MAX)
1713 return errno = EINVAL;
1715 signal_block_mask &= ~sigmask(nsig);
1717 if (signal_pending_mask & sigmask(nsig))
1723 int msw_sigpause (int nsig)
1725 /* This is currently not called, because the only
1726 call to sigpause inside XEmacs is with SIGCHLD
1727 parameter. Just in case, we put an assert here,
1728 so anyone who will add a call to sigpause will
1729 be surprised (or surprise someone else...) */
1734 int msw_raise (int nsig)
1736 /* We delegate some raises to the system routine */
1737 if (nsig == SIGFPE || nsig == SIGABRT || nsig == SIGINT)
1738 return raise (nsig);
1740 if (nsig < 0 || nsig > SIG_MAX)
1741 return errno = EINVAL;
1743 /* If the signal is blocked, remember to issue later */
1744 if (signal_block_mask & sigmask(nsig))
1746 signal_pending_mask |= sigmask(nsig);
1750 if (signal_handlers[nsig] == SIG_IGN)
1753 if (signal_handlers[nsig] != SIG_DFL)
1755 (*signal_handlers[nsig])(nsig);
1759 /* Default signal actions */
1760 if (nsig == SIGALRM || nsig == SIGPROF)
1763 /* Other signals are ignored by default */
1767 /*--------------------------------------------------------------------*/
1769 /*--------------------------------------------------------------------*/
1771 /* We emulate two timers, one for SIGALRM, another for SIGPROF.
1773 itimerproc() function has an implementation limitation: it does
1774 not allow to set *both* interval and period. If an attempt is
1775 made to set both, and then they are unequal, the function
1778 Minimum timer resolution on Win32 systems varies, and is greater
1779 than or equal than 1 ms. The resolution is always wrapped not to
1780 attempt to get below the system defined limit.
1783 /* Timer precision, denominator of one fraction: for 100 ms
1784 interval, request 10 ms precision
1786 const int timer_prec = 10;
1788 /* Last itimervals, as set by calls to setitimer */
1789 static struct itimerval it_alarm;
1790 static struct itimerval it_prof;
1792 /* Timer IDs as returned by MM */
1793 MMRESULT tid_alarm = 0;
1794 MMRESULT tid_prof = 0;
1796 static void CALLBACK timer_proc (UINT uID, UINT uMsg, DWORD dwUser,
1797 DWORD dw1, DWORD dw2)
1799 /* Just raise a signal indicated by dwUser parameter */
1803 /* Divide time in ms specified by IT by DENOM. Return 1 ms
1804 if division results in zero */
1805 static UINT period (const struct itimerval* it, UINT denom)
1807 static TIMECAPS time_caps;
1810 const struct timeval* tv =
1811 (it->it_value.tv_sec == 0 && it->it_value.tv_usec == 0)
1812 ? &it->it_interval : &it->it_value;
1814 /* Zero means stop timer */
1815 if (tv->tv_sec == 0 && tv->tv_usec == 0)
1818 /* Convert to ms and divide by denom */
1819 res = (tv->tv_sec * 1000 + (tv->tv_usec + 500) / 1000) / denom;
1821 /* Converge to minimum timer resolution */
1822 if (time_caps.wPeriodMin == 0)
1823 timeGetDevCaps (&time_caps, sizeof(time_caps));
1825 if (res < time_caps.wPeriodMin)
1826 res = time_caps.wPeriodMin;
1831 static int setitimer_helper (const struct itimerval* itnew,
1832 struct itimerval* itold, struct itimerval* itcurrent,
1833 MMRESULT* tid, DWORD sigkind)
1835 UINT delay, resolution, event_type;
1837 /* First stop the old timer */
1840 timeKillEvent (*tid);
1841 timeEndPeriod (period (itcurrent, timer_prec));
1845 /* Return old itimerval if requested */
1847 *itold = *itcurrent;
1849 *itcurrent = *itnew;
1851 /* Determine if to start new timer */
1852 delay = period (itnew, 1);
1855 resolution = period (itnew, timer_prec);
1856 event_type = (itnew->it_value.tv_sec == 0 && itnew->it_value.tv_usec == 0)
1857 ? TIME_ONESHOT : TIME_PERIODIC;
1858 timeBeginPeriod (resolution);
1859 *tid = timeSetEvent (delay, resolution, timer_proc, sigkind, event_type);
1862 return !delay || *tid;
1865 int setitimer (int kind, const struct itimerval* itnew,
1866 struct itimerval* itold)
1868 /* In this version, both interval and value are allowed
1869 only if they are equal. */
1870 assert ((itnew->it_value.tv_sec == 0 && itnew->it_value.tv_usec == 0)
1871 || (itnew->it_interval.tv_sec == 0 && itnew->it_interval.tv_usec == 0)
1872 || (itnew->it_value.tv_sec == itnew->it_interval.tv_sec &&
1873 itnew->it_value.tv_usec == itnew->it_interval.tv_usec));
1875 if (kind == ITIMER_REAL)
1876 return setitimer_helper (itnew, itold, &it_alarm, &tid_alarm, SIGALRM);
1877 else if (kind == ITIMER_PROF)
1878 return setitimer_helper (itnew, itold, &it_prof, &tid_prof, SIGPROF);
1880 return errno = EINVAL;
1884 open_input_file (file_data *p_file, CONST char *filename)
1887 HANDLE file_mapping;
1889 DWORD size, upper_size;
1891 file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1892 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
1893 if (file == INVALID_HANDLE_VALUE)
1896 size = GetFileSize (file, &upper_size);
1897 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
1902 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
1906 p_file->name = (char*)filename;
1907 p_file->size = size;
1908 p_file->file = file;
1909 p_file->file_mapping = file_mapping;
1910 p_file->file_base = file_base;
1915 /* Close the system structures associated with the given file. */
1917 close_file_data (file_data *p_file)
1919 UnmapViewOfFile (p_file->file_base);
1920 CloseHandle (p_file->file_mapping);
1921 CloseHandle (p_file->file);