(event_kind): New event type `drag_n_drop'.
[emacs.git] / src / w32.c
blob42027ae20520fd8a56b841ce0e49c719a35eed25
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)
9 any later version.
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 */
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <io.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <ctype.h>
32 #include <signal.h>
33 #include <sys/time.h>
34 #include <sys/utime.h>
36 /* must include CRT headers *before* config.h */
37 #include "config.h"
38 #undef access
39 #undef chdir
40 #undef chmod
41 #undef creat
42 #undef ctime
43 #undef fopen
44 #undef link
45 #undef mkdir
46 #undef mktemp
47 #undef open
48 #undef rename
49 #undef rmdir
50 #undef unlink
52 #undef close
53 #undef dup
54 #undef dup2
55 #undef pipe
56 #undef read
57 #undef write
59 #include "lisp.h"
61 #include <pwd.h>
63 #include <windows.h>
65 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
66 #include <sys/socket.h>
67 #undef socket
68 #undef bind
69 #undef connect
70 #undef htons
71 #undef ntohs
72 #undef inet_addr
73 #undef gethostname
74 #undef gethostbyname
75 #undef getservbyname
76 #undef shutdown
77 #endif
79 #include "w32.h"
80 #include "ndir.h"
81 #include "w32heap.h"
83 #undef min
84 #undef max
85 #define min(x, y) (((x) < (y)) ? (x) : (y))
86 #define max(x, y) (((x) > (y)) ? (x) : (y))
88 extern Lisp_Object Vw32_downcase_file_names;
89 extern Lisp_Object Vw32_generate_fake_inodes;
90 extern Lisp_Object Vw32_get_true_file_attributes;
92 static char startup_dir[MAXPATHLEN];
94 /* Get the current working directory. */
95 char *
96 getwd (char *dir)
98 #if 0
99 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
100 return dir;
101 return NULL;
102 #else
103 /* Emacs doesn't actually change directory itself, and we want to
104 force our real wd to be where emacs.exe is to avoid unnecessary
105 conflicts when trying to rename or delete directories. */
106 strcpy (dir, startup_dir);
107 return dir;
108 #endif
111 #ifndef HAVE_SOCKETS
112 /* Emulate gethostname. */
114 gethostname (char *buffer, int size)
116 /* NT only allows small host names, so the buffer is
117 certainly large enough. */
118 return !GetComputerName (buffer, &size);
120 #endif /* HAVE_SOCKETS */
122 /* Emulate getloadavg. */
124 getloadavg (double loadavg[], int nelem)
126 int i;
128 /* A faithful emulation is going to have to be saved for a rainy day. */
129 for (i = 0; i < nelem; i++)
131 loadavg[i] = 0.0;
133 return i;
136 /* Emulate getpwuid, getpwnam and others. */
138 #define PASSWD_FIELD_SIZE 256
140 static char the_passwd_name[PASSWD_FIELD_SIZE];
141 static char the_passwd_passwd[PASSWD_FIELD_SIZE];
142 static char the_passwd_gecos[PASSWD_FIELD_SIZE];
143 static char the_passwd_dir[PASSWD_FIELD_SIZE];
144 static char the_passwd_shell[PASSWD_FIELD_SIZE];
146 static struct passwd the_passwd =
148 the_passwd_name,
149 the_passwd_passwd,
153 the_passwd_gecos,
154 the_passwd_dir,
155 the_passwd_shell,
158 int
159 getuid ()
161 return the_passwd.pw_uid;
164 int
165 geteuid ()
167 /* I could imagine arguing for checking to see whether the user is
168 in the Administrators group and returning a UID of 0 for that
169 case, but I don't know how wise that would be in the long run. */
170 return getuid ();
173 int
174 getgid ()
176 return the_passwd.pw_gid;
179 int
180 getegid ()
182 return getgid ();
185 struct passwd *
186 getpwuid (int uid)
188 if (uid == the_passwd.pw_uid)
189 return &the_passwd;
190 return NULL;
193 struct passwd *
194 getpwnam (char *name)
196 struct passwd *pw;
198 pw = getpwuid (getuid ());
199 if (!pw)
200 return pw;
202 if (stricmp (name, pw->pw_name))
203 return NULL;
205 return pw;
208 void
209 init_user_info ()
211 /* Find the user's real name by opening the process token and
212 looking up the name associated with the user-sid in that token.
214 Use the relative portion of the identifier authority value from
215 the user-sid as the user id value (same for group id using the
216 primary group sid from the process token). */
218 char user_sid[256], name[256], domain[256];
219 DWORD length = sizeof (name), dlength = sizeof (domain), trash;
220 HANDLE token = NULL;
221 SID_NAME_USE user_type;
223 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
224 && GetTokenInformation (token, TokenUser,
225 (PVOID) user_sid, sizeof (user_sid), &trash)
226 && LookupAccountSid (NULL, *((PSID *) user_sid), name, &length,
227 domain, &dlength, &user_type))
229 strcpy (the_passwd.pw_name, name);
230 /* Determine a reasonable uid value. */
231 if (stricmp ("administrator", name) == 0)
233 the_passwd.pw_uid = 0;
234 the_passwd.pw_gid = 0;
236 else
238 SID_IDENTIFIER_AUTHORITY * pSIA;
240 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
241 /* I believe the relative portion is the last 4 bytes (of 6)
242 with msb first. */
243 the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
244 (pSIA->Value[3] << 16) +
245 (pSIA->Value[4] << 8) +
246 (pSIA->Value[5] << 0));
247 /* restrict to conventional uid range for normal users */
248 the_passwd.pw_uid = the_passwd.pw_uid % 60001;
250 /* Get group id */
251 if (GetTokenInformation (token, TokenPrimaryGroup,
252 (PVOID) user_sid, sizeof (user_sid), &trash))
254 SID_IDENTIFIER_AUTHORITY * pSIA;
256 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
257 the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
258 (pSIA->Value[3] << 16) +
259 (pSIA->Value[4] << 8) +
260 (pSIA->Value[5] << 0));
261 /* I don't know if this is necessary, but for safety... */
262 the_passwd.pw_gid = the_passwd.pw_gid % 60001;
264 else
265 the_passwd.pw_gid = the_passwd.pw_uid;
268 /* If security calls are not supported (presumably because we
269 are running under Windows 95), fallback to this. */
270 else if (GetUserName (name, &length))
272 strcpy (the_passwd.pw_name, name);
273 if (stricmp ("administrator", name) == 0)
274 the_passwd.pw_uid = 0;
275 else
276 the_passwd.pw_uid = 123;
277 the_passwd.pw_gid = the_passwd.pw_uid;
279 else
281 strcpy (the_passwd.pw_name, "unknown");
282 the_passwd.pw_uid = 123;
283 the_passwd.pw_gid = 123;
286 /* Ensure HOME and SHELL are defined. */
287 if (getenv ("HOME") == NULL)
288 putenv ("HOME=c:/");
289 if (getenv ("SHELL") == NULL)
290 putenv (os_subtype == OS_WIN95 ? "SHELL=command" : "SHELL=cmd");
292 /* Set dir and shell from environment variables. */
293 strcpy (the_passwd.pw_dir, getenv ("HOME"));
294 strcpy (the_passwd.pw_shell, getenv ("SHELL"));
296 if (token)
297 CloseHandle (token);
301 random ()
303 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
304 return ((rand () << 15) | rand ());
307 void
308 srandom (int seed)
310 srand (seed);
314 /* Normalize filename by converting all path separators to
315 the specified separator. Also conditionally convert upper
316 case path name components to lower case. */
318 static void
319 normalize_filename (fp, path_sep)
320 register char *fp;
321 char path_sep;
323 char sep;
324 char *elem;
326 /* Always lower-case drive letters a-z, even if the filesystem
327 preserves case in filenames.
328 This is so filenames can be compared by string comparison
329 functions that are case-sensitive. Even case-preserving filesystems
330 do not distinguish case in drive letters. */
331 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
333 *fp += 'a' - 'A';
334 fp += 2;
337 if (NILP (Vw32_downcase_file_names))
339 while (*fp)
341 if (*fp == '/' || *fp == '\\')
342 *fp = path_sep;
343 fp++;
345 return;
348 sep = path_sep; /* convert to this path separator */
349 elem = fp; /* start of current path element */
351 do {
352 if (*fp >= 'a' && *fp <= 'z')
353 elem = 0; /* don't convert this element */
355 if (*fp == 0 || *fp == ':')
357 sep = *fp; /* restore current separator (or 0) */
358 *fp = '/'; /* after conversion of this element */
361 if (*fp == '/' || *fp == '\\')
363 if (elem && elem != fp)
365 *fp = 0; /* temporary end of string */
366 _strlwr (elem); /* while we convert to lower case */
368 *fp = sep; /* convert (or restore) path separator */
369 elem = fp + 1; /* next element starts after separator */
370 sep = path_sep;
372 } while (*fp++);
375 /* Destructively turn backslashes into slashes. */
376 void
377 dostounix_filename (p)
378 register char *p;
380 normalize_filename (p, '/');
383 /* Destructively turn slashes into backslashes. */
384 void
385 unixtodos_filename (p)
386 register char *p;
388 normalize_filename (p, '\\');
391 /* Remove all CR's that are followed by a LF.
392 (From msdos.c...probably should figure out a way to share it,
393 although this code isn't going to ever change.) */
395 crlf_to_lf (n, buf)
396 register int n;
397 register unsigned char *buf;
399 unsigned char *np = buf;
400 unsigned char *startp = buf;
401 unsigned char *endp = buf + n;
403 if (n == 0)
404 return n;
405 while (buf < endp - 1)
407 if (*buf == 0x0d)
409 if (*(++buf) != 0x0a)
410 *np++ = 0x0d;
412 else
413 *np++ = *buf++;
415 if (buf < endp)
416 *np++ = *buf++;
417 return np - startp;
420 /* Parse the root part of file name, if present. Return length and
421 optionally store pointer to char after root. */
422 static int
423 parse_root (char * name, char ** pPath)
425 char * start = name;
427 if (name == NULL)
428 return 0;
430 /* find the root name of the volume if given */
431 if (isalpha (name[0]) && name[1] == ':')
433 /* skip past drive specifier */
434 name += 2;
435 if (IS_DIRECTORY_SEP (name[0]))
436 name++;
438 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
440 int slashes = 2;
441 name += 2;
444 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
445 break;
446 name++;
448 while ( *name );
449 if (IS_DIRECTORY_SEP (name[0]))
450 name++;
453 if (pPath)
454 *pPath = name;
456 return name - start;
459 /* Get long base name for name; name is assumed to be absolute. */
460 static int
461 get_long_basename (char * name, char * buf, int size)
463 WIN32_FIND_DATA find_data;
464 HANDLE dir_handle;
465 int len = 0;
467 dir_handle = FindFirstFile (name, &find_data);
468 if (dir_handle != INVALID_HANDLE_VALUE)
470 if ((len = strlen (find_data.cFileName)) < size)
471 memcpy (buf, find_data.cFileName, len + 1);
472 else
473 len = 0;
474 FindClose (dir_handle);
476 return len;
479 /* Get long name for file, if possible (assumed to be absolute). */
480 BOOL
481 w32_get_long_filename (char * name, char * buf, int size)
483 char * o = buf;
484 char * p;
485 char * q;
486 char full[ MAX_PATH ];
487 int len;
489 len = strlen (name);
490 if (len >= MAX_PATH)
491 return FALSE;
493 /* Use local copy for destructive modification. */
494 memcpy (full, name, len+1);
495 unixtodos_filename (full);
497 /* Copy root part verbatim. */
498 len = parse_root (full, &p);
499 memcpy (o, full, len);
500 o += len;
501 size -= len;
505 q = p;
506 p = strchr (q, '\\');
507 if (p) *p = '\0';
508 len = get_long_basename (full, o, size);
509 if (len > 0)
511 o += len;
512 size -= len;
513 if (p != NULL)
515 *p++ = '\\';
516 if (size < 2)
517 return FALSE;
518 *o++ = '\\';
519 size--;
520 *o = '\0';
523 else
524 return FALSE;
526 while (p != NULL && *p);
528 return TRUE;
532 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
534 int
535 sigsetmask (int signal_mask)
537 return 0;
540 int
541 sigblock (int sig)
543 return 0;
546 int
547 setpgrp (int pid, int gid)
549 return 0;
552 int
553 alarm (int seconds)
555 return 0;
558 void
559 unrequest_sigio (void)
561 return;
564 void
565 request_sigio (void)
567 return;
570 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
572 LPBYTE
573 w32_get_resource (key, lpdwtype)
574 char *key;
575 LPDWORD lpdwtype;
577 LPBYTE lpvalue;
578 HKEY hrootkey = NULL;
579 DWORD cbData;
580 BOOL ok = FALSE;
582 /* Check both the current user and the local machine to see if
583 we have any resources. */
585 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
587 lpvalue = NULL;
589 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
590 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
591 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
593 return (lpvalue);
596 if (lpvalue) xfree (lpvalue);
598 RegCloseKey (hrootkey);
601 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
603 lpvalue = NULL;
605 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
606 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
607 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
609 return (lpvalue);
612 if (lpvalue) xfree (lpvalue);
614 RegCloseKey (hrootkey);
617 return (NULL);
620 char *get_emacs_configuration (void);
621 extern Lisp_Object Vsystem_configuration;
623 void
624 init_environment ()
626 /* Check for environment variables and use registry if they don't exist */
628 int i;
629 LPBYTE lpval;
630 DWORD dwType;
632 static char * env_vars[] =
634 "HOME",
635 "PRELOAD_WINSOCK",
636 "emacs_dir",
637 "EMACSLOADPATH",
638 "SHELL",
639 "CMDPROXY",
640 "EMACSDATA",
641 "EMACSPATH",
642 "EMACSLOCKDIR",
643 /* We no longer set INFOPATH because Info-default-directory-list
644 is then ignored. We use a hook in winnt.el instead. */
645 /* "INFOPATH", */
646 "EMACSDOC",
647 "TERM",
650 for (i = 0; i < (sizeof (env_vars) / sizeof (env_vars[0])); i++)
652 if (!getenv (env_vars[i])
653 && (lpval = w32_get_resource (env_vars[i], &dwType)) != NULL)
655 if (dwType == REG_EXPAND_SZ)
657 char buf1[500], buf2[500];
659 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, 500);
660 _snprintf (buf2, 499, "%s=%s", env_vars[i], buf1);
661 putenv (strdup (buf2));
663 else if (dwType == REG_SZ)
665 char buf[500];
667 _snprintf (buf, 499, "%s=%s", env_vars[i], lpval);
668 putenv (strdup (buf));
671 xfree (lpval);
676 /* Rebuild system configuration to reflect invoking system. */
677 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
679 /* Another special case: on NT, the PATH variable is actually named
680 "Path" although cmd.exe (perhaps NT itself) arranges for
681 environment variable lookup and setting to be case insensitive.
682 However, Emacs assumes a fully case sensitive environment, so we
683 need to change "Path" to "PATH" to match the expectations of
684 various elisp packages. We do this by the sneaky method of
685 modifying the string in the C runtime environ entry.
687 The same applies to COMSPEC. */
689 char ** envp;
691 for (envp = environ; *envp; envp++)
692 if (_strnicmp (*envp, "PATH=", 5) == 0)
693 memcpy (*envp, "PATH=", 5);
694 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
695 memcpy (*envp, "COMSPEC=", 8);
698 /* Remember the initial working directory for getwd, then make the
699 real wd be the location of emacs.exe to avoid conflicts when
700 renaming or deleting directories. (We also don't call chdir when
701 running subprocesses for the same reason.) */
702 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
703 abort ();
706 char *p;
707 char modname[MAX_PATH];
709 if (!GetModuleFileName (NULL, modname, MAX_PATH))
710 abort ();
711 if ((p = strrchr (modname, '\\')) == NULL)
712 abort ();
713 *p = 0;
715 SetCurrentDirectory (modname);
718 init_user_info ();
721 /* We don't have scripts to automatically determine the system configuration
722 for Emacs before it's compiled, and we don't want to have to make the
723 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
724 routine. */
726 static char configuration_buffer[32];
728 char *
729 get_emacs_configuration (void)
731 char *arch, *oem, *os;
733 /* Determine the processor type. */
734 switch (get_processor_type ())
737 #ifdef PROCESSOR_INTEL_386
738 case PROCESSOR_INTEL_386:
739 case PROCESSOR_INTEL_486:
740 case PROCESSOR_INTEL_PENTIUM:
741 arch = "i386";
742 break;
743 #endif
745 #ifdef PROCESSOR_INTEL_860
746 case PROCESSOR_INTEL_860:
747 arch = "i860";
748 break;
749 #endif
751 #ifdef PROCESSOR_MIPS_R2000
752 case PROCESSOR_MIPS_R2000:
753 case PROCESSOR_MIPS_R3000:
754 case PROCESSOR_MIPS_R4000:
755 arch = "mips";
756 break;
757 #endif
759 #ifdef PROCESSOR_ALPHA_21064
760 case PROCESSOR_ALPHA_21064:
761 arch = "alpha";
762 break;
763 #endif
765 default:
766 arch = "unknown";
767 break;
770 /* Let oem be "*" until we figure out how to decode the OEM field. */
771 oem = "*";
773 os = (GetVersion () & OS_WIN95) ? "windows95" : "nt";
775 sprintf (configuration_buffer, "%s-%s-%s%d.%d", arch, oem, os,
776 get_w32_major_version (), get_w32_minor_version ());
777 return configuration_buffer;
780 #include <sys/timeb.h>
782 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
783 void
784 gettimeofday (struct timeval *tv, struct timezone *tz)
786 struct _timeb tb;
787 _ftime (&tb);
789 tv->tv_sec = tb.time;
790 tv->tv_usec = tb.millitm * 1000L;
791 if (tz)
793 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
794 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
798 /* ------------------------------------------------------------------------- */
799 /* IO support and wrapper functions for W32 API. */
800 /* ------------------------------------------------------------------------- */
802 /* Place a wrapper around the MSVC version of ctime. It returns NULL
803 on network directories, so we handle that case here.
804 (Ulrich Leodolter, 1/11/95). */
805 char *
806 sys_ctime (const time_t *t)
808 char *str = (char *) ctime (t);
809 return (str ? str : "Sun Jan 01 00:00:00 1970");
812 /* Emulate sleep...we could have done this with a define, but that
813 would necessitate including windows.h in the files that used it.
814 This is much easier. */
815 void
816 sys_sleep (int seconds)
818 Sleep (seconds * 1000);
821 /* Internal MSVC functions for low-level descriptor munging */
822 extern int __cdecl _set_osfhnd (int fd, long h);
823 extern int __cdecl _free_osfhnd (int fd);
825 /* parallel array of private info on file handles */
826 filedesc fd_info [ MAXDESC ];
828 typedef struct volume_info_data {
829 struct volume_info_data * next;
831 /* time when info was obtained */
832 DWORD timestamp;
834 /* actual volume info */
835 char * root_dir;
836 DWORD serialnum;
837 DWORD maxcomp;
838 DWORD flags;
839 char * name;
840 char * type;
841 } volume_info_data;
843 /* Global referenced by various functions. */
844 static volume_info_data volume_info;
846 /* Vector to indicate which drives are local and fixed (for which cached
847 data never expires). */
848 static BOOL fixed_drives[26];
850 /* Consider cached volume information to be stale if older than 10s,
851 at least for non-local drives. Info for fixed drives is never stale. */
852 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
853 #define VOLINFO_STILL_VALID( root_dir, info ) \
854 ( ( isalpha (root_dir[0]) && \
855 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
856 || GetTickCount () - info->timestamp < 10000 )
858 /* Cache support functions. */
860 /* Simple linked list with linear search is sufficient. */
861 static volume_info_data *volume_cache = NULL;
863 static volume_info_data *
864 lookup_volume_info (char * root_dir)
866 volume_info_data * info;
868 for (info = volume_cache; info; info = info->next)
869 if (stricmp (info->root_dir, root_dir) == 0)
870 break;
871 return info;
874 static void
875 add_volume_info (char * root_dir, volume_info_data * info)
877 info->root_dir = strdup (root_dir);
878 info->next = volume_cache;
879 volume_cache = info;
883 /* Wrapper for GetVolumeInformation, which uses caching to avoid
884 performance penalty (~2ms on 486 for local drives, 7.5ms for local
885 cdrom drive, ~5-10ms or more for remote drives on LAN). */
886 volume_info_data *
887 GetCachedVolumeInformation (char * root_dir)
889 volume_info_data * info;
890 char default_root[ MAX_PATH ];
892 /* NULL for root_dir means use root from current directory. */
893 if (root_dir == NULL)
895 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
896 return NULL;
897 parse_root (default_root, &root_dir);
898 *root_dir = 0;
899 root_dir = default_root;
902 /* Local fixed drives can be cached permanently. Removable drives
903 cannot be cached permanently, since the volume name and serial
904 number (if nothing else) can change. Remote drives should be
905 treated as if they are removable, since there is no sure way to
906 tell whether they are or not. Also, the UNC association of drive
907 letters mapped to remote volumes can be changed at any time (even
908 by other processes) without notice.
910 As a compromise, so we can benefit from caching info for remote
911 volumes, we use a simple expiry mechanism to invalidate cache
912 entries that are more than ten seconds old. */
914 #if 0
915 /* No point doing this, because WNetGetConnection is even slower than
916 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
917 GetDriveType is about the only call of this type which does not
918 involve network access, and so is extremely quick). */
920 /* Map drive letter to UNC if remote. */
921 if ( isalpha( root_dir[0] ) && !fixed[ DRIVE_INDEX( root_dir[0] ) ] )
923 char remote_name[ 256 ];
924 char drive[3] = { root_dir[0], ':' };
926 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
927 == NO_ERROR)
928 /* do something */ ;
930 #endif
932 info = lookup_volume_info (root_dir);
934 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
936 char name[ 256 ];
937 DWORD serialnum;
938 DWORD maxcomp;
939 DWORD flags;
940 char type[ 256 ];
942 /* Info is not cached, or is stale. */
943 if (!GetVolumeInformation (root_dir,
944 name, sizeof (name),
945 &serialnum,
946 &maxcomp,
947 &flags,
948 type, sizeof (type)))
949 return NULL;
951 /* Cache the volume information for future use, overwriting existing
952 entry if present. */
953 if (info == NULL)
955 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
956 add_volume_info (root_dir, info);
958 else
960 free (info->name);
961 free (info->type);
964 info->name = strdup (name);
965 info->serialnum = serialnum;
966 info->maxcomp = maxcomp;
967 info->flags = flags;
968 info->type = strdup (type);
969 info->timestamp = GetTickCount ();
972 return info;
975 /* Get information on the volume where name is held; set path pointer to
976 start of pathname in name (past UNC header\volume header if present). */
978 get_volume_info (const char * name, const char ** pPath)
980 char temp[MAX_PATH];
981 char *rootname = NULL; /* default to current volume */
982 volume_info_data * info;
984 if (name == NULL)
985 return FALSE;
987 /* find the root name of the volume if given */
988 if (isalpha (name[0]) && name[1] == ':')
990 rootname = temp;
991 temp[0] = *name++;
992 temp[1] = *name++;
993 temp[2] = '\\';
994 temp[3] = 0;
996 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
998 char *str = temp;
999 int slashes = 4;
1000 rootname = temp;
1003 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1004 break;
1005 *str++ = *name++;
1007 while ( *name );
1009 *str++ = '\\';
1010 *str = 0;
1013 if (pPath)
1014 *pPath = name;
1016 info = GetCachedVolumeInformation (rootname);
1017 if (info != NULL)
1019 /* Set global referenced by other functions. */
1020 volume_info = *info;
1021 return TRUE;
1023 return FALSE;
1026 /* Determine if volume is FAT format (ie. only supports short 8.3
1027 names); also set path pointer to start of pathname in name. */
1029 is_fat_volume (const char * name, const char ** pPath)
1031 if (get_volume_info (name, pPath))
1032 return (volume_info.maxcomp == 12);
1033 return FALSE;
1036 /* Map filename to a legal 8.3 name if necessary. */
1037 const char *
1038 map_w32_filename (const char * name, const char ** pPath)
1040 static char shortname[MAX_PATH];
1041 char * str = shortname;
1042 char c;
1043 char * path;
1044 const char * save_name = name;
1046 if (is_fat_volume (name, &path)) /* truncate to 8.3 */
1048 register int left = 8; /* maximum number of chars in part */
1049 register int extn = 0; /* extension added? */
1050 register int dots = 2; /* maximum number of dots allowed */
1052 while (name < path)
1053 *str++ = *name++; /* skip past UNC header */
1055 while ((c = *name++))
1057 switch ( c )
1059 case '\\':
1060 case '/':
1061 *str++ = '\\';
1062 extn = 0; /* reset extension flags */
1063 dots = 2; /* max 2 dots */
1064 left = 8; /* max length 8 for main part */
1065 break;
1066 case ':':
1067 *str++ = ':';
1068 extn = 0; /* reset extension flags */
1069 dots = 2; /* max 2 dots */
1070 left = 8; /* max length 8 for main part */
1071 break;
1072 case '.':
1073 if ( dots )
1075 /* Convert path components of the form .xxx to _xxx,
1076 but leave . and .. as they are. This allows .emacs
1077 to be read as _emacs, for example. */
1079 if (! *name ||
1080 *name == '.' ||
1081 IS_DIRECTORY_SEP (*name))
1083 *str++ = '.';
1084 dots--;
1086 else
1088 *str++ = '_';
1089 left--;
1090 dots = 0;
1093 else if ( !extn )
1095 *str++ = '.';
1096 extn = 1; /* we've got an extension */
1097 left = 3; /* 3 chars in extension */
1099 else
1101 /* any embedded dots after the first are converted to _ */
1102 *str++ = '_';
1104 break;
1105 case '~':
1106 case '#': /* don't lose these, they're important */
1107 if ( ! left )
1108 str[-1] = c; /* replace last character of part */
1109 /* FALLTHRU */
1110 default:
1111 if ( left )
1113 *str++ = tolower (c); /* map to lower case (looks nicer) */
1114 left--;
1115 dots = 0; /* started a path component */
1117 break;
1120 *str = '\0';
1122 else
1124 strcpy (shortname, name);
1125 unixtodos_filename (shortname);
1128 if (pPath)
1129 *pPath = shortname + (path - save_name);
1131 return shortname;
1134 /* Emulate the Unix directory procedures opendir, closedir,
1135 and readdir. We can't use the procedures supplied in sysdep.c,
1136 so we provide them here. */
1138 struct direct dir_static; /* simulated directory contents */
1139 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
1140 static int dir_is_fat;
1141 static char dir_pathname[MAXPATHLEN+1];
1142 static WIN32_FIND_DATA dir_find_data;
1144 DIR *
1145 opendir (char *filename)
1147 DIR *dirp;
1149 /* Opening is done by FindFirstFile. However, a read is inherent to
1150 this operation, so we defer the open until read time. */
1152 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
1153 return NULL;
1154 if (dir_find_handle != INVALID_HANDLE_VALUE)
1155 return NULL;
1157 dirp->dd_fd = 0;
1158 dirp->dd_loc = 0;
1159 dirp->dd_size = 0;
1161 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
1162 dir_pathname[MAXPATHLEN] = '\0';
1163 dir_is_fat = is_fat_volume (filename, NULL);
1165 return dirp;
1168 void
1169 closedir (DIR *dirp)
1171 /* If we have a find-handle open, close it. */
1172 if (dir_find_handle != INVALID_HANDLE_VALUE)
1174 FindClose (dir_find_handle);
1175 dir_find_handle = INVALID_HANDLE_VALUE;
1177 xfree ((char *) dirp);
1180 struct direct *
1181 readdir (DIR *dirp)
1183 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1184 if (dir_find_handle == INVALID_HANDLE_VALUE)
1186 char filename[MAXNAMLEN + 3];
1187 int ln;
1189 strcpy (filename, dir_pathname);
1190 ln = strlen (filename) - 1;
1191 if (!IS_DIRECTORY_SEP (filename[ln]))
1192 strcat (filename, "\\");
1193 strcat (filename, "*");
1195 dir_find_handle = FindFirstFile (filename, &dir_find_data);
1197 if (dir_find_handle == INVALID_HANDLE_VALUE)
1198 return NULL;
1200 else
1202 if (!FindNextFile (dir_find_handle, &dir_find_data))
1203 return NULL;
1206 /* Emacs never uses this value, so don't bother making it match
1207 value returned by stat(). */
1208 dir_static.d_ino = 1;
1210 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
1211 dir_static.d_namlen - dir_static.d_namlen % 4;
1213 dir_static.d_namlen = strlen (dir_find_data.cFileName);
1214 strcpy (dir_static.d_name, dir_find_data.cFileName);
1215 if (dir_is_fat)
1216 _strlwr (dir_static.d_name);
1217 else if (!NILP (Vw32_downcase_file_names))
1219 register char *p;
1220 for (p = dir_static.d_name; *p; p++)
1221 if (*p >= 'a' && *p <= 'z')
1222 break;
1223 if (!*p)
1224 _strlwr (dir_static.d_name);
1227 return &dir_static;
1231 /* Shadow some MSVC runtime functions to map requests for long filenames
1232 to reasonable short names if necessary. This was originally added to
1233 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1234 long file names. */
1237 sys_access (const char * path, int mode)
1239 return _access (map_w32_filename (path, NULL), mode);
1243 sys_chdir (const char * path)
1245 return _chdir (map_w32_filename (path, NULL));
1249 sys_chmod (const char * path, int mode)
1251 return _chmod (map_w32_filename (path, NULL), mode);
1255 sys_creat (const char * path, int mode)
1257 return _creat (map_w32_filename (path, NULL), mode);
1260 FILE *
1261 sys_fopen(const char * path, const char * mode)
1263 int fd;
1264 int oflag;
1265 const char * mode_save = mode;
1267 /* Force all file handles to be non-inheritable. This is necessary to
1268 ensure child processes don't unwittingly inherit handles that might
1269 prevent future file access. */
1271 if (mode[0] == 'r')
1272 oflag = O_RDONLY;
1273 else if (mode[0] == 'w' || mode[0] == 'a')
1274 oflag = O_WRONLY | O_CREAT | O_TRUNC;
1275 else
1276 return NULL;
1278 /* Only do simplistic option parsing. */
1279 while (*++mode)
1280 if (mode[0] == '+')
1282 oflag &= ~(O_RDONLY | O_WRONLY);
1283 oflag |= O_RDWR;
1285 else if (mode[0] == 'b')
1287 oflag &= ~O_TEXT;
1288 oflag |= O_BINARY;
1290 else if (mode[0] == 't')
1292 oflag &= ~O_BINARY;
1293 oflag |= O_TEXT;
1295 else break;
1297 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
1298 if (fd < 0)
1299 return NULL;
1301 return _fdopen (fd, mode_save);
1304 /* This only works on NTFS volumes, but is useful to have. */
1306 sys_link (const char * old, const char * new)
1308 HANDLE fileh;
1309 int result = -1;
1310 char oldname[MAX_PATH], newname[MAX_PATH];
1312 if (old == NULL || new == NULL)
1314 errno = ENOENT;
1315 return -1;
1318 strcpy (oldname, map_w32_filename (old, NULL));
1319 strcpy (newname, map_w32_filename (new, NULL));
1321 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
1322 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1323 if (fileh != INVALID_HANDLE_VALUE)
1325 int wlen;
1327 /* Confusingly, the "alternate" stream name field does not apply
1328 when restoring a hard link, and instead contains the actual
1329 stream data for the link (ie. the name of the link to create).
1330 The WIN32_STREAM_ID structure before the cStreamName field is
1331 the stream header, which is then immediately followed by the
1332 stream data. */
1334 struct {
1335 WIN32_STREAM_ID wid;
1336 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
1337 } data;
1339 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
1340 data.wid.cStreamName, MAX_PATH);
1341 if (wlen > 0)
1343 LPVOID context = NULL;
1344 DWORD wbytes = 0;
1346 data.wid.dwStreamId = BACKUP_LINK;
1347 data.wid.dwStreamAttributes = 0;
1348 data.wid.Size.LowPart = wlen * sizeof(WCHAR);
1349 data.wid.Size.HighPart = 0;
1350 data.wid.dwStreamNameSize = 0;
1352 if (BackupWrite (fileh, (LPBYTE)&data,
1353 offsetof (WIN32_STREAM_ID, cStreamName)
1354 + data.wid.Size.LowPart,
1355 &wbytes, FALSE, FALSE, &context)
1356 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
1358 /* succeeded */
1359 result = 0;
1361 else
1363 /* Should try mapping GetLastError to errno; for now just
1364 indicate a general error (eg. links not supported). */
1365 errno = EINVAL; // perhaps EMLINK?
1369 CloseHandle (fileh);
1371 else
1372 errno = ENOENT;
1374 return result;
1378 sys_mkdir (const char * path)
1380 return _mkdir (map_w32_filename (path, NULL));
1383 /* Because of long name mapping issues, we need to implement this
1384 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1385 a unique name, instead of setting the input template to an empty
1386 string.
1388 Standard algorithm seems to be use pid or tid with a letter on the
1389 front (in place of the 6 X's) and cycle through the letters to find a
1390 unique name. We extend that to allow any reasonable character as the
1391 first of the 6 X's. */
1392 char *
1393 sys_mktemp (char * template)
1395 char * p;
1396 int i;
1397 unsigned uid = GetCurrentThreadId ();
1398 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1400 if (template == NULL)
1401 return NULL;
1402 p = template + strlen (template);
1403 i = 5;
1404 /* replace up to the last 5 X's with uid in decimal */
1405 while (--p >= template && p[0] == 'X' && --i >= 0)
1407 p[0] = '0' + uid % 10;
1408 uid /= 10;
1411 if (i < 0 && p[0] == 'X')
1413 i = 0;
1416 int save_errno = errno;
1417 p[0] = first_char[i];
1418 if (sys_access (template, 0) < 0)
1420 errno = save_errno;
1421 return template;
1424 while (++i < sizeof (first_char));
1427 /* Template is badly formed or else we can't generate a unique name,
1428 so return empty string */
1429 template[0] = 0;
1430 return template;
1434 sys_open (const char * path, int oflag, int mode)
1436 /* Force all file handles to be non-inheritable. */
1437 return _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, mode);
1441 sys_rename (const char * oldname, const char * newname)
1443 char temp[MAX_PATH];
1444 DWORD attr;
1446 /* MoveFile on Windows 95 doesn't correctly change the short file name
1447 alias in a number of circumstances (it is not easy to predict when
1448 just by looking at oldname and newname, unfortunately). In these
1449 cases, renaming through a temporary name avoids the problem.
1451 A second problem on Windows 95 is that renaming through a temp name when
1452 newname is uppercase fails (the final long name ends up in
1453 lowercase, although the short alias might be uppercase) UNLESS the
1454 long temp name is not 8.3.
1456 So, on Windows 95 we always rename through a temp name, and we make sure
1457 the temp name has a long extension to ensure correct renaming. */
1459 strcpy (temp, map_w32_filename (oldname, NULL));
1461 if (os_subtype == OS_WIN95)
1463 char * p;
1465 if (p = strrchr (temp, '\\'))
1466 p++;
1467 else
1468 p = temp;
1469 /* Force temp name to require a manufactured 8.3 alias - this
1470 seems to make the second rename work properly. */
1471 strcpy (p, "_rename_temp.XXXXXX");
1472 sys_mktemp (temp);
1473 if (rename (map_w32_filename (oldname, NULL), temp) < 0)
1474 return -1;
1477 /* Emulate Unix behaviour - newname is deleted if it already exists
1478 (at least if it is a file; don't do this for directories).
1479 However, don't do this if we are just changing the case of the file
1480 name - we will end up deleting the file we are trying to rename! */
1481 newname = map_w32_filename (newname, NULL);
1483 /* TODO: Use GetInformationByHandle (on NT) to ensure newname and temp
1484 do not refer to the same file, eg. through share aliases. */
1485 if (stricmp (newname, temp) != 0
1486 && (attr = GetFileAttributes (newname)) != -1
1487 && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
1489 _chmod (newname, 0666);
1490 _unlink (newname);
1493 return rename (temp, newname);
1497 sys_rmdir (const char * path)
1499 return _rmdir (map_w32_filename (path, NULL));
1503 sys_unlink (const char * path)
1505 path = map_w32_filename (path, NULL);
1507 /* On Unix, unlink works without write permission. */
1508 _chmod (path, 0666);
1509 return _unlink (path);
1512 static FILETIME utc_base_ft;
1513 static long double utc_base;
1514 static int init = 0;
1516 static time_t
1517 convert_time (FILETIME ft)
1519 long double ret;
1521 if (!init)
1523 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1524 SYSTEMTIME st;
1526 st.wYear = 1970;
1527 st.wMonth = 1;
1528 st.wDay = 1;
1529 st.wHour = 0;
1530 st.wMinute = 0;
1531 st.wSecond = 0;
1532 st.wMilliseconds = 0;
1534 SystemTimeToFileTime (&st, &utc_base_ft);
1535 utc_base = (long double) utc_base_ft.dwHighDateTime
1536 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1537 init = 1;
1540 if (CompareFileTime (&ft, &utc_base_ft) < 0)
1541 return 0;
1543 ret = (long double) ft.dwHighDateTime * 4096 * 1024 * 1024 + ft.dwLowDateTime;
1544 ret -= utc_base;
1545 return (time_t) (ret * 1e-7);
1548 void
1549 convert_from_time_t (time_t time, FILETIME * pft)
1551 long double tmp;
1553 if (!init)
1555 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1556 SYSTEMTIME st;
1558 st.wYear = 1970;
1559 st.wMonth = 1;
1560 st.wDay = 1;
1561 st.wHour = 0;
1562 st.wMinute = 0;
1563 st.wSecond = 0;
1564 st.wMilliseconds = 0;
1566 SystemTimeToFileTime (&st, &utc_base_ft);
1567 utc_base = (long double) utc_base_ft.dwHighDateTime
1568 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1569 init = 1;
1572 /* time in 100ns units since 1-Jan-1601 */
1573 tmp = (long double) time * 1e7 + utc_base;
1574 pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
1575 pft->dwLowDateTime = (DWORD) (tmp - (4096.0 * 1024 * 1024) * pft->dwHighDateTime);
1578 #if 0
1579 /* No reason to keep this; faking inode values either by hashing or even
1580 using the file index from GetInformationByHandle, is not perfect and
1581 so by default Emacs doesn't use the inode values on Windows.
1582 Instead, we now determine file-truename correctly (except for
1583 possible drive aliasing etc). */
1585 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1586 static unsigned
1587 hashval (const unsigned char * str)
1589 unsigned h = 0;
1590 while (*str)
1592 h = (h << 4) + *str++;
1593 h ^= (h >> 28);
1595 return h;
1598 /* Return the hash value of the canonical pathname, excluding the
1599 drive/UNC header, to get a hopefully unique inode number. */
1600 static DWORD
1601 generate_inode_val (const char * name)
1603 char fullname[ MAX_PATH ];
1604 char * p;
1605 unsigned hash;
1607 /* Get the truly canonical filename, if it exists. (Note: this
1608 doesn't resolve aliasing due to subst commands, or recognise hard
1609 links. */
1610 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
1611 abort ();
1613 parse_root (fullname, &p);
1614 /* Normal W32 filesystems are still case insensitive. */
1615 _strlwr (p);
1616 return hashval (p);
1619 #endif
1621 /* MSVC stat function can't cope with UNC names and has other bugs, so
1622 replace it with our own. This also allows us to calculate consistent
1623 inode values without hacks in the main Emacs code. */
1625 stat (const char * path, struct stat * buf)
1627 char * name;
1628 WIN32_FIND_DATA wfd;
1629 HANDLE fh;
1630 DWORD fake_inode;
1631 int permission;
1632 int len;
1633 int rootdir = FALSE;
1635 if (path == NULL || buf == NULL)
1637 errno = EFAULT;
1638 return -1;
1641 name = (char *) map_w32_filename (path, &path);
1642 /* must be valid filename, no wild cards */
1643 if (strchr (name, '*') || strchr (name, '?'))
1645 errno = ENOENT;
1646 return -1;
1649 /* Remove trailing directory separator, unless name is the root
1650 directory of a drive or UNC volume in which case ensure there
1651 is a trailing separator. */
1652 len = strlen (name);
1653 rootdir = (path >= name + len - 1
1654 && (IS_DIRECTORY_SEP (*path) || *path == 0));
1655 name = strcpy (alloca (len + 2), name);
1657 if (rootdir)
1659 if (!IS_DIRECTORY_SEP (name[len-1]))
1660 strcat (name, "\\");
1661 if (GetDriveType (name) < 2)
1663 errno = ENOENT;
1664 return -1;
1666 memset (&wfd, 0, sizeof (wfd));
1667 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1668 wfd.ftCreationTime = utc_base_ft;
1669 wfd.ftLastAccessTime = utc_base_ft;
1670 wfd.ftLastWriteTime = utc_base_ft;
1671 strcpy (wfd.cFileName, name);
1673 else
1675 if (IS_DIRECTORY_SEP (name[len-1]))
1676 name[len - 1] = 0;
1678 /* (This is hacky, but helps when doing file completions on
1679 network drives.) Optimize by using information available from
1680 active readdir if possible. */
1681 if (dir_find_handle != INVALID_HANDLE_VALUE
1682 && (len = strlen (dir_pathname)),
1683 strnicmp (name, dir_pathname, len) == 0
1684 && IS_DIRECTORY_SEP (name[len])
1685 && stricmp (name + len + 1, dir_static.d_name) == 0)
1687 /* This was the last entry returned by readdir. */
1688 wfd = dir_find_data;
1690 else
1692 fh = FindFirstFile (name, &wfd);
1693 if (fh == INVALID_HANDLE_VALUE)
1695 errno = ENOENT;
1696 return -1;
1698 FindClose (fh);
1702 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1704 buf->st_mode = _S_IFDIR;
1705 buf->st_nlink = 2; /* doesn't really matter */
1706 fake_inode = 0; /* this doesn't either I think */
1708 else if (!NILP (Vw32_get_true_file_attributes))
1710 /* This is more accurate in terms of gettting the correct number
1711 of links, but is quite slow (it is noticable when Emacs is
1712 making a list of file name completions). */
1713 BY_HANDLE_FILE_INFORMATION info;
1715 /* No access rights required to get info. */
1716 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
1718 if (GetFileInformationByHandle (fh, &info))
1720 switch (GetFileType (fh))
1722 case FILE_TYPE_DISK:
1723 buf->st_mode = _S_IFREG;
1724 break;
1725 case FILE_TYPE_PIPE:
1726 buf->st_mode = _S_IFIFO;
1727 break;
1728 case FILE_TYPE_CHAR:
1729 case FILE_TYPE_UNKNOWN:
1730 default:
1731 buf->st_mode = _S_IFCHR;
1733 buf->st_nlink = info.nNumberOfLinks;
1734 /* Might as well use file index to fake inode values, but this
1735 is not guaranteed to be unique unless we keep a handle open
1736 all the time (even then there are situations where it is
1737 not unique). Reputedly, there are at most 48 bits of info
1738 (on NTFS, presumably less on FAT). */
1739 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
1740 CloseHandle (fh);
1742 else
1744 errno = EACCES;
1745 return -1;
1748 else
1750 /* Don't bother to make this information more accurate. */
1751 buf->st_mode = _S_IFREG;
1752 buf->st_nlink = 1;
1753 fake_inode = 0;
1756 #if 0
1757 /* Not sure if there is any point in this. */
1758 if (!NILP (Vw32_generate_fake_inodes))
1759 fake_inode = generate_inode_val (name);
1760 else if (fake_inode == 0)
1762 /* For want of something better, try to make everything unique. */
1763 static DWORD gen_num = 0;
1764 fake_inode = ++gen_num;
1766 #endif
1768 /* MSVC defines _ino_t to be short; other libc's might not. */
1769 if (sizeof (buf->st_ino) == 2)
1770 buf->st_ino = fake_inode ^ (fake_inode >> 16);
1771 else
1772 buf->st_ino = fake_inode;
1774 /* consider files to belong to current user */
1775 buf->st_uid = the_passwd.pw_uid;
1776 buf->st_gid = the_passwd.pw_gid;
1778 /* volume_info is set indirectly by map_w32_filename */
1779 buf->st_dev = volume_info.serialnum;
1780 buf->st_rdev = volume_info.serialnum;
1783 buf->st_size = wfd.nFileSizeLow;
1785 /* Convert timestamps to Unix format. */
1786 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
1787 buf->st_atime = convert_time (wfd.ftLastAccessTime);
1788 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
1789 buf->st_ctime = convert_time (wfd.ftCreationTime);
1790 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
1792 /* determine rwx permissions */
1793 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
1794 permission = _S_IREAD;
1795 else
1796 permission = _S_IREAD | _S_IWRITE;
1798 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1799 permission |= _S_IEXEC;
1800 else
1802 char * p = strrchr (name, '.');
1803 if (p != NULL
1804 && (stricmp (p, ".exe") == 0 ||
1805 stricmp (p, ".com") == 0 ||
1806 stricmp (p, ".bat") == 0 ||
1807 stricmp (p, ".cmd") == 0))
1808 permission |= _S_IEXEC;
1811 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
1813 return 0;
1816 /* Provide fstat and utime as well as stat for consistent handling of
1817 file timestamps. */
1819 fstat (int desc, struct stat * buf)
1821 HANDLE fh = (HANDLE) _get_osfhandle (desc);
1822 BY_HANDLE_FILE_INFORMATION info;
1823 DWORD fake_inode;
1824 int permission;
1826 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
1828 case FILE_TYPE_DISK:
1829 buf->st_mode = _S_IFREG;
1830 if (!GetFileInformationByHandle (fh, &info))
1832 errno = EACCES;
1833 return -1;
1835 break;
1836 case FILE_TYPE_PIPE:
1837 buf->st_mode = _S_IFIFO;
1838 goto non_disk;
1839 case FILE_TYPE_CHAR:
1840 case FILE_TYPE_UNKNOWN:
1841 default:
1842 buf->st_mode = _S_IFCHR;
1843 non_disk:
1844 memset (&info, 0, sizeof (info));
1845 info.dwFileAttributes = 0;
1846 info.ftCreationTime = utc_base_ft;
1847 info.ftLastAccessTime = utc_base_ft;
1848 info.ftLastWriteTime = utc_base_ft;
1851 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1853 buf->st_mode = _S_IFDIR;
1854 buf->st_nlink = 2; /* doesn't really matter */
1855 fake_inode = 0; /* this doesn't either I think */
1857 else
1859 buf->st_nlink = info.nNumberOfLinks;
1860 /* Might as well use file index to fake inode values, but this
1861 is not guaranteed to be unique unless we keep a handle open
1862 all the time (even then there are situations where it is
1863 not unique). Reputedly, there are at most 48 bits of info
1864 (on NTFS, presumably less on FAT). */
1865 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
1868 /* MSVC defines _ino_t to be short; other libc's might not. */
1869 if (sizeof (buf->st_ino) == 2)
1870 buf->st_ino = fake_inode ^ (fake_inode >> 16);
1871 else
1872 buf->st_ino = fake_inode;
1874 /* consider files to belong to current user */
1875 buf->st_uid = 0;
1876 buf->st_gid = 0;
1878 buf->st_dev = info.dwVolumeSerialNumber;
1879 buf->st_rdev = info.dwVolumeSerialNumber;
1881 buf->st_size = info.nFileSizeLow;
1883 /* Convert timestamps to Unix format. */
1884 buf->st_mtime = convert_time (info.ftLastWriteTime);
1885 buf->st_atime = convert_time (info.ftLastAccessTime);
1886 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
1887 buf->st_ctime = convert_time (info.ftCreationTime);
1888 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
1890 /* determine rwx permissions */
1891 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
1892 permission = _S_IREAD;
1893 else
1894 permission = _S_IREAD | _S_IWRITE;
1896 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1897 permission |= _S_IEXEC;
1898 else
1900 #if 0 /* no way of knowing the filename */
1901 char * p = strrchr (name, '.');
1902 if (p != NULL &&
1903 (stricmp (p, ".exe") == 0 ||
1904 stricmp (p, ".com") == 0 ||
1905 stricmp (p, ".bat") == 0 ||
1906 stricmp (p, ".cmd") == 0))
1907 permission |= _S_IEXEC;
1908 #endif
1911 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
1913 return 0;
1917 utime (const char *name, struct utimbuf *times)
1919 struct utimbuf deftime;
1920 HANDLE fh;
1921 FILETIME mtime;
1922 FILETIME atime;
1924 if (times == NULL)
1926 deftime.modtime = deftime.actime = time (NULL);
1927 times = &deftime;
1930 /* Need write access to set times. */
1931 fh = CreateFile (name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
1932 0, OPEN_EXISTING, 0, NULL);
1933 if (fh)
1935 convert_from_time_t (times->actime, &atime);
1936 convert_from_time_t (times->modtime, &mtime);
1937 if (!SetFileTime (fh, NULL, &atime, &mtime))
1939 CloseHandle (fh);
1940 errno = EACCES;
1941 return -1;
1943 CloseHandle (fh);
1945 else
1947 errno = EINVAL;
1948 return -1;
1950 return 0;
1953 #ifdef HAVE_SOCKETS
1955 /* Wrappers for winsock functions to map between our file descriptors
1956 and winsock's handles; also set h_errno for convenience.
1958 To allow Emacs to run on systems which don't have winsock support
1959 installed, we dynamically link to winsock on startup if present, and
1960 otherwise provide the minimum necessary functionality
1961 (eg. gethostname). */
1963 /* function pointers for relevant socket functions */
1964 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
1965 void (PASCAL *pfn_WSASetLastError) (int iError);
1966 int (PASCAL *pfn_WSAGetLastError) (void);
1967 int (PASCAL *pfn_socket) (int af, int type, int protocol);
1968 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
1969 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
1970 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
1971 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
1972 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
1973 int (PASCAL *pfn_closesocket) (SOCKET s);
1974 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
1975 int (PASCAL *pfn_WSACleanup) (void);
1977 u_short (PASCAL *pfn_htons) (u_short hostshort);
1978 u_short (PASCAL *pfn_ntohs) (u_short netshort);
1979 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
1980 int (PASCAL *pfn_gethostname) (char * name, int namelen);
1981 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
1982 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
1984 /* SetHandleInformation is only needed to make sockets non-inheritable. */
1985 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
1986 #ifndef HANDLE_FLAG_INHERIT
1987 #define HANDLE_FLAG_INHERIT 1
1988 #endif
1990 HANDLE winsock_lib;
1991 static int winsock_inuse;
1993 BOOL
1994 term_winsock (void)
1996 if (winsock_lib != NULL && winsock_inuse == 0)
1998 /* Not sure what would cause WSAENETDOWN, or even if it can happen
1999 after WSAStartup returns successfully, but it seems reasonable
2000 to allow unloading winsock anyway in that case. */
2001 if (pfn_WSACleanup () == 0 ||
2002 pfn_WSAGetLastError () == WSAENETDOWN)
2004 if (FreeLibrary (winsock_lib))
2005 winsock_lib = NULL;
2006 return TRUE;
2009 return FALSE;
2012 BOOL
2013 init_winsock (int load_now)
2015 WSADATA winsockData;
2017 if (winsock_lib != NULL)
2018 return TRUE;
2020 pfn_SetHandleInformation = NULL;
2021 pfn_SetHandleInformation
2022 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2023 "SetHandleInformation");
2025 winsock_lib = LoadLibrary ("wsock32.dll");
2027 if (winsock_lib != NULL)
2029 /* dynamically link to socket functions */
2031 #define LOAD_PROC(fn) \
2032 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2033 goto fail;
2035 LOAD_PROC( WSAStartup );
2036 LOAD_PROC( WSASetLastError );
2037 LOAD_PROC( WSAGetLastError );
2038 LOAD_PROC( socket );
2039 LOAD_PROC( bind );
2040 LOAD_PROC( connect );
2041 LOAD_PROC( ioctlsocket );
2042 LOAD_PROC( recv );
2043 LOAD_PROC( send );
2044 LOAD_PROC( closesocket );
2045 LOAD_PROC( shutdown );
2046 LOAD_PROC( htons );
2047 LOAD_PROC( ntohs );
2048 LOAD_PROC( inet_addr );
2049 LOAD_PROC( gethostname );
2050 LOAD_PROC( gethostbyname );
2051 LOAD_PROC( getservbyname );
2052 LOAD_PROC( WSACleanup );
2054 #undef LOAD_PROC
2056 /* specify version 1.1 of winsock */
2057 if (pfn_WSAStartup (0x101, &winsockData) == 0)
2059 if (winsockData.wVersion != 0x101)
2060 goto fail;
2062 if (!load_now)
2064 /* Report that winsock exists and is usable, but leave
2065 socket functions disabled. I am assuming that calling
2066 WSAStartup does not require any network interaction,
2067 and in particular does not cause or require a dial-up
2068 connection to be established. */
2070 pfn_WSACleanup ();
2071 FreeLibrary (winsock_lib);
2072 winsock_lib = NULL;
2074 winsock_inuse = 0;
2075 return TRUE;
2078 fail:
2079 FreeLibrary (winsock_lib);
2080 winsock_lib = NULL;
2083 return FALSE;
2087 int h_errno = 0;
2089 /* function to set h_errno for compatability; map winsock error codes to
2090 normal system codes where they overlap (non-overlapping definitions
2091 are already in <sys/socket.h> */
2092 static void set_errno ()
2094 if (winsock_lib == NULL)
2095 h_errno = EINVAL;
2096 else
2097 h_errno = pfn_WSAGetLastError ();
2099 switch (h_errno)
2101 case WSAEACCES: h_errno = EACCES; break;
2102 case WSAEBADF: h_errno = EBADF; break;
2103 case WSAEFAULT: h_errno = EFAULT; break;
2104 case WSAEINTR: h_errno = EINTR; break;
2105 case WSAEINVAL: h_errno = EINVAL; break;
2106 case WSAEMFILE: h_errno = EMFILE; break;
2107 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
2108 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
2110 errno = h_errno;
2113 static void check_errno ()
2115 if (h_errno == 0 && winsock_lib != NULL)
2116 pfn_WSASetLastError (0);
2119 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2120 but I believe the method of keeping the socket handle separate (and
2121 insuring it is not inheritable) is the correct one. */
2123 //#define SOCK_REPLACE_HANDLE
2125 #ifdef SOCK_REPLACE_HANDLE
2126 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2127 #else
2128 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2129 #endif
2132 sys_socket(int af, int type, int protocol)
2134 int fd;
2135 long s;
2136 child_process * cp;
2138 if (winsock_lib == NULL)
2140 h_errno = ENETDOWN;
2141 return INVALID_SOCKET;
2144 check_errno ();
2146 /* call the real socket function */
2147 s = (long) pfn_socket (af, type, protocol);
2149 if (s != INVALID_SOCKET)
2151 /* Although under NT 3.5 _open_osfhandle will accept a socket
2152 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2153 that does not work under NT 3.1. However, we can get the same
2154 effect by using a backdoor function to replace an existing
2155 descriptor handle with the one we want. */
2157 /* allocate a file descriptor (with appropriate flags) */
2158 fd = _open ("NUL:", _O_RDWR);
2159 if (fd >= 0)
2161 #ifdef SOCK_REPLACE_HANDLE
2162 /* now replace handle to NUL with our socket handle */
2163 CloseHandle ((HANDLE) _get_osfhandle (fd));
2164 _free_osfhnd (fd);
2165 _set_osfhnd (fd, s);
2166 /* setmode (fd, _O_BINARY); */
2167 #else
2168 /* Make a non-inheritable copy of the socket handle. */
2170 HANDLE parent;
2171 HANDLE new_s = INVALID_HANDLE_VALUE;
2173 parent = GetCurrentProcess ();
2175 /* Apparently there is a bug in NT 3.51 with some service
2176 packs, which prevents using DuplicateHandle to make a
2177 socket handle non-inheritable (causes WSACleanup to
2178 hang). The work-around is to use SetHandleInformation
2179 instead if it is available and implemented. */
2180 if (!pfn_SetHandleInformation
2181 || !pfn_SetHandleInformation ((HANDLE) s,
2182 HANDLE_FLAG_INHERIT,
2185 DuplicateHandle (parent,
2186 (HANDLE) s,
2187 parent,
2188 &new_s,
2190 FALSE,
2191 DUPLICATE_SAME_ACCESS);
2192 pfn_closesocket (s);
2193 s = (SOCKET) new_s;
2195 fd_info[fd].hnd = (HANDLE) s;
2197 #endif
2199 /* set our own internal flags */
2200 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
2202 cp = new_child ();
2203 if (cp)
2205 cp->fd = fd;
2206 cp->status = STATUS_READ_ACKNOWLEDGED;
2208 /* attach child_process to fd_info */
2209 if (fd_info[ fd ].cp != NULL)
2211 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
2212 abort ();
2215 fd_info[ fd ].cp = cp;
2217 /* success! */
2218 winsock_inuse++; /* count open sockets */
2219 return fd;
2222 /* clean up */
2223 _close (fd);
2225 pfn_closesocket (s);
2226 h_errno = EMFILE;
2228 set_errno ();
2230 return -1;
2235 sys_bind (int s, const struct sockaddr * addr, int namelen)
2237 if (winsock_lib == NULL)
2239 h_errno = ENOTSOCK;
2240 return SOCKET_ERROR;
2243 check_errno ();
2244 if (fd_info[s].flags & FILE_SOCKET)
2246 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
2247 if (rc == SOCKET_ERROR)
2248 set_errno ();
2249 return rc;
2251 h_errno = ENOTSOCK;
2252 return SOCKET_ERROR;
2257 sys_connect (int s, const struct sockaddr * name, int namelen)
2259 if (winsock_lib == NULL)
2261 h_errno = ENOTSOCK;
2262 return SOCKET_ERROR;
2265 check_errno ();
2266 if (fd_info[s].flags & FILE_SOCKET)
2268 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
2269 if (rc == SOCKET_ERROR)
2270 set_errno ();
2271 return rc;
2273 h_errno = ENOTSOCK;
2274 return SOCKET_ERROR;
2277 u_short
2278 sys_htons (u_short hostshort)
2280 return (winsock_lib != NULL) ?
2281 pfn_htons (hostshort) : hostshort;
2284 u_short
2285 sys_ntohs (u_short netshort)
2287 return (winsock_lib != NULL) ?
2288 pfn_ntohs (netshort) : netshort;
2291 unsigned long
2292 sys_inet_addr (const char * cp)
2294 return (winsock_lib != NULL) ?
2295 pfn_inet_addr (cp) : INADDR_NONE;
2299 sys_gethostname (char * name, int namelen)
2301 if (winsock_lib != NULL)
2302 return pfn_gethostname (name, namelen);
2304 if (namelen > MAX_COMPUTERNAME_LENGTH)
2305 return !GetComputerName (name, &namelen);
2307 h_errno = EFAULT;
2308 return SOCKET_ERROR;
2311 struct hostent *
2312 sys_gethostbyname(const char * name)
2314 struct hostent * host;
2316 if (winsock_lib == NULL)
2318 h_errno = ENETDOWN;
2319 return NULL;
2322 check_errno ();
2323 host = pfn_gethostbyname (name);
2324 if (!host)
2325 set_errno ();
2326 return host;
2329 struct servent *
2330 sys_getservbyname(const char * name, const char * proto)
2332 struct servent * serv;
2334 if (winsock_lib == NULL)
2336 h_errno = ENETDOWN;
2337 return NULL;
2340 check_errno ();
2341 serv = pfn_getservbyname (name, proto);
2342 if (!serv)
2343 set_errno ();
2344 return serv;
2348 sys_shutdown (int s, int how)
2350 int rc;
2352 if (winsock_lib == NULL)
2354 h_errno = ENETDOWN;
2355 return SOCKET_ERROR;
2358 check_errno ();
2359 if (fd_info[s].flags & FILE_SOCKET)
2361 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
2362 if (rc == SOCKET_ERROR)
2363 set_errno ();
2364 return rc;
2366 h_errno = ENOTSOCK;
2367 return SOCKET_ERROR;
2370 #endif /* HAVE_SOCKETS */
2373 /* Shadow main io functions: we need to handle pipes and sockets more
2374 intelligently, and implement non-blocking mode as well. */
2377 sys_close (int fd)
2379 int rc;
2381 if (fd < 0 || fd >= MAXDESC)
2383 errno = EBADF;
2384 return -1;
2387 if (fd_info[fd].cp)
2389 child_process * cp = fd_info[fd].cp;
2391 fd_info[fd].cp = NULL;
2393 if (CHILD_ACTIVE (cp))
2395 /* if last descriptor to active child_process then cleanup */
2396 int i;
2397 for (i = 0; i < MAXDESC; i++)
2399 if (i == fd)
2400 continue;
2401 if (fd_info[i].cp == cp)
2402 break;
2404 if (i == MAXDESC)
2406 #ifdef HAVE_SOCKETS
2407 if (fd_info[fd].flags & FILE_SOCKET)
2409 #ifndef SOCK_REPLACE_HANDLE
2410 if (winsock_lib == NULL) abort ();
2412 pfn_shutdown (SOCK_HANDLE (fd), 2);
2413 rc = pfn_closesocket (SOCK_HANDLE (fd));
2414 #endif
2415 winsock_inuse--; /* count open sockets */
2417 #endif
2418 delete_child (cp);
2423 /* Note that sockets do not need special treatment here (at least on
2424 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2425 closesocket is equivalent to CloseHandle, which is to be expected
2426 because socket handles are fully fledged kernel handles. */
2427 rc = _close (fd);
2429 if (rc == 0)
2430 fd_info[fd].flags = 0;
2432 return rc;
2436 sys_dup (int fd)
2438 int new_fd;
2440 new_fd = _dup (fd);
2441 if (new_fd >= 0)
2443 /* duplicate our internal info as well */
2444 fd_info[new_fd] = fd_info[fd];
2446 return new_fd;
2451 sys_dup2 (int src, int dst)
2453 int rc;
2455 if (dst < 0 || dst >= MAXDESC)
2457 errno = EBADF;
2458 return -1;
2461 /* make sure we close the destination first if it's a pipe or socket */
2462 if (src != dst && fd_info[dst].flags != 0)
2463 sys_close (dst);
2465 rc = _dup2 (src, dst);
2466 if (rc == 0)
2468 /* duplicate our internal info as well */
2469 fd_info[dst] = fd_info[src];
2471 return rc;
2474 /* Unix pipe() has only one arg */
2476 sys_pipe (int * phandles)
2478 int rc;
2479 unsigned flags;
2480 child_process * cp;
2482 /* make pipe handles non-inheritable; when we spawn a child, we
2483 replace the relevant handle with an inheritable one. Also put
2484 pipes into binary mode; we will do text mode translation ourselves
2485 if required. */
2486 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
2488 if (rc == 0)
2490 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
2491 fd_info[phandles[0]].flags = flags;
2493 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
2494 fd_info[phandles[1]].flags = flags;
2497 return rc;
2500 /* From ntproc.c */
2501 extern Lisp_Object Vw32_pipe_read_delay;
2503 /* Function to do blocking read of one byte, needed to implement
2504 select. It is only allowed on sockets and pipes. */
2506 _sys_read_ahead (int fd)
2508 child_process * cp;
2509 int rc;
2511 if (fd < 0 || fd >= MAXDESC)
2512 return STATUS_READ_ERROR;
2514 cp = fd_info[fd].cp;
2516 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
2517 return STATUS_READ_ERROR;
2519 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
2520 || (fd_info[fd].flags & FILE_READ) == 0)
2522 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd));
2523 abort ();
2526 cp->status = STATUS_READ_IN_PROGRESS;
2528 if (fd_info[fd].flags & FILE_PIPE)
2530 rc = _read (fd, &cp->chr, sizeof (char));
2532 /* Give subprocess time to buffer some more output for us before
2533 reporting that input is available; we need this because Windows 95
2534 connects DOS programs to pipes by making the pipe appear to be
2535 the normal console stdout - as a result most DOS programs will
2536 write to stdout without buffering, ie. one character at a
2537 time. Even some W32 programs do this - "dir" in a command
2538 shell on NT is very slow if we don't do this. */
2539 if (rc > 0)
2541 int wait = XINT (Vw32_pipe_read_delay);
2543 if (wait > 0)
2544 Sleep (wait);
2545 else if (wait < 0)
2546 while (++wait <= 0)
2547 /* Yield remainder of our time slice, effectively giving a
2548 temporary priority boost to the child process. */
2549 Sleep (0);
2552 #ifdef HAVE_SOCKETS
2553 else if (fd_info[fd].flags & FILE_SOCKET)
2554 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
2555 #endif
2557 if (rc == sizeof (char))
2558 cp->status = STATUS_READ_SUCCEEDED;
2559 else
2560 cp->status = STATUS_READ_FAILED;
2562 return cp->status;
2566 sys_read (int fd, char * buffer, unsigned int count)
2568 int nchars;
2569 int to_read;
2570 DWORD waiting;
2571 char * orig_buffer = buffer;
2573 if (fd < 0 || fd >= MAXDESC)
2575 errno = EBADF;
2576 return -1;
2579 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
2581 child_process *cp = fd_info[fd].cp;
2583 if ((fd_info[fd].flags & FILE_READ) == 0)
2585 errno = EBADF;
2586 return -1;
2589 nchars = 0;
2591 /* re-read CR carried over from last read */
2592 if (fd_info[fd].flags & FILE_LAST_CR)
2594 if (fd_info[fd].flags & FILE_BINARY) abort ();
2595 *buffer++ = 0x0d;
2596 count--;
2597 nchars++;
2598 fd_info[fd].flags &= ~FILE_LAST_CR;
2601 /* presence of a child_process structure means we are operating in
2602 non-blocking mode - otherwise we just call _read directly.
2603 Note that the child_process structure might be missing because
2604 reap_subprocess has been called; in this case the pipe is
2605 already broken, so calling _read on it is okay. */
2606 if (cp)
2608 int current_status = cp->status;
2610 switch (current_status)
2612 case STATUS_READ_FAILED:
2613 case STATUS_READ_ERROR:
2614 /* report normal EOF if nothing in buffer */
2615 if (nchars <= 0)
2616 fd_info[fd].flags |= FILE_AT_EOF;
2617 return nchars;
2619 case STATUS_READ_READY:
2620 case STATUS_READ_IN_PROGRESS:
2621 DebPrint (("sys_read called when read is in progress\n"));
2622 errno = EWOULDBLOCK;
2623 return -1;
2625 case STATUS_READ_SUCCEEDED:
2626 /* consume read-ahead char */
2627 *buffer++ = cp->chr;
2628 count--;
2629 nchars++;
2630 cp->status = STATUS_READ_ACKNOWLEDGED;
2631 ResetEvent (cp->char_avail);
2633 case STATUS_READ_ACKNOWLEDGED:
2634 break;
2636 default:
2637 DebPrint (("sys_read: bad status %d\n", current_status));
2638 errno = EBADF;
2639 return -1;
2642 if (fd_info[fd].flags & FILE_PIPE)
2644 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
2645 to_read = min (waiting, (DWORD) count);
2647 if (to_read > 0)
2648 nchars += _read (fd, buffer, to_read);
2650 #ifdef HAVE_SOCKETS
2651 else /* FILE_SOCKET */
2653 if (winsock_lib == NULL) abort ();
2655 /* do the equivalent of a non-blocking read */
2656 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
2657 if (waiting == 0 && nchars == 0)
2659 h_errno = errno = EWOULDBLOCK;
2660 return -1;
2663 if (waiting)
2665 /* always use binary mode for sockets */
2666 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
2667 if (res == SOCKET_ERROR)
2669 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
2670 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
2671 set_errno ();
2672 return -1;
2674 nchars += res;
2677 #endif
2679 else
2681 int nread = _read (fd, buffer, count);
2682 if (nread >= 0)
2683 nchars += nread;
2684 else if (nchars == 0)
2685 nchars = nread;
2688 if (nchars <= 0)
2689 fd_info[fd].flags |= FILE_AT_EOF;
2690 /* Perform text mode translation if required. */
2691 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
2693 nchars = crlf_to_lf (nchars, orig_buffer);
2694 /* If buffer contains only CR, return that. To be absolutely
2695 sure we should attempt to read the next char, but in
2696 practice a CR to be followed by LF would not appear by
2697 itself in the buffer. */
2698 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
2700 fd_info[fd].flags |= FILE_LAST_CR;
2701 nchars--;
2705 else
2706 nchars = _read (fd, buffer, count);
2708 return nchars;
2711 /* For now, don't bother with a non-blocking mode */
2713 sys_write (int fd, const void * buffer, unsigned int count)
2715 int nchars;
2717 if (fd < 0 || fd >= MAXDESC)
2719 errno = EBADF;
2720 return -1;
2723 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
2725 if ((fd_info[fd].flags & FILE_WRITE) == 0)
2727 errno = EBADF;
2728 return -1;
2731 /* Perform text mode translation if required. */
2732 if ((fd_info[fd].flags & FILE_BINARY) == 0)
2734 char * tmpbuf = alloca (count * 2);
2735 unsigned char * src = (void *)buffer;
2736 unsigned char * dst = tmpbuf;
2737 int nbytes = count;
2739 while (1)
2741 unsigned char *next;
2742 /* copy next line or remaining bytes */
2743 next = _memccpy (dst, src, '\n', nbytes);
2744 if (next)
2746 /* copied one line ending with '\n' */
2747 int copied = next - dst;
2748 nbytes -= copied;
2749 src += copied;
2750 /* insert '\r' before '\n' */
2751 next[-1] = '\r';
2752 next[0] = '\n';
2753 dst = next + 1;
2754 count++;
2756 else
2757 /* copied remaining partial line -> now finished */
2758 break;
2760 buffer = tmpbuf;
2764 #ifdef HAVE_SOCKETS
2765 if (fd_info[fd].flags & FILE_SOCKET)
2767 if (winsock_lib == NULL) abort ();
2768 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
2769 if (nchars == SOCKET_ERROR)
2771 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
2772 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
2773 set_errno ();
2776 else
2777 #endif
2778 nchars = _write (fd, buffer, count);
2780 return nchars;
2783 static void
2784 check_windows_init_file ()
2786 extern int noninteractive, inhibit_window_system;
2788 /* A common indication that Emacs is not installed properly is when
2789 it cannot find the Windows installation file. If this file does
2790 not exist in the expected place, tell the user. */
2792 if (!noninteractive && !inhibit_window_system) {
2793 extern Lisp_Object Vwindow_system, Vload_path;
2794 Lisp_Object init_file;
2795 int fd;
2797 init_file = build_string ("term/w32-win");
2798 fd = openp (Vload_path, init_file, ".el:.elc", NULL, 0);
2799 if (fd < 0) {
2800 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
2801 char *init_file_name = XSTRING (init_file)->data;
2802 char *load_path = XSTRING (load_path_print)->data;
2803 char *buffer = alloca (1024);
2805 sprintf (buffer,
2806 "The Emacs Windows initialization file \"%s.el\" "
2807 "could not be found in your Emacs installation. "
2808 "Emacs checked the following directories for this file:\n"
2809 "\n%s\n\n"
2810 "When Emacs cannot find this file, it usually means that it "
2811 "was not installed properly, or its distribution file was "
2812 "not unpacked properly.\nSee the README.W32 file in the "
2813 "top-level Emacs directory for more information.",
2814 init_file_name, load_path);
2815 MessageBox (NULL,
2816 buffer,
2817 "Emacs Abort Dialog",
2818 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
2819 close (fd);
2821 /* Use the low-level Emacs abort. */
2822 #undef abort
2823 abort ();
2828 void
2829 term_ntproc ()
2831 #ifdef HAVE_SOCKETS
2832 /* shutdown the socket interface if necessary */
2833 term_winsock ();
2834 #endif
2836 /* Check whether we are shutting down because we cannot find the
2837 Windows initialization file. Do this during shutdown so that
2838 Emacs is initialized as possible, and so that it is out of the
2839 critical startup path. */
2840 check_windows_init_file ();
2843 void
2844 init_ntproc ()
2846 #ifdef HAVE_SOCKETS
2847 /* Initialise the socket interface now if available and requested by
2848 the user by defining PRELOAD_WINSOCK; otherwise loading will be
2849 delayed until open-network-stream is called (w32-has-winsock can
2850 also be used to dynamically load or reload winsock).
2852 Conveniently, init_environment is called before us, so
2853 PRELOAD_WINSOCK can be set in the registry. */
2855 /* Always initialize this correctly. */
2856 winsock_lib = NULL;
2858 if (getenv ("PRELOAD_WINSOCK") != NULL)
2859 init_winsock (TRUE);
2860 #endif
2862 /* Initial preparation for subprocess support: replace our standard
2863 handles with non-inheritable versions. */
2865 HANDLE parent;
2866 HANDLE stdin_save = INVALID_HANDLE_VALUE;
2867 HANDLE stdout_save = INVALID_HANDLE_VALUE;
2868 HANDLE stderr_save = INVALID_HANDLE_VALUE;
2870 parent = GetCurrentProcess ();
2872 /* ignore errors when duplicating and closing; typically the
2873 handles will be invalid when running as a gui program. */
2874 DuplicateHandle (parent,
2875 GetStdHandle (STD_INPUT_HANDLE),
2876 parent,
2877 &stdin_save,
2879 FALSE,
2880 DUPLICATE_SAME_ACCESS);
2882 DuplicateHandle (parent,
2883 GetStdHandle (STD_OUTPUT_HANDLE),
2884 parent,
2885 &stdout_save,
2887 FALSE,
2888 DUPLICATE_SAME_ACCESS);
2890 DuplicateHandle (parent,
2891 GetStdHandle (STD_ERROR_HANDLE),
2892 parent,
2893 &stderr_save,
2895 FALSE,
2896 DUPLICATE_SAME_ACCESS);
2898 fclose (stdin);
2899 fclose (stdout);
2900 fclose (stderr);
2902 if (stdin_save != INVALID_HANDLE_VALUE)
2903 _open_osfhandle ((long) stdin_save, O_TEXT);
2904 else
2905 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
2906 _fdopen (0, "r");
2908 if (stdout_save != INVALID_HANDLE_VALUE)
2909 _open_osfhandle ((long) stdout_save, O_TEXT);
2910 else
2911 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
2912 _fdopen (1, "w");
2914 if (stderr_save != INVALID_HANDLE_VALUE)
2915 _open_osfhandle ((long) stderr_save, O_TEXT);
2916 else
2917 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
2918 _fdopen (2, "w");
2921 /* unfortunately, atexit depends on implementation of malloc */
2922 /* atexit (term_ntproc); */
2923 signal (SIGABRT, term_ntproc);
2925 /* determine which drives are fixed, for GetCachedVolumeInformation */
2927 /* GetDriveType must have trailing backslash. */
2928 char drive[] = "A:\\";
2930 /* Loop over all possible drive letters */
2931 while (*drive <= 'Z')
2933 /* Record if this drive letter refers to a fixed drive. */
2934 fixed_drives[DRIVE_INDEX (*drive)] =
2935 (GetDriveType (drive) == DRIVE_FIXED);
2937 (*drive)++;
2942 /* end of nt.c */