* generic-x.el (apache-conf-generic-mode): Highlight the first
[emacs.git] / src / w32.c
blobf6e9f765500b5a68910354702fa8e46a03a2cc17
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995, 2000, 2001 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/file.h>
34 #include <sys/time.h>
35 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
43 #undef access
44 #undef chdir
45 #undef chmod
46 #undef creat
47 #undef ctime
48 #undef fopen
49 #undef link
50 #undef mkdir
51 #undef mktemp
52 #undef open
53 #undef rename
54 #undef rmdir
55 #undef unlink
57 #undef close
58 #undef dup
59 #undef dup2
60 #undef pipe
61 #undef read
62 #undef write
64 #undef strerror
66 #include "lisp.h"
68 #include <pwd.h>
70 #ifdef __GNUC__
71 #define _ANONYMOUS_UNION
72 #define _ANONYMOUS_STRUCT
73 #endif
74 #include <windows.h>
76 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
77 #include <sys/socket.h>
78 #undef socket
79 #undef bind
80 #undef connect
81 #undef htons
82 #undef ntohs
83 #undef inet_addr
84 #undef gethostname
85 #undef gethostbyname
86 #undef getservbyname
87 #undef shutdown
88 #endif
90 #include "w32.h"
91 #include "ndir.h"
92 #include "w32heap.h"
93 #include "systime.h"
95 extern Lisp_Object Vw32_downcase_file_names;
96 extern Lisp_Object Vw32_generate_fake_inodes;
97 extern Lisp_Object Vw32_get_true_file_attributes;
98 extern Lisp_Object Vw32_num_mouse_buttons;
101 /* Equivalent of strerror for W32 error codes. */
102 char *
103 w32_strerror (int error_no)
105 static char buf[500];
107 if (error_no == 0)
108 error_no = GetLastError ();
110 buf[0] = '\0';
111 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL,
112 error_no,
113 0, /* choose most suitable language */
114 buf, sizeof (buf), NULL))
115 sprintf (buf, "w32 error %u", error_no);
116 return buf;
119 static char startup_dir[MAXPATHLEN];
121 /* Get the current working directory. */
122 char *
123 getwd (char *dir)
125 #if 0
126 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
127 return dir;
128 return NULL;
129 #else
130 /* Emacs doesn't actually change directory itself, and we want to
131 force our real wd to be where emacs.exe is to avoid unnecessary
132 conflicts when trying to rename or delete directories. */
133 strcpy (dir, startup_dir);
134 return dir;
135 #endif
138 #ifndef HAVE_SOCKETS
139 /* Emulate gethostname. */
141 gethostname (char *buffer, int size)
143 /* NT only allows small host names, so the buffer is
144 certainly large enough. */
145 return !GetComputerName (buffer, &size);
147 #endif /* HAVE_SOCKETS */
149 /* Emulate getloadavg. */
151 getloadavg (double loadavg[], int nelem)
153 int i;
155 /* A faithful emulation is going to have to be saved for a rainy day. */
156 for (i = 0; i < nelem; i++)
158 loadavg[i] = 0.0;
160 return i;
163 /* Emulate getpwuid, getpwnam and others. */
165 #define PASSWD_FIELD_SIZE 256
167 static char the_passwd_name[PASSWD_FIELD_SIZE];
168 static char the_passwd_passwd[PASSWD_FIELD_SIZE];
169 static char the_passwd_gecos[PASSWD_FIELD_SIZE];
170 static char the_passwd_dir[PASSWD_FIELD_SIZE];
171 static char the_passwd_shell[PASSWD_FIELD_SIZE];
173 static struct passwd the_passwd =
175 the_passwd_name,
176 the_passwd_passwd,
180 the_passwd_gecos,
181 the_passwd_dir,
182 the_passwd_shell,
185 int
186 getuid ()
188 return the_passwd.pw_uid;
191 int
192 geteuid ()
194 /* I could imagine arguing for checking to see whether the user is
195 in the Administrators group and returning a UID of 0 for that
196 case, but I don't know how wise that would be in the long run. */
197 return getuid ();
200 int
201 getgid ()
203 return the_passwd.pw_gid;
206 int
207 getegid ()
209 return getgid ();
212 struct passwd *
213 getpwuid (int uid)
215 if (uid == the_passwd.pw_uid)
216 return &the_passwd;
217 return NULL;
220 struct passwd *
221 getpwnam (char *name)
223 struct passwd *pw;
225 pw = getpwuid (getuid ());
226 if (!pw)
227 return pw;
229 if (stricmp (name, pw->pw_name))
230 return NULL;
232 return pw;
235 void
236 init_user_info ()
238 /* Find the user's real name by opening the process token and
239 looking up the name associated with the user-sid in that token.
241 Use the relative portion of the identifier authority value from
242 the user-sid as the user id value (same for group id using the
243 primary group sid from the process token). */
245 char user_sid[256], name[256], domain[256];
246 DWORD length = sizeof (name), dlength = sizeof (domain), trash;
247 HANDLE token = NULL;
248 SID_NAME_USE user_type;
250 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
251 && GetTokenInformation (token, TokenUser,
252 (PVOID) user_sid, sizeof (user_sid), &trash)
253 && LookupAccountSid (NULL, *((PSID *) user_sid), name, &length,
254 domain, &dlength, &user_type))
256 strcpy (the_passwd.pw_name, name);
257 /* Determine a reasonable uid value. */
258 if (stricmp ("administrator", name) == 0)
260 the_passwd.pw_uid = 0;
261 the_passwd.pw_gid = 0;
263 else
265 SID_IDENTIFIER_AUTHORITY * pSIA;
267 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
268 /* I believe the relative portion is the last 4 bytes (of 6)
269 with msb first. */
270 the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
271 (pSIA->Value[3] << 16) +
272 (pSIA->Value[4] << 8) +
273 (pSIA->Value[5] << 0));
274 /* restrict to conventional uid range for normal users */
275 the_passwd.pw_uid = the_passwd.pw_uid % 60001;
277 /* Get group id */
278 if (GetTokenInformation (token, TokenPrimaryGroup,
279 (PVOID) user_sid, sizeof (user_sid), &trash))
281 SID_IDENTIFIER_AUTHORITY * pSIA;
283 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
284 the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
285 (pSIA->Value[3] << 16) +
286 (pSIA->Value[4] << 8) +
287 (pSIA->Value[5] << 0));
288 /* I don't know if this is necessary, but for safety... */
289 the_passwd.pw_gid = the_passwd.pw_gid % 60001;
291 else
292 the_passwd.pw_gid = the_passwd.pw_uid;
295 /* If security calls are not supported (presumably because we
296 are running under Windows 95), fallback to this. */
297 else if (GetUserName (name, &length))
299 strcpy (the_passwd.pw_name, name);
300 if (stricmp ("administrator", name) == 0)
301 the_passwd.pw_uid = 0;
302 else
303 the_passwd.pw_uid = 123;
304 the_passwd.pw_gid = the_passwd.pw_uid;
306 else
308 strcpy (the_passwd.pw_name, "unknown");
309 the_passwd.pw_uid = 123;
310 the_passwd.pw_gid = 123;
313 /* Ensure HOME and SHELL are defined. */
314 if (getenv ("HOME") == NULL)
315 abort ();
316 if (getenv ("SHELL") == NULL)
317 abort ();
319 /* Set dir and shell from environment variables. */
320 strcpy (the_passwd.pw_dir, getenv ("HOME"));
321 strcpy (the_passwd.pw_shell, getenv ("SHELL"));
323 if (token)
324 CloseHandle (token);
328 random ()
330 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
331 return ((rand () << 15) | rand ());
334 void
335 srandom (int seed)
337 srand (seed);
341 /* Normalize filename by converting all path separators to
342 the specified separator. Also conditionally convert upper
343 case path name components to lower case. */
345 static void
346 normalize_filename (fp, path_sep)
347 register char *fp;
348 char path_sep;
350 char sep;
351 char *elem;
353 /* Always lower-case drive letters a-z, even if the filesystem
354 preserves case in filenames.
355 This is so filenames can be compared by string comparison
356 functions that are case-sensitive. Even case-preserving filesystems
357 do not distinguish case in drive letters. */
358 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
360 *fp += 'a' - 'A';
361 fp += 2;
364 if (NILP (Vw32_downcase_file_names))
366 while (*fp)
368 if (*fp == '/' || *fp == '\\')
369 *fp = path_sep;
370 fp++;
372 return;
375 sep = path_sep; /* convert to this path separator */
376 elem = fp; /* start of current path element */
378 do {
379 if (*fp >= 'a' && *fp <= 'z')
380 elem = 0; /* don't convert this element */
382 if (*fp == 0 || *fp == ':')
384 sep = *fp; /* restore current separator (or 0) */
385 *fp = '/'; /* after conversion of this element */
388 if (*fp == '/' || *fp == '\\')
390 if (elem && elem != fp)
392 *fp = 0; /* temporary end of string */
393 _strlwr (elem); /* while we convert to lower case */
395 *fp = sep; /* convert (or restore) path separator */
396 elem = fp + 1; /* next element starts after separator */
397 sep = path_sep;
399 } while (*fp++);
402 /* Destructively turn backslashes into slashes. */
403 void
404 dostounix_filename (p)
405 register char *p;
407 normalize_filename (p, '/');
410 /* Destructively turn slashes into backslashes. */
411 void
412 unixtodos_filename (p)
413 register char *p;
415 normalize_filename (p, '\\');
418 /* Remove all CR's that are followed by a LF.
419 (From msdos.c...probably should figure out a way to share it,
420 although this code isn't going to ever change.) */
422 crlf_to_lf (n, buf)
423 register int n;
424 register unsigned char *buf;
426 unsigned char *np = buf;
427 unsigned char *startp = buf;
428 unsigned char *endp = buf + n;
430 if (n == 0)
431 return n;
432 while (buf < endp - 1)
434 if (*buf == 0x0d)
436 if (*(++buf) != 0x0a)
437 *np++ = 0x0d;
439 else
440 *np++ = *buf++;
442 if (buf < endp)
443 *np++ = *buf++;
444 return np - startp;
447 /* Parse the root part of file name, if present. Return length and
448 optionally store pointer to char after root. */
449 static int
450 parse_root (char * name, char ** pPath)
452 char * start = name;
454 if (name == NULL)
455 return 0;
457 /* find the root name of the volume if given */
458 if (isalpha (name[0]) && name[1] == ':')
460 /* skip past drive specifier */
461 name += 2;
462 if (IS_DIRECTORY_SEP (name[0]))
463 name++;
465 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
467 int slashes = 2;
468 name += 2;
471 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
472 break;
473 name++;
475 while ( *name );
476 if (IS_DIRECTORY_SEP (name[0]))
477 name++;
480 if (pPath)
481 *pPath = name;
483 return name - start;
486 /* Get long base name for name; name is assumed to be absolute. */
487 static int
488 get_long_basename (char * name, char * buf, int size)
490 WIN32_FIND_DATA find_data;
491 HANDLE dir_handle;
492 int len = 0;
494 /* must be valid filename, no wild cards or other invalid characters */
495 if (strpbrk (name, "*?|<>\""))
496 return 0;
498 dir_handle = FindFirstFile (name, &find_data);
499 if (dir_handle != INVALID_HANDLE_VALUE)
501 if ((len = strlen (find_data.cFileName)) < size)
502 memcpy (buf, find_data.cFileName, len + 1);
503 else
504 len = 0;
505 FindClose (dir_handle);
507 return len;
510 /* Get long name for file, if possible (assumed to be absolute). */
511 BOOL
512 w32_get_long_filename (char * name, char * buf, int size)
514 char * o = buf;
515 char * p;
516 char * q;
517 char full[ MAX_PATH ];
518 int len;
520 len = strlen (name);
521 if (len >= MAX_PATH)
522 return FALSE;
524 /* Use local copy for destructive modification. */
525 memcpy (full, name, len+1);
526 unixtodos_filename (full);
528 /* Copy root part verbatim. */
529 len = parse_root (full, &p);
530 memcpy (o, full, len);
531 o += len;
532 *o = '\0';
533 size -= len;
535 while (p != NULL && *p)
537 q = p;
538 p = strchr (q, '\\');
539 if (p) *p = '\0';
540 len = get_long_basename (full, o, size);
541 if (len > 0)
543 o += len;
544 size -= len;
545 if (p != NULL)
547 *p++ = '\\';
548 if (size < 2)
549 return FALSE;
550 *o++ = '\\';
551 size--;
552 *o = '\0';
555 else
556 return FALSE;
559 return TRUE;
563 is_unc_volume (const char *filename)
565 const char *ptr = filename;
567 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
568 return 0;
570 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
571 return 0;
573 return 1;
576 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
578 int
579 sigsetmask (int signal_mask)
581 return 0;
584 int
585 sigmask (int sig)
587 return 0;
590 int
591 sigblock (int sig)
593 return 0;
596 int
597 sigunblock (int sig)
599 return 0;
602 int
603 setpgrp (int pid, int gid)
605 return 0;
608 int
609 alarm (int seconds)
611 return 0;
614 void
615 unrequest_sigio (void)
617 return;
620 void
621 request_sigio (void)
623 return;
626 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
628 LPBYTE
629 w32_get_resource (key, lpdwtype)
630 char *key;
631 LPDWORD lpdwtype;
633 LPBYTE lpvalue;
634 HKEY hrootkey = NULL;
635 DWORD cbData;
636 BOOL ok = FALSE;
638 /* Check both the current user and the local machine to see if
639 we have any resources. */
641 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
643 lpvalue = NULL;
645 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
646 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
647 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
649 return (lpvalue);
652 if (lpvalue) xfree (lpvalue);
654 RegCloseKey (hrootkey);
657 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
659 lpvalue = NULL;
661 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
662 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
663 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
665 return (lpvalue);
668 if (lpvalue) xfree (lpvalue);
670 RegCloseKey (hrootkey);
673 return (NULL);
676 char *get_emacs_configuration (void);
677 extern Lisp_Object Vsystem_configuration;
679 void
680 init_environment (char ** argv)
682 static const char * const tempdirs[] = {
683 "$TMPDIR", "$TEMP", "$TMP", "c:/"
685 int i;
686 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
688 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
689 temporary files and assume "/tmp" if $TMPDIR is unset, which
690 will break on DOS/Windows. Refuse to work if we cannot find
691 a directory, not even "c:/", usable for that purpose. */
692 for (i = 0; i < imax ; i++)
694 const char *tmp = tempdirs[i];
696 if (*tmp == '$')
697 tmp = getenv (tmp + 1);
698 /* Note that `access' can lie to us if the directory resides on a
699 read-only filesystem, like CD-ROM or a write-protected floppy.
700 The only way to be really sure is to actually create a file and
701 see if it succeeds. But I think that's too much to ask. */
702 if (tmp && _access (tmp, D_OK) == 0)
704 char * var = alloca (strlen (tmp) + 8);
705 sprintf (var, "TMPDIR=%s", tmp);
706 _putenv (strdup (var));
707 break;
710 if (i >= imax)
711 cmd_error_internal
712 (Fcons (Qerror,
713 Fcons (build_string ("no usable temporary directories found!!"),
714 Qnil)),
715 "While setting TMPDIR: ");
717 /* Check for environment variables and use registry settings if they
718 don't exist. Fallback on default values where applicable. */
720 int i;
721 LPBYTE lpval;
722 DWORD dwType;
723 char locale_name[32];
725 static struct env_entry
727 char * name;
728 char * def_value;
729 } env_vars[] =
731 {"HOME", "C:/"},
732 {"PRELOAD_WINSOCK", NULL},
733 {"emacs_dir", "C:/emacs"},
734 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/../site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
735 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
736 {"EMACSDATA", "%emacs_dir%/etc"},
737 {"EMACSPATH", "%emacs_dir%/bin"},
738 {"EMACSLOCKDIR", "%emacs_dir%/lock"},
739 /* We no longer set INFOPATH because Info-default-directory-list
740 is then ignored. */
741 /* {"INFOPATH", "%emacs_dir%/info"}, */
742 {"EMACSDOC", "%emacs_dir%/etc"},
743 {"TERM", "cmd"},
744 {"LANG", NULL},
747 /* Get default locale info and use it for LANG. */
748 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
749 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
750 locale_name, sizeof (locale_name)))
752 for (i = 0; i < (sizeof (env_vars) / sizeof (env_vars[0])); i++)
754 if (strcmp (env_vars[i].name, "LANG") == 0)
756 env_vars[i].def_value = locale_name;
757 break;
762 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
764 /* Treat emacs_dir specially: set it unconditionally based on our
765 location, if it appears that we are running from the bin subdir
766 of a standard installation. */
768 char *p;
769 char modname[MAX_PATH];
771 if (!GetModuleFileName (NULL, modname, MAX_PATH))
772 abort ();
773 if ((p = strrchr (modname, '\\')) == NULL)
774 abort ();
775 *p = 0;
777 if ((p = strrchr (modname, '\\')) && stricmp (p, "\\bin") == 0)
779 char buf[SET_ENV_BUF_SIZE];
781 *p = 0;
782 for (p = modname; *p; p++)
783 if (*p == '\\') *p = '/';
785 _snprintf (buf, sizeof(buf)-1, "emacs_dir=%s", modname);
786 _putenv (strdup (buf));
790 for (i = 0; i < (sizeof (env_vars) / sizeof (env_vars[0])); i++)
792 if (!getenv (env_vars[i].name))
794 int dont_free = 0;
796 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL)
798 lpval = env_vars[i].def_value;
799 dwType = REG_EXPAND_SZ;
800 dont_free = 1;
803 if (lpval)
805 if (dwType == REG_EXPAND_SZ)
807 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
809 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof(buf1));
810 _snprintf (buf2, sizeof(buf2)-1, "%s=%s", env_vars[i].name, buf1);
811 _putenv (strdup (buf2));
813 else if (dwType == REG_SZ)
815 char buf[SET_ENV_BUF_SIZE];
817 _snprintf (buf, sizeof(buf)-1, "%s=%s", env_vars[i].name, lpval);
818 _putenv (strdup (buf));
821 if (!dont_free)
822 xfree (lpval);
828 /* Rebuild system configuration to reflect invoking system. */
829 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
831 /* Another special case: on NT, the PATH variable is actually named
832 "Path" although cmd.exe (perhaps NT itself) arranges for
833 environment variable lookup and setting to be case insensitive.
834 However, Emacs assumes a fully case sensitive environment, so we
835 need to change "Path" to "PATH" to match the expectations of
836 various elisp packages. We do this by the sneaky method of
837 modifying the string in the C runtime environ entry.
839 The same applies to COMSPEC. */
841 char ** envp;
843 for (envp = environ; *envp; envp++)
844 if (_strnicmp (*envp, "PATH=", 5) == 0)
845 memcpy (*envp, "PATH=", 5);
846 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
847 memcpy (*envp, "COMSPEC=", 8);
850 /* Remember the initial working directory for getwd, then make the
851 real wd be the location of emacs.exe to avoid conflicts when
852 renaming or deleting directories. (We also don't call chdir when
853 running subprocesses for the same reason.) */
854 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
855 abort ();
858 char *p;
859 static char modname[MAX_PATH];
861 if (!GetModuleFileName (NULL, modname, MAX_PATH))
862 abort ();
863 if ((p = strrchr (modname, '\\')) == NULL)
864 abort ();
865 *p = 0;
867 SetCurrentDirectory (modname);
869 /* Ensure argv[0] has the full path to Emacs. */
870 *p = '\\';
871 argv[0] = modname;
874 /* Determine if there is a middle mouse button, to allow parse_button
875 to decide whether right mouse events should be mouse-2 or
876 mouse-3. */
877 XSETINT (Vw32_num_mouse_buttons, GetSystemMetrics (SM_CMOUSEBUTTONS));
879 init_user_info ();
882 char *
883 emacs_root_dir (void)
885 static char root_dir[FILENAME_MAX];
886 const char *p;
888 p = getenv ("emacs_dir");
889 if (p == NULL)
890 abort ();
891 strcpy (root_dir, p);
892 root_dir[parse_root (root_dir, NULL)] = '\0';
893 dostounix_filename (root_dir);
894 return root_dir;
897 /* We don't have scripts to automatically determine the system configuration
898 for Emacs before it's compiled, and we don't want to have to make the
899 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
900 routine. */
902 char *
903 get_emacs_configuration (void)
905 char *arch, *oem, *os;
906 int build_num;
907 static char configuration_buffer[32];
909 /* Determine the processor type. */
910 switch (get_processor_type ())
913 #ifdef PROCESSOR_INTEL_386
914 case PROCESSOR_INTEL_386:
915 case PROCESSOR_INTEL_486:
916 case PROCESSOR_INTEL_PENTIUM:
917 arch = "i386";
918 break;
919 #endif
921 #ifdef PROCESSOR_INTEL_860
922 case PROCESSOR_INTEL_860:
923 arch = "i860";
924 break;
925 #endif
927 #ifdef PROCESSOR_MIPS_R2000
928 case PROCESSOR_MIPS_R2000:
929 case PROCESSOR_MIPS_R3000:
930 case PROCESSOR_MIPS_R4000:
931 arch = "mips";
932 break;
933 #endif
935 #ifdef PROCESSOR_ALPHA_21064
936 case PROCESSOR_ALPHA_21064:
937 arch = "alpha";
938 break;
939 #endif
941 default:
942 arch = "unknown";
943 break;
946 /* Use the OEM field to reflect the compiler/library combination. */
947 #ifdef _MSC_VER
948 #define COMPILER_NAME "msvc"
949 #else
950 #ifdef __GNUC__
951 #define COMPILER_NAME "mingw"
952 #else
953 #define COMPILER_NAME "unknown"
954 #endif
955 #endif
956 oem = COMPILER_NAME;
958 switch (osinfo_cache.dwPlatformId) {
959 case VER_PLATFORM_WIN32_NT:
960 os = "nt";
961 build_num = osinfo_cache.dwBuildNumber;
962 break;
963 case VER_PLATFORM_WIN32_WINDOWS:
964 if (osinfo_cache.dwMinorVersion == 0) {
965 os = "windows95";
966 } else {
967 os = "windows98";
969 build_num = LOWORD (osinfo_cache.dwBuildNumber);
970 break;
971 case VER_PLATFORM_WIN32s:
972 /* Not supported, should not happen. */
973 os = "windows32s";
974 build_num = LOWORD (osinfo_cache.dwBuildNumber);
975 break;
976 default:
977 os = "unknown";
978 build_num = 0;
979 break;
982 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
983 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
984 get_w32_major_version (), get_w32_minor_version (), build_num);
985 } else {
986 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
989 return configuration_buffer;
992 char *
993 get_emacs_configuration_options (void)
995 static char options_buffer[256];
997 /* Work out the effective configure options for this build. */
998 #ifdef _MSC_VER
999 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1000 #else
1001 #ifdef __GNUC__
1002 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1003 #else
1004 #define COMPILER_VERSION ""
1005 #endif
1006 #endif
1008 sprintf (options_buffer, COMPILER_VERSION);
1009 #ifdef EMACSDEBUG
1010 strcat (options_buffer, " --no-opt");
1011 #endif
1012 #ifdef USER_CFLAGS
1013 strcat (options_buffer, " --cflags");
1014 strcat (options_buffer, USER_CFLAGS);
1015 #endif
1016 #ifdef USER_LDFLAGS
1017 strcat (options_buffer, " --ldflags");
1018 strcat (options_buffer, USER_LDFLAGS);
1019 #endif
1020 return options_buffer;
1024 #include <sys/timeb.h>
1026 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1027 void
1028 gettimeofday (struct timeval *tv, struct timezone *tz)
1030 struct timeb tb;
1031 _ftime (&tb);
1033 tv->tv_sec = tb.time;
1034 tv->tv_usec = tb.millitm * 1000L;
1035 if (tz)
1037 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
1038 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
1042 /* ------------------------------------------------------------------------- */
1043 /* IO support and wrapper functions for W32 API. */
1044 /* ------------------------------------------------------------------------- */
1046 /* Place a wrapper around the MSVC version of ctime. It returns NULL
1047 on network directories, so we handle that case here.
1048 (Ulrich Leodolter, 1/11/95). */
1049 char *
1050 sys_ctime (const time_t *t)
1052 char *str = (char *) ctime (t);
1053 return (str ? str : "Sun Jan 01 00:00:00 1970");
1056 /* Emulate sleep...we could have done this with a define, but that
1057 would necessitate including windows.h in the files that used it.
1058 This is much easier. */
1059 void
1060 sys_sleep (int seconds)
1062 Sleep (seconds * 1000);
1065 /* Internal MSVC functions for low-level descriptor munging */
1066 extern int __cdecl _set_osfhnd (int fd, long h);
1067 extern int __cdecl _free_osfhnd (int fd);
1069 /* parallel array of private info on file handles */
1070 filedesc fd_info [ MAXDESC ];
1072 typedef struct volume_info_data {
1073 struct volume_info_data * next;
1075 /* time when info was obtained */
1076 DWORD timestamp;
1078 /* actual volume info */
1079 char * root_dir;
1080 DWORD serialnum;
1081 DWORD maxcomp;
1082 DWORD flags;
1083 char * name;
1084 char * type;
1085 } volume_info_data;
1087 /* Global referenced by various functions. */
1088 static volume_info_data volume_info;
1090 /* Vector to indicate which drives are local and fixed (for which cached
1091 data never expires). */
1092 static BOOL fixed_drives[26];
1094 /* Consider cached volume information to be stale if older than 10s,
1095 at least for non-local drives. Info for fixed drives is never stale. */
1096 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
1097 #define VOLINFO_STILL_VALID( root_dir, info ) \
1098 ( ( isalpha (root_dir[0]) && \
1099 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
1100 || GetTickCount () - info->timestamp < 10000 )
1102 /* Cache support functions. */
1104 /* Simple linked list with linear search is sufficient. */
1105 static volume_info_data *volume_cache = NULL;
1107 static volume_info_data *
1108 lookup_volume_info (char * root_dir)
1110 volume_info_data * info;
1112 for (info = volume_cache; info; info = info->next)
1113 if (stricmp (info->root_dir, root_dir) == 0)
1114 break;
1115 return info;
1118 static void
1119 add_volume_info (char * root_dir, volume_info_data * info)
1121 info->root_dir = xstrdup (root_dir);
1122 info->next = volume_cache;
1123 volume_cache = info;
1127 /* Wrapper for GetVolumeInformation, which uses caching to avoid
1128 performance penalty (~2ms on 486 for local drives, 7.5ms for local
1129 cdrom drive, ~5-10ms or more for remote drives on LAN). */
1130 volume_info_data *
1131 GetCachedVolumeInformation (char * root_dir)
1133 volume_info_data * info;
1134 char default_root[ MAX_PATH ];
1136 /* NULL for root_dir means use root from current directory. */
1137 if (root_dir == NULL)
1139 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
1140 return NULL;
1141 parse_root (default_root, &root_dir);
1142 *root_dir = 0;
1143 root_dir = default_root;
1146 /* Local fixed drives can be cached permanently. Removable drives
1147 cannot be cached permanently, since the volume name and serial
1148 number (if nothing else) can change. Remote drives should be
1149 treated as if they are removable, since there is no sure way to
1150 tell whether they are or not. Also, the UNC association of drive
1151 letters mapped to remote volumes can be changed at any time (even
1152 by other processes) without notice.
1154 As a compromise, so we can benefit from caching info for remote
1155 volumes, we use a simple expiry mechanism to invalidate cache
1156 entries that are more than ten seconds old. */
1158 #if 0
1159 /* No point doing this, because WNetGetConnection is even slower than
1160 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
1161 GetDriveType is about the only call of this type which does not
1162 involve network access, and so is extremely quick). */
1164 /* Map drive letter to UNC if remote. */
1165 if ( isalpha( root_dir[0] ) && !fixed[ DRIVE_INDEX( root_dir[0] ) ] )
1167 char remote_name[ 256 ];
1168 char drive[3] = { root_dir[0], ':' };
1170 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
1171 == NO_ERROR)
1172 /* do something */ ;
1174 #endif
1176 info = lookup_volume_info (root_dir);
1178 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
1180 char name[ 256 ];
1181 DWORD serialnum;
1182 DWORD maxcomp;
1183 DWORD flags;
1184 char type[ 256 ];
1186 /* Info is not cached, or is stale. */
1187 if (!GetVolumeInformation (root_dir,
1188 name, sizeof (name),
1189 &serialnum,
1190 &maxcomp,
1191 &flags,
1192 type, sizeof (type)))
1193 return NULL;
1195 /* Cache the volume information for future use, overwriting existing
1196 entry if present. */
1197 if (info == NULL)
1199 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
1200 add_volume_info (root_dir, info);
1202 else
1204 xfree (info->name);
1205 xfree (info->type);
1208 info->name = xstrdup (name);
1209 info->serialnum = serialnum;
1210 info->maxcomp = maxcomp;
1211 info->flags = flags;
1212 info->type = xstrdup (type);
1213 info->timestamp = GetTickCount ();
1216 return info;
1219 /* Get information on the volume where name is held; set path pointer to
1220 start of pathname in name (past UNC header\volume header if present). */
1222 get_volume_info (const char * name, const char ** pPath)
1224 char temp[MAX_PATH];
1225 char *rootname = NULL; /* default to current volume */
1226 volume_info_data * info;
1228 if (name == NULL)
1229 return FALSE;
1231 /* find the root name of the volume if given */
1232 if (isalpha (name[0]) && name[1] == ':')
1234 rootname = temp;
1235 temp[0] = *name++;
1236 temp[1] = *name++;
1237 temp[2] = '\\';
1238 temp[3] = 0;
1240 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1242 char *str = temp;
1243 int slashes = 4;
1244 rootname = temp;
1247 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1248 break;
1249 *str++ = *name++;
1251 while ( *name );
1253 *str++ = '\\';
1254 *str = 0;
1257 if (pPath)
1258 *pPath = name;
1260 info = GetCachedVolumeInformation (rootname);
1261 if (info != NULL)
1263 /* Set global referenced by other functions. */
1264 volume_info = *info;
1265 return TRUE;
1267 return FALSE;
1270 /* Determine if volume is FAT format (ie. only supports short 8.3
1271 names); also set path pointer to start of pathname in name. */
1273 is_fat_volume (const char * name, const char ** pPath)
1275 if (get_volume_info (name, pPath))
1276 return (volume_info.maxcomp == 12);
1277 return FALSE;
1280 /* Map filename to a legal 8.3 name if necessary. */
1281 const char *
1282 map_w32_filename (const char * name, const char ** pPath)
1284 static char shortname[MAX_PATH];
1285 char * str = shortname;
1286 char c;
1287 char * path;
1288 const char * save_name = name;
1290 if (strlen (name) >= MAX_PATH)
1292 /* Return a filename which will cause callers to fail. */
1293 strcpy (shortname, "?");
1294 return shortname;
1297 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
1299 register int left = 8; /* maximum number of chars in part */
1300 register int extn = 0; /* extension added? */
1301 register int dots = 2; /* maximum number of dots allowed */
1303 while (name < path)
1304 *str++ = *name++; /* skip past UNC header */
1306 while ((c = *name++))
1308 switch ( c )
1310 case '\\':
1311 case '/':
1312 *str++ = '\\';
1313 extn = 0; /* reset extension flags */
1314 dots = 2; /* max 2 dots */
1315 left = 8; /* max length 8 for main part */
1316 break;
1317 case ':':
1318 *str++ = ':';
1319 extn = 0; /* reset extension flags */
1320 dots = 2; /* max 2 dots */
1321 left = 8; /* max length 8 for main part */
1322 break;
1323 case '.':
1324 if ( dots )
1326 /* Convert path components of the form .xxx to _xxx,
1327 but leave . and .. as they are. This allows .emacs
1328 to be read as _emacs, for example. */
1330 if (! *name ||
1331 *name == '.' ||
1332 IS_DIRECTORY_SEP (*name))
1334 *str++ = '.';
1335 dots--;
1337 else
1339 *str++ = '_';
1340 left--;
1341 dots = 0;
1344 else if ( !extn )
1346 *str++ = '.';
1347 extn = 1; /* we've got an extension */
1348 left = 3; /* 3 chars in extension */
1350 else
1352 /* any embedded dots after the first are converted to _ */
1353 *str++ = '_';
1355 break;
1356 case '~':
1357 case '#': /* don't lose these, they're important */
1358 if ( ! left )
1359 str[-1] = c; /* replace last character of part */
1360 /* FALLTHRU */
1361 default:
1362 if ( left )
1364 *str++ = tolower (c); /* map to lower case (looks nicer) */
1365 left--;
1366 dots = 0; /* started a path component */
1368 break;
1371 *str = '\0';
1373 else
1375 strcpy (shortname, name);
1376 unixtodos_filename (shortname);
1379 if (pPath)
1380 *pPath = shortname + (path - save_name);
1382 return shortname;
1385 static int
1386 is_exec (const char * name)
1388 char * p = strrchr (name, '.');
1389 return
1390 (p != NULL
1391 && (stricmp (p, ".exe") == 0 ||
1392 stricmp (p, ".com") == 0 ||
1393 stricmp (p, ".bat") == 0 ||
1394 stricmp (p, ".cmd") == 0));
1397 /* Emulate the Unix directory procedures opendir, closedir,
1398 and readdir. We can't use the procedures supplied in sysdep.c,
1399 so we provide them here. */
1401 struct direct dir_static; /* simulated directory contents */
1402 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
1403 static int dir_is_fat;
1404 static char dir_pathname[MAXPATHLEN+1];
1405 static WIN32_FIND_DATA dir_find_data;
1407 /* Support shares on a network resource as subdirectories of a read-only
1408 root directory. */
1409 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
1410 HANDLE open_unc_volume (char *);
1411 char *read_unc_volume (HANDLE, char *, int);
1412 void close_unc_volume (HANDLE);
1414 DIR *
1415 opendir (char *filename)
1417 DIR *dirp;
1419 /* Opening is done by FindFirstFile. However, a read is inherent to
1420 this operation, so we defer the open until read time. */
1422 if (dir_find_handle != INVALID_HANDLE_VALUE)
1423 return NULL;
1424 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1425 return NULL;
1427 if (is_unc_volume (filename))
1429 wnet_enum_handle = open_unc_volume (filename);
1430 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
1431 return NULL;
1434 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
1435 return NULL;
1437 dirp->dd_fd = 0;
1438 dirp->dd_loc = 0;
1439 dirp->dd_size = 0;
1441 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
1442 dir_pathname[MAXPATHLEN] = '\0';
1443 dir_is_fat = is_fat_volume (filename, NULL);
1445 return dirp;
1448 void
1449 closedir (DIR *dirp)
1451 /* If we have a find-handle open, close it. */
1452 if (dir_find_handle != INVALID_HANDLE_VALUE)
1454 FindClose (dir_find_handle);
1455 dir_find_handle = INVALID_HANDLE_VALUE;
1457 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1459 close_unc_volume (wnet_enum_handle);
1460 wnet_enum_handle = INVALID_HANDLE_VALUE;
1462 xfree ((char *) dirp);
1465 struct direct *
1466 readdir (DIR *dirp)
1468 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1470 if (!read_unc_volume (wnet_enum_handle,
1471 dir_find_data.cFileName,
1472 MAX_PATH))
1473 return NULL;
1475 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1476 else if (dir_find_handle == INVALID_HANDLE_VALUE)
1478 char filename[MAXNAMLEN + 3];
1479 int ln;
1481 strcpy (filename, dir_pathname);
1482 ln = strlen (filename) - 1;
1483 if (!IS_DIRECTORY_SEP (filename[ln]))
1484 strcat (filename, "\\");
1485 strcat (filename, "*");
1487 dir_find_handle = FindFirstFile (filename, &dir_find_data);
1489 if (dir_find_handle == INVALID_HANDLE_VALUE)
1490 return NULL;
1492 else
1494 if (!FindNextFile (dir_find_handle, &dir_find_data))
1495 return NULL;
1498 /* Emacs never uses this value, so don't bother making it match
1499 value returned by stat(). */
1500 dir_static.d_ino = 1;
1502 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
1503 dir_static.d_namlen - dir_static.d_namlen % 4;
1505 dir_static.d_namlen = strlen (dir_find_data.cFileName);
1506 strcpy (dir_static.d_name, dir_find_data.cFileName);
1507 if (dir_is_fat)
1508 _strlwr (dir_static.d_name);
1509 else if (!NILP (Vw32_downcase_file_names))
1511 register char *p;
1512 for (p = dir_static.d_name; *p; p++)
1513 if (*p >= 'a' && *p <= 'z')
1514 break;
1515 if (!*p)
1516 _strlwr (dir_static.d_name);
1519 return &dir_static;
1522 HANDLE
1523 open_unc_volume (char *path)
1525 NETRESOURCE nr;
1526 HANDLE henum;
1527 int result;
1529 nr.dwScope = RESOURCE_GLOBALNET;
1530 nr.dwType = RESOURCETYPE_DISK;
1531 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
1532 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
1533 nr.lpLocalName = NULL;
1534 nr.lpRemoteName = map_w32_filename (path, NULL);
1535 nr.lpComment = NULL;
1536 nr.lpProvider = NULL;
1538 result = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
1539 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
1541 if (result == NO_ERROR)
1542 return henum;
1543 else
1544 return INVALID_HANDLE_VALUE;
1547 char *
1548 read_unc_volume (HANDLE henum, char *readbuf, int size)
1550 DWORD count;
1551 int result;
1552 DWORD bufsize = 512;
1553 char *buffer;
1554 char *ptr;
1556 count = 1;
1557 buffer = alloca (bufsize);
1558 result = WNetEnumResource (wnet_enum_handle, &count, buffer, &bufsize);
1559 if (result != NO_ERROR)
1560 return NULL;
1562 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
1563 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
1564 ptr += 2;
1565 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
1566 ptr++;
1568 strncpy (readbuf, ptr, size);
1569 return readbuf;
1572 void
1573 close_unc_volume (HANDLE henum)
1575 if (henum != INVALID_HANDLE_VALUE)
1576 WNetCloseEnum (henum);
1579 DWORD
1580 unc_volume_file_attributes (char *path)
1582 HANDLE henum;
1583 DWORD attrs;
1585 henum = open_unc_volume (path);
1586 if (henum == INVALID_HANDLE_VALUE)
1587 return -1;
1589 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
1591 close_unc_volume (henum);
1593 return attrs;
1597 /* Shadow some MSVC runtime functions to map requests for long filenames
1598 to reasonable short names if necessary. This was originally added to
1599 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1600 long file names. */
1603 sys_access (const char * path, int mode)
1605 DWORD attributes;
1607 /* MSVC implementation doesn't recognize D_OK. */
1608 path = map_w32_filename (path, NULL);
1609 if (is_unc_volume (path))
1611 attributes = unc_volume_file_attributes (path);
1612 if (attributes == -1) {
1613 errno = EACCES;
1614 return -1;
1617 else if ((attributes = GetFileAttributes (path)) == -1)
1619 /* Should try mapping GetLastError to errno; for now just indicate
1620 that path doesn't exist. */
1621 errno = EACCES;
1622 return -1;
1624 if ((mode & X_OK) != 0 && !is_exec (path))
1626 errno = EACCES;
1627 return -1;
1629 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
1631 errno = EACCES;
1632 return -1;
1634 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1636 errno = EACCES;
1637 return -1;
1639 return 0;
1643 sys_chdir (const char * path)
1645 return _chdir (map_w32_filename (path, NULL));
1649 sys_chmod (const char * path, int mode)
1651 return _chmod (map_w32_filename (path, NULL), mode);
1655 sys_creat (const char * path, int mode)
1657 return _creat (map_w32_filename (path, NULL), mode);
1660 FILE *
1661 sys_fopen(const char * path, const char * mode)
1663 int fd;
1664 int oflag;
1665 const char * mode_save = mode;
1667 /* Force all file handles to be non-inheritable. This is necessary to
1668 ensure child processes don't unwittingly inherit handles that might
1669 prevent future file access. */
1671 if (mode[0] == 'r')
1672 oflag = O_RDONLY;
1673 else if (mode[0] == 'w' || mode[0] == 'a')
1674 oflag = O_WRONLY | O_CREAT | O_TRUNC;
1675 else
1676 return NULL;
1678 /* Only do simplistic option parsing. */
1679 while (*++mode)
1680 if (mode[0] == '+')
1682 oflag &= ~(O_RDONLY | O_WRONLY);
1683 oflag |= O_RDWR;
1685 else if (mode[0] == 'b')
1687 oflag &= ~O_TEXT;
1688 oflag |= O_BINARY;
1690 else if (mode[0] == 't')
1692 oflag &= ~O_BINARY;
1693 oflag |= O_TEXT;
1695 else break;
1697 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
1698 if (fd < 0)
1699 return NULL;
1701 return _fdopen (fd, mode_save);
1704 /* This only works on NTFS volumes, but is useful to have. */
1706 sys_link (const char * old, const char * new)
1708 HANDLE fileh;
1709 int result = -1;
1710 char oldname[MAX_PATH], newname[MAX_PATH];
1712 if (old == NULL || new == NULL)
1714 errno = ENOENT;
1715 return -1;
1718 strcpy (oldname, map_w32_filename (old, NULL));
1719 strcpy (newname, map_w32_filename (new, NULL));
1721 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
1722 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1723 if (fileh != INVALID_HANDLE_VALUE)
1725 int wlen;
1727 /* Confusingly, the "alternate" stream name field does not apply
1728 when restoring a hard link, and instead contains the actual
1729 stream data for the link (ie. the name of the link to create).
1730 The WIN32_STREAM_ID structure before the cStreamName field is
1731 the stream header, which is then immediately followed by the
1732 stream data. */
1734 struct {
1735 WIN32_STREAM_ID wid;
1736 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
1737 } data;
1739 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
1740 data.wid.cStreamName, MAX_PATH);
1741 if (wlen > 0)
1743 LPVOID context = NULL;
1744 DWORD wbytes = 0;
1746 data.wid.dwStreamId = BACKUP_LINK;
1747 data.wid.dwStreamAttributes = 0;
1748 data.wid.Size.LowPart = wlen * sizeof(WCHAR);
1749 data.wid.Size.HighPart = 0;
1750 data.wid.dwStreamNameSize = 0;
1752 if (BackupWrite (fileh, (LPBYTE)&data,
1753 offsetof (WIN32_STREAM_ID, cStreamName)
1754 + data.wid.Size.LowPart,
1755 &wbytes, FALSE, FALSE, &context)
1756 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
1758 /* succeeded */
1759 result = 0;
1761 else
1763 /* Should try mapping GetLastError to errno; for now just
1764 indicate a general error (eg. links not supported). */
1765 errno = EINVAL; // perhaps EMLINK?
1769 CloseHandle (fileh);
1771 else
1772 errno = ENOENT;
1774 return result;
1778 sys_mkdir (const char * path)
1780 return _mkdir (map_w32_filename (path, NULL));
1783 /* Because of long name mapping issues, we need to implement this
1784 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1785 a unique name, instead of setting the input template to an empty
1786 string.
1788 Standard algorithm seems to be use pid or tid with a letter on the
1789 front (in place of the 6 X's) and cycle through the letters to find a
1790 unique name. We extend that to allow any reasonable character as the
1791 first of the 6 X's. */
1792 char *
1793 sys_mktemp (char * template)
1795 char * p;
1796 int i;
1797 unsigned uid = GetCurrentThreadId ();
1798 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1800 if (template == NULL)
1801 return NULL;
1802 p = template + strlen (template);
1803 i = 5;
1804 /* replace up to the last 5 X's with uid in decimal */
1805 while (--p >= template && p[0] == 'X' && --i >= 0)
1807 p[0] = '0' + uid % 10;
1808 uid /= 10;
1811 if (i < 0 && p[0] == 'X')
1813 i = 0;
1816 int save_errno = errno;
1817 p[0] = first_char[i];
1818 if (sys_access (template, 0) < 0)
1820 errno = save_errno;
1821 return template;
1824 while (++i < sizeof (first_char));
1827 /* Template is badly formed or else we can't generate a unique name,
1828 so return empty string */
1829 template[0] = 0;
1830 return template;
1834 sys_open (const char * path, int oflag, int mode)
1836 const char* mpath = map_w32_filename (path, NULL);
1837 /* Try to open file without _O_CREAT, to be able to write to hidden
1838 and system files. Force all file handles to be
1839 non-inheritable. */
1840 int res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
1841 if (res >= 0)
1842 return res;
1843 return _open (mpath, oflag | _O_NOINHERIT, mode);
1847 sys_rename (const char * oldname, const char * newname)
1849 BOOL result;
1850 char temp[MAX_PATH];
1852 /* MoveFile on Windows 95 doesn't correctly change the short file name
1853 alias in a number of circumstances (it is not easy to predict when
1854 just by looking at oldname and newname, unfortunately). In these
1855 cases, renaming through a temporary name avoids the problem.
1857 A second problem on Windows 95 is that renaming through a temp name when
1858 newname is uppercase fails (the final long name ends up in
1859 lowercase, although the short alias might be uppercase) UNLESS the
1860 long temp name is not 8.3.
1862 So, on Windows 95 we always rename through a temp name, and we make sure
1863 the temp name has a long extension to ensure correct renaming. */
1865 strcpy (temp, map_w32_filename (oldname, NULL));
1867 if (os_subtype == OS_WIN95)
1869 char * o;
1870 char * p;
1871 int i = 0;
1873 oldname = map_w32_filename (oldname, NULL);
1874 if (o = strrchr (oldname, '\\'))
1875 o++;
1876 else
1877 o = (char *) oldname;
1879 if (p = strrchr (temp, '\\'))
1880 p++;
1881 else
1882 p = temp;
1886 /* Force temp name to require a manufactured 8.3 alias - this
1887 seems to make the second rename work properly. */
1888 sprintf (p, "_.%s.%u", o, i);
1889 i++;
1890 result = rename (oldname, temp);
1892 /* This loop must surely terminate! */
1893 while (result < 0 && errno == EEXIST);
1894 if (result < 0)
1895 return -1;
1898 /* Emulate Unix behaviour - newname is deleted if it already exists
1899 (at least if it is a file; don't do this for directories).
1901 Since we mustn't do this if we are just changing the case of the
1902 file name (we would end up deleting the file we are trying to
1903 rename!), we let rename detect if the destination file already
1904 exists - that way we avoid the possible pitfalls of trying to
1905 determine ourselves whether two names really refer to the same
1906 file, which is not always possible in the general case. (Consider
1907 all the permutations of shared or subst'd drives, etc.) */
1909 newname = map_w32_filename (newname, NULL);
1910 result = rename (temp, newname);
1912 if (result < 0
1913 && errno == EEXIST
1914 && _chmod (newname, 0666) == 0
1915 && _unlink (newname) == 0)
1916 result = rename (temp, newname);
1918 return result;
1922 sys_rmdir (const char * path)
1924 return _rmdir (map_w32_filename (path, NULL));
1928 sys_unlink (const char * path)
1930 path = map_w32_filename (path, NULL);
1932 /* On Unix, unlink works without write permission. */
1933 _chmod (path, 0666);
1934 return _unlink (path);
1937 static FILETIME utc_base_ft;
1938 static long double utc_base;
1939 static int init = 0;
1941 static time_t
1942 convert_time (FILETIME ft)
1944 long double ret;
1946 if (!init)
1948 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1949 SYSTEMTIME st;
1951 st.wYear = 1970;
1952 st.wMonth = 1;
1953 st.wDay = 1;
1954 st.wHour = 0;
1955 st.wMinute = 0;
1956 st.wSecond = 0;
1957 st.wMilliseconds = 0;
1959 SystemTimeToFileTime (&st, &utc_base_ft);
1960 utc_base = (long double) utc_base_ft.dwHighDateTime
1961 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1962 init = 1;
1965 if (CompareFileTime (&ft, &utc_base_ft) < 0)
1966 return 0;
1968 ret = (long double) ft.dwHighDateTime * 4096 * 1024 * 1024 + ft.dwLowDateTime;
1969 ret -= utc_base;
1970 return (time_t) (ret * 1e-7);
1973 void
1974 convert_from_time_t (time_t time, FILETIME * pft)
1976 long double tmp;
1978 if (!init)
1980 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1981 SYSTEMTIME st;
1983 st.wYear = 1970;
1984 st.wMonth = 1;
1985 st.wDay = 1;
1986 st.wHour = 0;
1987 st.wMinute = 0;
1988 st.wSecond = 0;
1989 st.wMilliseconds = 0;
1991 SystemTimeToFileTime (&st, &utc_base_ft);
1992 utc_base = (long double) utc_base_ft.dwHighDateTime
1993 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1994 init = 1;
1997 /* time in 100ns units since 1-Jan-1601 */
1998 tmp = (long double) time * 1e7 + utc_base;
1999 pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
2000 pft->dwLowDateTime = (DWORD) (tmp - (4096.0 * 1024 * 1024) * pft->dwHighDateTime);
2003 #if 0
2004 /* No reason to keep this; faking inode values either by hashing or even
2005 using the file index from GetInformationByHandle, is not perfect and
2006 so by default Emacs doesn't use the inode values on Windows.
2007 Instead, we now determine file-truename correctly (except for
2008 possible drive aliasing etc). */
2010 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
2011 static unsigned
2012 hashval (const unsigned char * str)
2014 unsigned h = 0;
2015 while (*str)
2017 h = (h << 4) + *str++;
2018 h ^= (h >> 28);
2020 return h;
2023 /* Return the hash value of the canonical pathname, excluding the
2024 drive/UNC header, to get a hopefully unique inode number. */
2025 static DWORD
2026 generate_inode_val (const char * name)
2028 char fullname[ MAX_PATH ];
2029 char * p;
2030 unsigned hash;
2032 /* Get the truly canonical filename, if it exists. (Note: this
2033 doesn't resolve aliasing due to subst commands, or recognise hard
2034 links. */
2035 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
2036 abort ();
2038 parse_root (fullname, &p);
2039 /* Normal W32 filesystems are still case insensitive. */
2040 _strlwr (p);
2041 return hashval (p);
2044 #endif
2046 /* MSVC stat function can't cope with UNC names and has other bugs, so
2047 replace it with our own. This also allows us to calculate consistent
2048 inode values without hacks in the main Emacs code. */
2050 stat (const char * path, struct stat * buf)
2052 char *name, *r;
2053 WIN32_FIND_DATA wfd;
2054 HANDLE fh;
2055 DWORD fake_inode;
2056 int permission;
2057 int len;
2058 int rootdir = FALSE;
2060 if (path == NULL || buf == NULL)
2062 errno = EFAULT;
2063 return -1;
2066 name = (char *) map_w32_filename (path, &path);
2067 /* must be valid filename, no wild cards or other invalid characters */
2068 if (strpbrk (name, "*?|<>\""))
2070 errno = ENOENT;
2071 return -1;
2074 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
2075 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
2076 if (IS_DIRECTORY_SEP (r[0]) && r[1] == '.' && r[2] == '.' && r[3] == '\0')
2078 r[1] = r[2] = '\0';
2081 /* Remove trailing directory separator, unless name is the root
2082 directory of a drive or UNC volume in which case ensure there
2083 is a trailing separator. */
2084 len = strlen (name);
2085 rootdir = (path >= name + len - 1
2086 && (IS_DIRECTORY_SEP (*path) || *path == 0));
2087 name = strcpy (alloca (len + 2), name);
2089 if (is_unc_volume (name))
2091 DWORD attrs = unc_volume_file_attributes (name);
2093 if (attrs == -1)
2094 return -1;
2096 memset (&wfd, 0, sizeof (wfd));
2097 wfd.dwFileAttributes = attrs;
2098 wfd.ftCreationTime = utc_base_ft;
2099 wfd.ftLastAccessTime = utc_base_ft;
2100 wfd.ftLastWriteTime = utc_base_ft;
2101 strcpy (wfd.cFileName, name);
2103 else if (rootdir)
2105 if (!IS_DIRECTORY_SEP (name[len-1]))
2106 strcat (name, "\\");
2107 if (GetDriveType (name) < 2)
2109 errno = ENOENT;
2110 return -1;
2112 memset (&wfd, 0, sizeof (wfd));
2113 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
2114 wfd.ftCreationTime = utc_base_ft;
2115 wfd.ftLastAccessTime = utc_base_ft;
2116 wfd.ftLastWriteTime = utc_base_ft;
2117 strcpy (wfd.cFileName, name);
2119 else
2121 if (IS_DIRECTORY_SEP (name[len-1]))
2122 name[len - 1] = 0;
2124 /* (This is hacky, but helps when doing file completions on
2125 network drives.) Optimize by using information available from
2126 active readdir if possible. */
2127 len = strlen (dir_pathname);
2128 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
2129 len--;
2130 if (dir_find_handle != INVALID_HANDLE_VALUE
2131 && strnicmp (name, dir_pathname, len) == 0
2132 && IS_DIRECTORY_SEP (name[len])
2133 && stricmp (name + len + 1, dir_static.d_name) == 0)
2135 /* This was the last entry returned by readdir. */
2136 wfd = dir_find_data;
2138 else
2140 fh = FindFirstFile (name, &wfd);
2141 if (fh == INVALID_HANDLE_VALUE)
2143 errno = ENOENT;
2144 return -1;
2146 FindClose (fh);
2150 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2152 buf->st_mode = _S_IFDIR;
2153 buf->st_nlink = 2; /* doesn't really matter */
2154 fake_inode = 0; /* this doesn't either I think */
2156 else if (!NILP (Vw32_get_true_file_attributes)
2157 /* No access rights required to get info. */
2158 && (fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING, 0, NULL))
2159 != INVALID_HANDLE_VALUE)
2161 /* This is more accurate in terms of gettting the correct number
2162 of links, but is quite slow (it is noticable when Emacs is
2163 making a list of file name completions). */
2164 BY_HANDLE_FILE_INFORMATION info;
2166 if (GetFileInformationByHandle (fh, &info))
2168 buf->st_nlink = info.nNumberOfLinks;
2169 /* Might as well use file index to fake inode values, but this
2170 is not guaranteed to be unique unless we keep a handle open
2171 all the time (even then there are situations where it is
2172 not unique). Reputedly, there are at most 48 bits of info
2173 (on NTFS, presumably less on FAT). */
2174 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
2176 else
2178 buf->st_nlink = 1;
2179 fake_inode = 0;
2182 switch (GetFileType (fh))
2184 case FILE_TYPE_DISK:
2185 buf->st_mode = _S_IFREG;
2186 break;
2187 case FILE_TYPE_PIPE:
2188 buf->st_mode = _S_IFIFO;
2189 break;
2190 case FILE_TYPE_CHAR:
2191 case FILE_TYPE_UNKNOWN:
2192 default:
2193 buf->st_mode = _S_IFCHR;
2195 CloseHandle (fh);
2197 else
2199 /* Don't bother to make this information more accurate. */
2200 buf->st_mode = _S_IFREG;
2201 buf->st_nlink = 1;
2202 fake_inode = 0;
2205 #if 0
2206 /* Not sure if there is any point in this. */
2207 if (!NILP (Vw32_generate_fake_inodes))
2208 fake_inode = generate_inode_val (name);
2209 else if (fake_inode == 0)
2211 /* For want of something better, try to make everything unique. */
2212 static DWORD gen_num = 0;
2213 fake_inode = ++gen_num;
2215 #endif
2217 /* MSVC defines _ino_t to be short; other libc's might not. */
2218 if (sizeof (buf->st_ino) == 2)
2219 buf->st_ino = fake_inode ^ (fake_inode >> 16);
2220 else
2221 buf->st_ino = fake_inode;
2223 /* consider files to belong to current user */
2224 buf->st_uid = the_passwd.pw_uid;
2225 buf->st_gid = the_passwd.pw_gid;
2227 /* volume_info is set indirectly by map_w32_filename */
2228 buf->st_dev = volume_info.serialnum;
2229 buf->st_rdev = volume_info.serialnum;
2232 buf->st_size = wfd.nFileSizeLow;
2234 /* Convert timestamps to Unix format. */
2235 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
2236 buf->st_atime = convert_time (wfd.ftLastAccessTime);
2237 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
2238 buf->st_ctime = convert_time (wfd.ftCreationTime);
2239 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
2241 /* determine rwx permissions */
2242 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2243 permission = _S_IREAD;
2244 else
2245 permission = _S_IREAD | _S_IWRITE;
2247 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2248 permission |= _S_IEXEC;
2249 else if (is_exec (name))
2250 permission |= _S_IEXEC;
2252 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
2254 return 0;
2257 /* Provide fstat and utime as well as stat for consistent handling of
2258 file timestamps. */
2260 fstat (int desc, struct stat * buf)
2262 HANDLE fh = (HANDLE) _get_osfhandle (desc);
2263 BY_HANDLE_FILE_INFORMATION info;
2264 DWORD fake_inode;
2265 int permission;
2267 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
2269 case FILE_TYPE_DISK:
2270 buf->st_mode = _S_IFREG;
2271 if (!GetFileInformationByHandle (fh, &info))
2273 errno = EACCES;
2274 return -1;
2276 break;
2277 case FILE_TYPE_PIPE:
2278 buf->st_mode = _S_IFIFO;
2279 goto non_disk;
2280 case FILE_TYPE_CHAR:
2281 case FILE_TYPE_UNKNOWN:
2282 default:
2283 buf->st_mode = _S_IFCHR;
2284 non_disk:
2285 memset (&info, 0, sizeof (info));
2286 info.dwFileAttributes = 0;
2287 info.ftCreationTime = utc_base_ft;
2288 info.ftLastAccessTime = utc_base_ft;
2289 info.ftLastWriteTime = utc_base_ft;
2292 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2294 buf->st_mode = _S_IFDIR;
2295 buf->st_nlink = 2; /* doesn't really matter */
2296 fake_inode = 0; /* this doesn't either I think */
2298 else
2300 buf->st_nlink = info.nNumberOfLinks;
2301 /* Might as well use file index to fake inode values, but this
2302 is not guaranteed to be unique unless we keep a handle open
2303 all the time (even then there are situations where it is
2304 not unique). Reputedly, there are at most 48 bits of info
2305 (on NTFS, presumably less on FAT). */
2306 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
2309 /* MSVC defines _ino_t to be short; other libc's might not. */
2310 if (sizeof (buf->st_ino) == 2)
2311 buf->st_ino = fake_inode ^ (fake_inode >> 16);
2312 else
2313 buf->st_ino = fake_inode;
2315 /* consider files to belong to current user */
2316 buf->st_uid = 0;
2317 buf->st_gid = 0;
2319 buf->st_dev = info.dwVolumeSerialNumber;
2320 buf->st_rdev = info.dwVolumeSerialNumber;
2322 buf->st_size = info.nFileSizeLow;
2324 /* Convert timestamps to Unix format. */
2325 buf->st_mtime = convert_time (info.ftLastWriteTime);
2326 buf->st_atime = convert_time (info.ftLastAccessTime);
2327 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
2328 buf->st_ctime = convert_time (info.ftCreationTime);
2329 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
2331 /* determine rwx permissions */
2332 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2333 permission = _S_IREAD;
2334 else
2335 permission = _S_IREAD | _S_IWRITE;
2337 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2338 permission |= _S_IEXEC;
2339 else
2341 #if 0 /* no way of knowing the filename */
2342 char * p = strrchr (name, '.');
2343 if (p != NULL &&
2344 (stricmp (p, ".exe") == 0 ||
2345 stricmp (p, ".com") == 0 ||
2346 stricmp (p, ".bat") == 0 ||
2347 stricmp (p, ".cmd") == 0))
2348 permission |= _S_IEXEC;
2349 #endif
2352 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
2354 return 0;
2358 utime (const char *name, struct utimbuf *times)
2360 struct utimbuf deftime;
2361 HANDLE fh;
2362 FILETIME mtime;
2363 FILETIME atime;
2365 if (times == NULL)
2367 deftime.modtime = deftime.actime = time (NULL);
2368 times = &deftime;
2371 /* Need write access to set times. */
2372 fh = CreateFile (name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
2373 0, OPEN_EXISTING, 0, NULL);
2374 if (fh)
2376 convert_from_time_t (times->actime, &atime);
2377 convert_from_time_t (times->modtime, &mtime);
2378 if (!SetFileTime (fh, NULL, &atime, &mtime))
2380 CloseHandle (fh);
2381 errno = EACCES;
2382 return -1;
2384 CloseHandle (fh);
2386 else
2388 errno = EINVAL;
2389 return -1;
2391 return 0;
2394 #ifdef HAVE_SOCKETS
2396 /* Wrappers for winsock functions to map between our file descriptors
2397 and winsock's handles; also set h_errno for convenience.
2399 To allow Emacs to run on systems which don't have winsock support
2400 installed, we dynamically link to winsock on startup if present, and
2401 otherwise provide the minimum necessary functionality
2402 (eg. gethostname). */
2404 /* function pointers for relevant socket functions */
2405 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
2406 void (PASCAL *pfn_WSASetLastError) (int iError);
2407 int (PASCAL *pfn_WSAGetLastError) (void);
2408 int (PASCAL *pfn_socket) (int af, int type, int protocol);
2409 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
2410 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
2411 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
2412 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
2413 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
2414 int (PASCAL *pfn_closesocket) (SOCKET s);
2415 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
2416 int (PASCAL *pfn_WSACleanup) (void);
2418 u_short (PASCAL *pfn_htons) (u_short hostshort);
2419 u_short (PASCAL *pfn_ntohs) (u_short netshort);
2420 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
2421 int (PASCAL *pfn_gethostname) (char * name, int namelen);
2422 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
2423 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
2425 /* SetHandleInformation is only needed to make sockets non-inheritable. */
2426 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
2427 #ifndef HANDLE_FLAG_INHERIT
2428 #define HANDLE_FLAG_INHERIT 1
2429 #endif
2431 HANDLE winsock_lib;
2432 static int winsock_inuse;
2434 BOOL
2435 term_winsock (void)
2437 if (winsock_lib != NULL && winsock_inuse == 0)
2439 /* Not sure what would cause WSAENETDOWN, or even if it can happen
2440 after WSAStartup returns successfully, but it seems reasonable
2441 to allow unloading winsock anyway in that case. */
2442 if (pfn_WSACleanup () == 0 ||
2443 pfn_WSAGetLastError () == WSAENETDOWN)
2445 if (FreeLibrary (winsock_lib))
2446 winsock_lib = NULL;
2447 return TRUE;
2450 return FALSE;
2453 BOOL
2454 init_winsock (int load_now)
2456 WSADATA winsockData;
2458 if (winsock_lib != NULL)
2459 return TRUE;
2461 pfn_SetHandleInformation = NULL;
2462 pfn_SetHandleInformation
2463 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2464 "SetHandleInformation");
2466 winsock_lib = LoadLibrary ("wsock32.dll");
2468 if (winsock_lib != NULL)
2470 /* dynamically link to socket functions */
2472 #define LOAD_PROC(fn) \
2473 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2474 goto fail;
2476 LOAD_PROC( WSAStartup );
2477 LOAD_PROC( WSASetLastError );
2478 LOAD_PROC( WSAGetLastError );
2479 LOAD_PROC( socket );
2480 LOAD_PROC( bind );
2481 LOAD_PROC( connect );
2482 LOAD_PROC( ioctlsocket );
2483 LOAD_PROC( recv );
2484 LOAD_PROC( send );
2485 LOAD_PROC( closesocket );
2486 LOAD_PROC( shutdown );
2487 LOAD_PROC( htons );
2488 LOAD_PROC( ntohs );
2489 LOAD_PROC( inet_addr );
2490 LOAD_PROC( gethostname );
2491 LOAD_PROC( gethostbyname );
2492 LOAD_PROC( getservbyname );
2493 LOAD_PROC( WSACleanup );
2495 #undef LOAD_PROC
2497 /* specify version 1.1 of winsock */
2498 if (pfn_WSAStartup (0x101, &winsockData) == 0)
2500 if (winsockData.wVersion != 0x101)
2501 goto fail;
2503 if (!load_now)
2505 /* Report that winsock exists and is usable, but leave
2506 socket functions disabled. I am assuming that calling
2507 WSAStartup does not require any network interaction,
2508 and in particular does not cause or require a dial-up
2509 connection to be established. */
2511 pfn_WSACleanup ();
2512 FreeLibrary (winsock_lib);
2513 winsock_lib = NULL;
2515 winsock_inuse = 0;
2516 return TRUE;
2519 fail:
2520 FreeLibrary (winsock_lib);
2521 winsock_lib = NULL;
2524 return FALSE;
2528 int h_errno = 0;
2530 /* function to set h_errno for compatability; map winsock error codes to
2531 normal system codes where they overlap (non-overlapping definitions
2532 are already in <sys/socket.h> */
2533 static void set_errno ()
2535 if (winsock_lib == NULL)
2536 h_errno = EINVAL;
2537 else
2538 h_errno = pfn_WSAGetLastError ();
2540 switch (h_errno)
2542 case WSAEACCES: h_errno = EACCES; break;
2543 case WSAEBADF: h_errno = EBADF; break;
2544 case WSAEFAULT: h_errno = EFAULT; break;
2545 case WSAEINTR: h_errno = EINTR; break;
2546 case WSAEINVAL: h_errno = EINVAL; break;
2547 case WSAEMFILE: h_errno = EMFILE; break;
2548 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
2549 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
2551 errno = h_errno;
2554 static void check_errno ()
2556 if (h_errno == 0 && winsock_lib != NULL)
2557 pfn_WSASetLastError (0);
2560 /* Extend strerror to handle the winsock-specific error codes. */
2561 struct {
2562 int errnum;
2563 char * msg;
2564 } _wsa_errlist[] = {
2565 WSAEINTR , "Interrupted function call",
2566 WSAEBADF , "Bad file descriptor",
2567 WSAEACCES , "Permission denied",
2568 WSAEFAULT , "Bad address",
2569 WSAEINVAL , "Invalid argument",
2570 WSAEMFILE , "Too many open files",
2572 WSAEWOULDBLOCK , "Resource temporarily unavailable",
2573 WSAEINPROGRESS , "Operation now in progress",
2574 WSAEALREADY , "Operation already in progress",
2575 WSAENOTSOCK , "Socket operation on non-socket",
2576 WSAEDESTADDRREQ , "Destination address required",
2577 WSAEMSGSIZE , "Message too long",
2578 WSAEPROTOTYPE , "Protocol wrong type for socket",
2579 WSAENOPROTOOPT , "Bad protocol option",
2580 WSAEPROTONOSUPPORT , "Protocol not supported",
2581 WSAESOCKTNOSUPPORT , "Socket type not supported",
2582 WSAEOPNOTSUPP , "Operation not supported",
2583 WSAEPFNOSUPPORT , "Protocol family not supported",
2584 WSAEAFNOSUPPORT , "Address family not supported by protocol family",
2585 WSAEADDRINUSE , "Address already in use",
2586 WSAEADDRNOTAVAIL , "Cannot assign requested address",
2587 WSAENETDOWN , "Network is down",
2588 WSAENETUNREACH , "Network is unreachable",
2589 WSAENETRESET , "Network dropped connection on reset",
2590 WSAECONNABORTED , "Software caused connection abort",
2591 WSAECONNRESET , "Connection reset by peer",
2592 WSAENOBUFS , "No buffer space available",
2593 WSAEISCONN , "Socket is already connected",
2594 WSAENOTCONN , "Socket is not connected",
2595 WSAESHUTDOWN , "Cannot send after socket shutdown",
2596 WSAETOOMANYREFS , "Too many references", /* not sure */
2597 WSAETIMEDOUT , "Connection timed out",
2598 WSAECONNREFUSED , "Connection refused",
2599 WSAELOOP , "Network loop", /* not sure */
2600 WSAENAMETOOLONG , "Name is too long",
2601 WSAEHOSTDOWN , "Host is down",
2602 WSAEHOSTUNREACH , "No route to host",
2603 WSAENOTEMPTY , "Buffer not empty", /* not sure */
2604 WSAEPROCLIM , "Too many processes",
2605 WSAEUSERS , "Too many users", /* not sure */
2606 WSAEDQUOT , "Double quote in host name", /* really not sure */
2607 WSAESTALE , "Data is stale", /* not sure */
2608 WSAEREMOTE , "Remote error", /* not sure */
2610 WSASYSNOTREADY , "Network subsystem is unavailable",
2611 WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range",
2612 WSANOTINITIALISED , "Winsock not initialized successfully",
2613 WSAEDISCON , "Graceful shutdown in progress",
2614 #ifdef WSAENOMORE
2615 WSAENOMORE , "No more operations allowed", /* not sure */
2616 WSAECANCELLED , "Operation cancelled", /* not sure */
2617 WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider",
2618 WSAEINVALIDPROVIDER , "Invalid service provider version number",
2619 WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider",
2620 WSASYSCALLFAILURE , "System call failured",
2621 WSASERVICE_NOT_FOUND , "Service not found", /* not sure */
2622 WSATYPE_NOT_FOUND , "Class type not found",
2623 WSA_E_NO_MORE , "No more resources available", /* really not sure */
2624 WSA_E_CANCELLED , "Operation already cancelled", /* really not sure */
2625 WSAEREFUSED , "Operation refused", /* not sure */
2626 #endif
2628 WSAHOST_NOT_FOUND , "Host not found",
2629 WSATRY_AGAIN , "Authoritative host not found during name lookup",
2630 WSANO_RECOVERY , "Non-recoverable error during name lookup",
2631 WSANO_DATA , "Valid name, no data record of requested type",
2633 -1, NULL
2636 char *
2637 sys_strerror(int error_no)
2639 int i;
2640 static char unknown_msg[40];
2642 if (error_no >= 0 && error_no < sys_nerr)
2643 return sys_errlist[error_no];
2645 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
2646 if (_wsa_errlist[i].errnum == error_no)
2647 return _wsa_errlist[i].msg;
2649 sprintf(unknown_msg, "Unidentified error: %d", error_no);
2650 return unknown_msg;
2653 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2654 but I believe the method of keeping the socket handle separate (and
2655 insuring it is not inheritable) is the correct one. */
2657 //#define SOCK_REPLACE_HANDLE
2659 #ifdef SOCK_REPLACE_HANDLE
2660 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2661 #else
2662 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2663 #endif
2666 sys_socket(int af, int type, int protocol)
2668 int fd;
2669 long s;
2670 child_process * cp;
2672 if (winsock_lib == NULL)
2674 h_errno = ENETDOWN;
2675 return INVALID_SOCKET;
2678 check_errno ();
2680 /* call the real socket function */
2681 s = (long) pfn_socket (af, type, protocol);
2683 if (s != INVALID_SOCKET)
2685 /* Although under NT 3.5 _open_osfhandle will accept a socket
2686 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2687 that does not work under NT 3.1. However, we can get the same
2688 effect by using a backdoor function to replace an existing
2689 descriptor handle with the one we want. */
2691 /* allocate a file descriptor (with appropriate flags) */
2692 fd = _open ("NUL:", _O_RDWR);
2693 if (fd >= 0)
2695 #ifdef SOCK_REPLACE_HANDLE
2696 /* now replace handle to NUL with our socket handle */
2697 CloseHandle ((HANDLE) _get_osfhandle (fd));
2698 _free_osfhnd (fd);
2699 _set_osfhnd (fd, s);
2700 /* setmode (fd, _O_BINARY); */
2701 #else
2702 /* Make a non-inheritable copy of the socket handle. Note
2703 that it is possible that sockets aren't actually kernel
2704 handles, which appears to be the case on Windows 9x when
2705 the MS Proxy winsock client is installed. */
2707 /* Apparently there is a bug in NT 3.51 with some service
2708 packs, which prevents using DuplicateHandle to make a
2709 socket handle non-inheritable (causes WSACleanup to
2710 hang). The work-around is to use SetHandleInformation
2711 instead if it is available and implemented. */
2712 if (pfn_SetHandleInformation)
2714 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
2716 else
2718 HANDLE parent = GetCurrentProcess ();
2719 HANDLE new_s = INVALID_HANDLE_VALUE;
2721 if (DuplicateHandle (parent,
2722 (HANDLE) s,
2723 parent,
2724 &new_s,
2726 FALSE,
2727 DUPLICATE_SAME_ACCESS))
2729 /* It is possible that DuplicateHandle succeeds even
2730 though the socket wasn't really a kernel handle,
2731 because a real handle has the same value. So
2732 test whether the new handle really is a socket. */
2733 long nonblocking = 0;
2734 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
2736 pfn_closesocket (s);
2737 s = (SOCKET) new_s;
2739 else
2741 CloseHandle (new_s);
2746 fd_info[fd].hnd = (HANDLE) s;
2747 #endif
2749 /* set our own internal flags */
2750 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
2752 cp = new_child ();
2753 if (cp)
2755 cp->fd = fd;
2756 cp->status = STATUS_READ_ACKNOWLEDGED;
2758 /* attach child_process to fd_info */
2759 if (fd_info[ fd ].cp != NULL)
2761 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
2762 abort ();
2765 fd_info[ fd ].cp = cp;
2767 /* success! */
2768 winsock_inuse++; /* count open sockets */
2769 return fd;
2772 /* clean up */
2773 _close (fd);
2775 pfn_closesocket (s);
2776 h_errno = EMFILE;
2778 set_errno ();
2780 return -1;
2785 sys_bind (int s, const struct sockaddr * addr, int namelen)
2787 if (winsock_lib == NULL)
2789 h_errno = ENOTSOCK;
2790 return SOCKET_ERROR;
2793 check_errno ();
2794 if (fd_info[s].flags & FILE_SOCKET)
2796 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
2797 if (rc == SOCKET_ERROR)
2798 set_errno ();
2799 return rc;
2801 h_errno = ENOTSOCK;
2802 return SOCKET_ERROR;
2807 sys_connect (int s, const struct sockaddr * name, int namelen)
2809 if (winsock_lib == NULL)
2811 h_errno = ENOTSOCK;
2812 return SOCKET_ERROR;
2815 check_errno ();
2816 if (fd_info[s].flags & FILE_SOCKET)
2818 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
2819 if (rc == SOCKET_ERROR)
2820 set_errno ();
2821 return rc;
2823 h_errno = ENOTSOCK;
2824 return SOCKET_ERROR;
2827 u_short
2828 sys_htons (u_short hostshort)
2830 return (winsock_lib != NULL) ?
2831 pfn_htons (hostshort) : hostshort;
2834 u_short
2835 sys_ntohs (u_short netshort)
2837 return (winsock_lib != NULL) ?
2838 pfn_ntohs (netshort) : netshort;
2841 unsigned long
2842 sys_inet_addr (const char * cp)
2844 return (winsock_lib != NULL) ?
2845 pfn_inet_addr (cp) : INADDR_NONE;
2849 sys_gethostname (char * name, int namelen)
2851 if (winsock_lib != NULL)
2852 return pfn_gethostname (name, namelen);
2854 if (namelen > MAX_COMPUTERNAME_LENGTH)
2855 return !GetComputerName (name, (DWORD *)&namelen);
2857 h_errno = EFAULT;
2858 return SOCKET_ERROR;
2861 struct hostent *
2862 sys_gethostbyname(const char * name)
2864 struct hostent * host;
2866 if (winsock_lib == NULL)
2868 h_errno = ENETDOWN;
2869 return NULL;
2872 check_errno ();
2873 host = pfn_gethostbyname (name);
2874 if (!host)
2875 set_errno ();
2876 return host;
2879 struct servent *
2880 sys_getservbyname(const char * name, const char * proto)
2882 struct servent * serv;
2884 if (winsock_lib == NULL)
2886 h_errno = ENETDOWN;
2887 return NULL;
2890 check_errno ();
2891 serv = pfn_getservbyname (name, proto);
2892 if (!serv)
2893 set_errno ();
2894 return serv;
2898 sys_shutdown (int s, int how)
2900 if (winsock_lib == NULL)
2902 h_errno = ENETDOWN;
2903 return SOCKET_ERROR;
2906 check_errno ();
2907 if (fd_info[s].flags & FILE_SOCKET)
2909 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
2910 if (rc == SOCKET_ERROR)
2911 set_errno ();
2912 return rc;
2914 h_errno = ENOTSOCK;
2915 return SOCKET_ERROR;
2918 #endif /* HAVE_SOCKETS */
2921 /* Shadow main io functions: we need to handle pipes and sockets more
2922 intelligently, and implement non-blocking mode as well. */
2925 sys_close (int fd)
2927 int rc;
2929 if (fd < 0 || fd >= MAXDESC)
2931 errno = EBADF;
2932 return -1;
2935 if (fd_info[fd].cp)
2937 child_process * cp = fd_info[fd].cp;
2939 fd_info[fd].cp = NULL;
2941 if (CHILD_ACTIVE (cp))
2943 /* if last descriptor to active child_process then cleanup */
2944 int i;
2945 for (i = 0; i < MAXDESC; i++)
2947 if (i == fd)
2948 continue;
2949 if (fd_info[i].cp == cp)
2950 break;
2952 if (i == MAXDESC)
2954 #ifdef HAVE_SOCKETS
2955 if (fd_info[fd].flags & FILE_SOCKET)
2957 #ifndef SOCK_REPLACE_HANDLE
2958 if (winsock_lib == NULL) abort ();
2960 pfn_shutdown (SOCK_HANDLE (fd), 2);
2961 rc = pfn_closesocket (SOCK_HANDLE (fd));
2962 #endif
2963 winsock_inuse--; /* count open sockets */
2965 #endif
2966 delete_child (cp);
2971 /* Note that sockets do not need special treatment here (at least on
2972 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2973 closesocket is equivalent to CloseHandle, which is to be expected
2974 because socket handles are fully fledged kernel handles. */
2975 rc = _close (fd);
2977 if (rc == 0)
2978 fd_info[fd].flags = 0;
2980 return rc;
2984 sys_dup (int fd)
2986 int new_fd;
2988 new_fd = _dup (fd);
2989 if (new_fd >= 0)
2991 /* duplicate our internal info as well */
2992 fd_info[new_fd] = fd_info[fd];
2994 return new_fd;
2999 sys_dup2 (int src, int dst)
3001 int rc;
3003 if (dst < 0 || dst >= MAXDESC)
3005 errno = EBADF;
3006 return -1;
3009 /* make sure we close the destination first if it's a pipe or socket */
3010 if (src != dst && fd_info[dst].flags != 0)
3011 sys_close (dst);
3013 rc = _dup2 (src, dst);
3014 if (rc == 0)
3016 /* duplicate our internal info as well */
3017 fd_info[dst] = fd_info[src];
3019 return rc;
3022 /* Unix pipe() has only one arg */
3024 sys_pipe (int * phandles)
3026 int rc;
3027 unsigned flags;
3029 /* make pipe handles non-inheritable; when we spawn a child, we
3030 replace the relevant handle with an inheritable one. Also put
3031 pipes into binary mode; we will do text mode translation ourselves
3032 if required. */
3033 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
3035 if (rc == 0)
3037 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
3038 fd_info[phandles[0]].flags = flags;
3040 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
3041 fd_info[phandles[1]].flags = flags;
3044 return rc;
3047 /* From ntproc.c */
3048 extern Lisp_Object Vw32_pipe_read_delay;
3050 /* Function to do blocking read of one byte, needed to implement
3051 select. It is only allowed on sockets and pipes. */
3053 _sys_read_ahead (int fd)
3055 child_process * cp;
3056 int rc;
3058 if (fd < 0 || fd >= MAXDESC)
3059 return STATUS_READ_ERROR;
3061 cp = fd_info[fd].cp;
3063 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
3064 return STATUS_READ_ERROR;
3066 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
3067 || (fd_info[fd].flags & FILE_READ) == 0)
3069 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd));
3070 abort ();
3073 cp->status = STATUS_READ_IN_PROGRESS;
3075 if (fd_info[fd].flags & FILE_PIPE)
3077 rc = _read (fd, &cp->chr, sizeof (char));
3079 /* Give subprocess time to buffer some more output for us before
3080 reporting that input is available; we need this because Windows 95
3081 connects DOS programs to pipes by making the pipe appear to be
3082 the normal console stdout - as a result most DOS programs will
3083 write to stdout without buffering, ie. one character at a
3084 time. Even some W32 programs do this - "dir" in a command
3085 shell on NT is very slow if we don't do this. */
3086 if (rc > 0)
3088 int wait = XINT (Vw32_pipe_read_delay);
3090 if (wait > 0)
3091 Sleep (wait);
3092 else if (wait < 0)
3093 while (++wait <= 0)
3094 /* Yield remainder of our time slice, effectively giving a
3095 temporary priority boost to the child process. */
3096 Sleep (0);
3099 #ifdef HAVE_SOCKETS
3100 else if (fd_info[fd].flags & FILE_SOCKET)
3101 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
3102 #endif
3104 if (rc == sizeof (char))
3105 cp->status = STATUS_READ_SUCCEEDED;
3106 else
3107 cp->status = STATUS_READ_FAILED;
3109 return cp->status;
3113 sys_read (int fd, char * buffer, unsigned int count)
3115 int nchars;
3116 int to_read;
3117 DWORD waiting;
3118 char * orig_buffer = buffer;
3120 if (fd < 0 || fd >= MAXDESC)
3122 errno = EBADF;
3123 return -1;
3126 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
3128 child_process *cp = fd_info[fd].cp;
3130 if ((fd_info[fd].flags & FILE_READ) == 0)
3132 errno = EBADF;
3133 return -1;
3136 nchars = 0;
3138 /* re-read CR carried over from last read */
3139 if (fd_info[fd].flags & FILE_LAST_CR)
3141 if (fd_info[fd].flags & FILE_BINARY) abort ();
3142 *buffer++ = 0x0d;
3143 count--;
3144 nchars++;
3145 fd_info[fd].flags &= ~FILE_LAST_CR;
3148 /* presence of a child_process structure means we are operating in
3149 non-blocking mode - otherwise we just call _read directly.
3150 Note that the child_process structure might be missing because
3151 reap_subprocess has been called; in this case the pipe is
3152 already broken, so calling _read on it is okay. */
3153 if (cp)
3155 int current_status = cp->status;
3157 switch (current_status)
3159 case STATUS_READ_FAILED:
3160 case STATUS_READ_ERROR:
3161 /* report normal EOF if nothing in buffer */
3162 if (nchars <= 0)
3163 fd_info[fd].flags |= FILE_AT_EOF;
3164 return nchars;
3166 case STATUS_READ_READY:
3167 case STATUS_READ_IN_PROGRESS:
3168 DebPrint (("sys_read called when read is in progress\n"));
3169 errno = EWOULDBLOCK;
3170 return -1;
3172 case STATUS_READ_SUCCEEDED:
3173 /* consume read-ahead char */
3174 *buffer++ = cp->chr;
3175 count--;
3176 nchars++;
3177 cp->status = STATUS_READ_ACKNOWLEDGED;
3178 ResetEvent (cp->char_avail);
3180 case STATUS_READ_ACKNOWLEDGED:
3181 break;
3183 default:
3184 DebPrint (("sys_read: bad status %d\n", current_status));
3185 errno = EBADF;
3186 return -1;
3189 if (fd_info[fd].flags & FILE_PIPE)
3191 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
3192 to_read = min (waiting, (DWORD) count);
3194 if (to_read > 0)
3195 nchars += _read (fd, buffer, to_read);
3197 #ifdef HAVE_SOCKETS
3198 else /* FILE_SOCKET */
3200 if (winsock_lib == NULL) abort ();
3202 /* do the equivalent of a non-blocking read */
3203 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
3204 if (waiting == 0 && nchars == 0)
3206 h_errno = errno = EWOULDBLOCK;
3207 return -1;
3210 if (waiting)
3212 /* always use binary mode for sockets */
3213 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
3214 if (res == SOCKET_ERROR)
3216 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
3217 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
3218 set_errno ();
3219 return -1;
3221 nchars += res;
3224 #endif
3226 else
3228 int nread = _read (fd, buffer, count);
3229 if (nread >= 0)
3230 nchars += nread;
3231 else if (nchars == 0)
3232 nchars = nread;
3235 if (nchars <= 0)
3236 fd_info[fd].flags |= FILE_AT_EOF;
3237 /* Perform text mode translation if required. */
3238 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
3240 nchars = crlf_to_lf (nchars, orig_buffer);
3241 /* If buffer contains only CR, return that. To be absolutely
3242 sure we should attempt to read the next char, but in
3243 practice a CR to be followed by LF would not appear by
3244 itself in the buffer. */
3245 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
3247 fd_info[fd].flags |= FILE_LAST_CR;
3248 nchars--;
3252 else
3253 nchars = _read (fd, buffer, count);
3255 return nchars;
3258 /* For now, don't bother with a non-blocking mode */
3260 sys_write (int fd, const void * buffer, unsigned int count)
3262 int nchars;
3264 if (fd < 0 || fd >= MAXDESC)
3266 errno = EBADF;
3267 return -1;
3270 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
3272 if ((fd_info[fd].flags & FILE_WRITE) == 0)
3274 errno = EBADF;
3275 return -1;
3278 /* Perform text mode translation if required. */
3279 if ((fd_info[fd].flags & FILE_BINARY) == 0)
3281 char * tmpbuf = alloca (count * 2);
3282 unsigned char * src = (void *)buffer;
3283 unsigned char * dst = tmpbuf;
3284 int nbytes = count;
3286 while (1)
3288 unsigned char *next;
3289 /* copy next line or remaining bytes */
3290 next = _memccpy (dst, src, '\n', nbytes);
3291 if (next)
3293 /* copied one line ending with '\n' */
3294 int copied = next - dst;
3295 nbytes -= copied;
3296 src += copied;
3297 /* insert '\r' before '\n' */
3298 next[-1] = '\r';
3299 next[0] = '\n';
3300 dst = next + 1;
3301 count++;
3303 else
3304 /* copied remaining partial line -> now finished */
3305 break;
3307 buffer = tmpbuf;
3311 #ifdef HAVE_SOCKETS
3312 if (fd_info[fd].flags & FILE_SOCKET)
3314 if (winsock_lib == NULL) abort ();
3315 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
3316 if (nchars == SOCKET_ERROR)
3318 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
3319 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
3320 set_errno ();
3323 else
3324 #endif
3325 nchars = _write (fd, buffer, count);
3327 return nchars;
3330 static void
3331 check_windows_init_file ()
3333 extern int noninteractive, inhibit_window_system;
3335 /* A common indication that Emacs is not installed properly is when
3336 it cannot find the Windows installation file. If this file does
3337 not exist in the expected place, tell the user. */
3339 if (!noninteractive && !inhibit_window_system)
3341 extern Lisp_Object Vwindow_system, Vload_path, Qfile_exists_p;
3342 Lisp_Object objs[2];
3343 Lisp_Object full_load_path;
3344 Lisp_Object init_file;
3345 int fd;
3347 objs[0] = Vload_path;
3348 objs[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
3349 full_load_path = Fappend (2, objs);
3350 init_file = build_string ("term/w32-win");
3351 fd = openp (full_load_path, init_file, Vload_suffixes, NULL, 0);
3352 if (fd < 0)
3354 Lisp_Object load_path_print = Fprin1_to_string (full_load_path, Qnil);
3355 char *init_file_name = XSTRING (init_file)->data;
3356 char *load_path = XSTRING (load_path_print)->data;
3357 char *buffer = alloca (1024);
3359 sprintf (buffer,
3360 "The Emacs Windows initialization file \"%s.el\" "
3361 "could not be found in your Emacs installation. "
3362 "Emacs checked the following directories for this file:\n"
3363 "\n%s\n\n"
3364 "When Emacs cannot find this file, it usually means that it "
3365 "was not installed properly, or its distribution file was "
3366 "not unpacked properly.\nSee the README.W32 file in the "
3367 "top-level Emacs directory for more information.",
3368 init_file_name, load_path);
3369 MessageBox (NULL,
3370 buffer,
3371 "Emacs Abort Dialog",
3372 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
3373 /* Use the low-level Emacs abort. */
3374 #undef abort
3375 abort ();
3377 else
3379 _close (fd);
3384 void
3385 term_ntproc ()
3387 #ifdef HAVE_SOCKETS
3388 /* shutdown the socket interface if necessary */
3389 term_winsock ();
3390 #endif
3393 void
3394 init_ntproc ()
3396 #ifdef HAVE_SOCKETS
3397 /* Initialise the socket interface now if available and requested by
3398 the user by defining PRELOAD_WINSOCK; otherwise loading will be
3399 delayed until open-network-stream is called (w32-has-winsock can
3400 also be used to dynamically load or reload winsock).
3402 Conveniently, init_environment is called before us, so
3403 PRELOAD_WINSOCK can be set in the registry. */
3405 /* Always initialize this correctly. */
3406 winsock_lib = NULL;
3408 if (getenv ("PRELOAD_WINSOCK") != NULL)
3409 init_winsock (TRUE);
3410 #endif
3412 /* Initial preparation for subprocess support: replace our standard
3413 handles with non-inheritable versions. */
3415 HANDLE parent;
3416 HANDLE stdin_save = INVALID_HANDLE_VALUE;
3417 HANDLE stdout_save = INVALID_HANDLE_VALUE;
3418 HANDLE stderr_save = INVALID_HANDLE_VALUE;
3420 parent = GetCurrentProcess ();
3422 /* ignore errors when duplicating and closing; typically the
3423 handles will be invalid when running as a gui program. */
3424 DuplicateHandle (parent,
3425 GetStdHandle (STD_INPUT_HANDLE),
3426 parent,
3427 &stdin_save,
3429 FALSE,
3430 DUPLICATE_SAME_ACCESS);
3432 DuplicateHandle (parent,
3433 GetStdHandle (STD_OUTPUT_HANDLE),
3434 parent,
3435 &stdout_save,
3437 FALSE,
3438 DUPLICATE_SAME_ACCESS);
3440 DuplicateHandle (parent,
3441 GetStdHandle (STD_ERROR_HANDLE),
3442 parent,
3443 &stderr_save,
3445 FALSE,
3446 DUPLICATE_SAME_ACCESS);
3448 fclose (stdin);
3449 fclose (stdout);
3450 fclose (stderr);
3452 if (stdin_save != INVALID_HANDLE_VALUE)
3453 _open_osfhandle ((long) stdin_save, O_TEXT);
3454 else
3455 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
3456 _fdopen (0, "r");
3458 if (stdout_save != INVALID_HANDLE_VALUE)
3459 _open_osfhandle ((long) stdout_save, O_TEXT);
3460 else
3461 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
3462 _fdopen (1, "w");
3464 if (stderr_save != INVALID_HANDLE_VALUE)
3465 _open_osfhandle ((long) stderr_save, O_TEXT);
3466 else
3467 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
3468 _fdopen (2, "w");
3471 /* unfortunately, atexit depends on implementation of malloc */
3472 /* atexit (term_ntproc); */
3473 signal (SIGABRT, term_ntproc);
3475 /* determine which drives are fixed, for GetCachedVolumeInformation */
3477 /* GetDriveType must have trailing backslash. */
3478 char drive[] = "A:\\";
3480 /* Loop over all possible drive letters */
3481 while (*drive <= 'Z')
3483 /* Record if this drive letter refers to a fixed drive. */
3484 fixed_drives[DRIVE_INDEX (*drive)] =
3485 (GetDriveType (drive) == DRIVE_FIXED);
3487 (*drive)++;
3490 /* Reset the volume info cache. */
3491 volume_cache = NULL;
3494 /* Check to see if Emacs has been installed correctly. */
3495 check_windows_init_file ();
3498 /* end of nt.c */