]> code.delx.au - gnu-emacs/blob - src/w32.c
(quail-help): The output message is improved.
[gnu-emacs] / src / w32.c
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
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.
10
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.
15
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.
20
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
22 */
23
24
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>
36
37 /* must include CRT headers *before* config.h */
38 #include "config.h"
39 #undef access
40 #undef chdir
41 #undef chmod
42 #undef creat
43 #undef ctime
44 #undef fopen
45 #undef link
46 #undef mkdir
47 #undef mktemp
48 #undef open
49 #undef rename
50 #undef rmdir
51 #undef unlink
52
53 #undef close
54 #undef dup
55 #undef dup2
56 #undef pipe
57 #undef read
58 #undef write
59
60 #undef strerror
61
62 #include "lisp.h"
63
64 #include <pwd.h>
65
66 #ifdef __GNUC__
67 #define _ANONYMOUS_UNION
68 #define _ANONYMOUS_STRUCT
69 #endif
70 #include <windows.h>
71
72 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
73 #include <sys/socket.h>
74 #undef socket
75 #undef bind
76 #undef connect
77 #undef htons
78 #undef ntohs
79 #undef inet_addr
80 #undef gethostname
81 #undef gethostbyname
82 #undef getservbyname
83 #undef shutdown
84 #endif
85
86 #include "w32.h"
87 #include "ndir.h"
88 #include "w32heap.h"
89
90 #undef min
91 #undef max
92 #define min(x, y) (((x) < (y)) ? (x) : (y))
93 #define max(x, y) (((x) > (y)) ? (x) : (y))
94
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;
99
100 static char startup_dir[MAXPATHLEN];
101
102 /* Get the current working directory. */
103 char *
104 getwd (char *dir)
105 {
106 #if 0
107 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
108 return dir;
109 return NULL;
110 #else
111 /* Emacs doesn't actually change directory itself, and we want to
112 force our real wd to be where emacs.exe is to avoid unnecessary
113 conflicts when trying to rename or delete directories. */
114 strcpy (dir, startup_dir);
115 return dir;
116 #endif
117 }
118
119 #ifndef HAVE_SOCKETS
120 /* Emulate gethostname. */
121 int
122 gethostname (char *buffer, int size)
123 {
124 /* NT only allows small host names, so the buffer is
125 certainly large enough. */
126 return !GetComputerName (buffer, &size);
127 }
128 #endif /* HAVE_SOCKETS */
129
130 /* Emulate getloadavg. */
131 int
132 getloadavg (double loadavg[], int nelem)
133 {
134 int i;
135
136 /* A faithful emulation is going to have to be saved for a rainy day. */
137 for (i = 0; i < nelem; i++)
138 {
139 loadavg[i] = 0.0;
140 }
141 return i;
142 }
143
144 /* Emulate getpwuid, getpwnam and others. */
145
146 #define PASSWD_FIELD_SIZE 256
147
148 static char the_passwd_name[PASSWD_FIELD_SIZE];
149 static char the_passwd_passwd[PASSWD_FIELD_SIZE];
150 static char the_passwd_gecos[PASSWD_FIELD_SIZE];
151 static char the_passwd_dir[PASSWD_FIELD_SIZE];
152 static char the_passwd_shell[PASSWD_FIELD_SIZE];
153
154 static struct passwd the_passwd =
155 {
156 the_passwd_name,
157 the_passwd_passwd,
158 0,
159 0,
160 0,
161 the_passwd_gecos,
162 the_passwd_dir,
163 the_passwd_shell,
164 };
165
166 int
167 getuid ()
168 {
169 return the_passwd.pw_uid;
170 }
171
172 int
173 geteuid ()
174 {
175 /* I could imagine arguing for checking to see whether the user is
176 in the Administrators group and returning a UID of 0 for that
177 case, but I don't know how wise that would be in the long run. */
178 return getuid ();
179 }
180
181 int
182 getgid ()
183 {
184 return the_passwd.pw_gid;
185 }
186
187 int
188 getegid ()
189 {
190 return getgid ();
191 }
192
193 struct passwd *
194 getpwuid (int uid)
195 {
196 if (uid == the_passwd.pw_uid)
197 return &the_passwd;
198 return NULL;
199 }
200
201 struct passwd *
202 getpwnam (char *name)
203 {
204 struct passwd *pw;
205
206 pw = getpwuid (getuid ());
207 if (!pw)
208 return pw;
209
210 if (stricmp (name, pw->pw_name))
211 return NULL;
212
213 return pw;
214 }
215
216 void
217 init_user_info ()
218 {
219 /* Find the user's real name by opening the process token and
220 looking up the name associated with the user-sid in that token.
221
222 Use the relative portion of the identifier authority value from
223 the user-sid as the user id value (same for group id using the
224 primary group sid from the process token). */
225
226 char user_sid[256], name[256], domain[256];
227 DWORD length = sizeof (name), dlength = sizeof (domain), trash;
228 HANDLE token = NULL;
229 SID_NAME_USE user_type;
230
231 if (OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token)
232 && GetTokenInformation (token, TokenUser,
233 (PVOID) user_sid, sizeof (user_sid), &trash)
234 && LookupAccountSid (NULL, *((PSID *) user_sid), name, &length,
235 domain, &dlength, &user_type))
236 {
237 strcpy (the_passwd.pw_name, name);
238 /* Determine a reasonable uid value. */
239 if (stricmp ("administrator", name) == 0)
240 {
241 the_passwd.pw_uid = 0;
242 the_passwd.pw_gid = 0;
243 }
244 else
245 {
246 SID_IDENTIFIER_AUTHORITY * pSIA;
247
248 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
249 /* I believe the relative portion is the last 4 bytes (of 6)
250 with msb first. */
251 the_passwd.pw_uid = ((pSIA->Value[2] << 24) +
252 (pSIA->Value[3] << 16) +
253 (pSIA->Value[4] << 8) +
254 (pSIA->Value[5] << 0));
255 /* restrict to conventional uid range for normal users */
256 the_passwd.pw_uid = the_passwd.pw_uid % 60001;
257
258 /* Get group id */
259 if (GetTokenInformation (token, TokenPrimaryGroup,
260 (PVOID) user_sid, sizeof (user_sid), &trash))
261 {
262 SID_IDENTIFIER_AUTHORITY * pSIA;
263
264 pSIA = GetSidIdentifierAuthority (*((PSID *) user_sid));
265 the_passwd.pw_gid = ((pSIA->Value[2] << 24) +
266 (pSIA->Value[3] << 16) +
267 (pSIA->Value[4] << 8) +
268 (pSIA->Value[5] << 0));
269 /* I don't know if this is necessary, but for safety... */
270 the_passwd.pw_gid = the_passwd.pw_gid % 60001;
271 }
272 else
273 the_passwd.pw_gid = the_passwd.pw_uid;
274 }
275 }
276 /* If security calls are not supported (presumably because we
277 are running under Windows 95), fallback to this. */
278 else if (GetUserName (name, &length))
279 {
280 strcpy (the_passwd.pw_name, name);
281 if (stricmp ("administrator", name) == 0)
282 the_passwd.pw_uid = 0;
283 else
284 the_passwd.pw_uid = 123;
285 the_passwd.pw_gid = the_passwd.pw_uid;
286 }
287 else
288 {
289 strcpy (the_passwd.pw_name, "unknown");
290 the_passwd.pw_uid = 123;
291 the_passwd.pw_gid = 123;
292 }
293
294 /* Ensure HOME and SHELL are defined. */
295 if (getenv ("HOME") == NULL)
296 abort ();
297 if (getenv ("SHELL") == NULL)
298 abort ();
299
300 /* Set dir and shell from environment variables. */
301 strcpy (the_passwd.pw_dir, getenv ("HOME"));
302 strcpy (the_passwd.pw_shell, getenv ("SHELL"));
303
304 if (token)
305 CloseHandle (token);
306 }
307
308 int
309 random ()
310 {
311 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
312 return ((rand () << 15) | rand ());
313 }
314
315 void
316 srandom (int seed)
317 {
318 srand (seed);
319 }
320
321
322 /* Normalize filename by converting all path separators to
323 the specified separator. Also conditionally convert upper
324 case path name components to lower case. */
325
326 static void
327 normalize_filename (fp, path_sep)
328 register char *fp;
329 char path_sep;
330 {
331 char sep;
332 char *elem;
333
334 /* Always lower-case drive letters a-z, even if the filesystem
335 preserves case in filenames.
336 This is so filenames can be compared by string comparison
337 functions that are case-sensitive. Even case-preserving filesystems
338 do not distinguish case in drive letters. */
339 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
340 {
341 *fp += 'a' - 'A';
342 fp += 2;
343 }
344
345 if (NILP (Vw32_downcase_file_names))
346 {
347 while (*fp)
348 {
349 if (*fp == '/' || *fp == '\\')
350 *fp = path_sep;
351 fp++;
352 }
353 return;
354 }
355
356 sep = path_sep; /* convert to this path separator */
357 elem = fp; /* start of current path element */
358
359 do {
360 if (*fp >= 'a' && *fp <= 'z')
361 elem = 0; /* don't convert this element */
362
363 if (*fp == 0 || *fp == ':')
364 {
365 sep = *fp; /* restore current separator (or 0) */
366 *fp = '/'; /* after conversion of this element */
367 }
368
369 if (*fp == '/' || *fp == '\\')
370 {
371 if (elem && elem != fp)
372 {
373 *fp = 0; /* temporary end of string */
374 _strlwr (elem); /* while we convert to lower case */
375 }
376 *fp = sep; /* convert (or restore) path separator */
377 elem = fp + 1; /* next element starts after separator */
378 sep = path_sep;
379 }
380 } while (*fp++);
381 }
382
383 /* Destructively turn backslashes into slashes. */
384 void
385 dostounix_filename (p)
386 register char *p;
387 {
388 normalize_filename (p, '/');
389 }
390
391 /* Destructively turn slashes into backslashes. */
392 void
393 unixtodos_filename (p)
394 register char *p;
395 {
396 normalize_filename (p, '\\');
397 }
398
399 /* Remove all CR's that are followed by a LF.
400 (From msdos.c...probably should figure out a way to share it,
401 although this code isn't going to ever change.) */
402 int
403 crlf_to_lf (n, buf)
404 register int n;
405 register unsigned char *buf;
406 {
407 unsigned char *np = buf;
408 unsigned char *startp = buf;
409 unsigned char *endp = buf + n;
410
411 if (n == 0)
412 return n;
413 while (buf < endp - 1)
414 {
415 if (*buf == 0x0d)
416 {
417 if (*(++buf) != 0x0a)
418 *np++ = 0x0d;
419 }
420 else
421 *np++ = *buf++;
422 }
423 if (buf < endp)
424 *np++ = *buf++;
425 return np - startp;
426 }
427
428 /* Parse the root part of file name, if present. Return length and
429 optionally store pointer to char after root. */
430 static int
431 parse_root (char * name, char ** pPath)
432 {
433 char * start = name;
434
435 if (name == NULL)
436 return 0;
437
438 /* find the root name of the volume if given */
439 if (isalpha (name[0]) && name[1] == ':')
440 {
441 /* skip past drive specifier */
442 name += 2;
443 if (IS_DIRECTORY_SEP (name[0]))
444 name++;
445 }
446 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
447 {
448 int slashes = 2;
449 name += 2;
450 do
451 {
452 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
453 break;
454 name++;
455 }
456 while ( *name );
457 if (IS_DIRECTORY_SEP (name[0]))
458 name++;
459 }
460
461 if (pPath)
462 *pPath = name;
463
464 return name - start;
465 }
466
467 /* Get long base name for name; name is assumed to be absolute. */
468 static int
469 get_long_basename (char * name, char * buf, int size)
470 {
471 WIN32_FIND_DATA find_data;
472 HANDLE dir_handle;
473 int len = 0;
474
475 /* must be valid filename, no wild cards or other invalid characters */
476 if (strpbrk (name, "*?|<>\""))
477 return 0;
478
479 dir_handle = FindFirstFile (name, &find_data);
480 if (dir_handle != INVALID_HANDLE_VALUE)
481 {
482 if ((len = strlen (find_data.cFileName)) < size)
483 memcpy (buf, find_data.cFileName, len + 1);
484 else
485 len = 0;
486 FindClose (dir_handle);
487 }
488 return len;
489 }
490
491 /* Get long name for file, if possible (assumed to be absolute). */
492 BOOL
493 w32_get_long_filename (char * name, char * buf, int size)
494 {
495 char * o = buf;
496 char * p;
497 char * q;
498 char full[ MAX_PATH ];
499 int len;
500
501 len = strlen (name);
502 if (len >= MAX_PATH)
503 return FALSE;
504
505 /* Use local copy for destructive modification. */
506 memcpy (full, name, len+1);
507 unixtodos_filename (full);
508
509 /* Copy root part verbatim. */
510 len = parse_root (full, &p);
511 memcpy (o, full, len);
512 o += len;
513 *o = '\0';
514 size -= len;
515
516 while (p != NULL && *p)
517 {
518 q = p;
519 p = strchr (q, '\\');
520 if (p) *p = '\0';
521 len = get_long_basename (full, o, size);
522 if (len > 0)
523 {
524 o += len;
525 size -= len;
526 if (p != NULL)
527 {
528 *p++ = '\\';
529 if (size < 2)
530 return FALSE;
531 *o++ = '\\';
532 size--;
533 *o = '\0';
534 }
535 }
536 else
537 return FALSE;
538 }
539
540 return TRUE;
541 }
542
543 int
544 is_unc_volume (const char *filename)
545 {
546 const char *ptr = filename;
547
548 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
549 return 0;
550
551 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
552 return 0;
553
554 return 1;
555 }
556
557 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
558
559 int
560 sigsetmask (int signal_mask)
561 {
562 return 0;
563 }
564
565 int
566 sigmask (int sig)
567 {
568 return 0;
569 }
570
571 int
572 sigblock (int sig)
573 {
574 return 0;
575 }
576
577 int
578 sigunblock (int sig)
579 {
580 return 0;
581 }
582
583 int
584 setpgrp (int pid, int gid)
585 {
586 return 0;
587 }
588
589 int
590 alarm (int seconds)
591 {
592 return 0;
593 }
594
595 void
596 unrequest_sigio (void)
597 {
598 return;
599 }
600
601 void
602 request_sigio (void)
603 {
604 return;
605 }
606
607 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
608
609 LPBYTE
610 w32_get_resource (key, lpdwtype)
611 char *key;
612 LPDWORD lpdwtype;
613 {
614 LPBYTE lpvalue;
615 HKEY hrootkey = NULL;
616 DWORD cbData;
617 BOOL ok = FALSE;
618
619 /* Check both the current user and the local machine to see if
620 we have any resources. */
621
622 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
623 {
624 lpvalue = NULL;
625
626 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
627 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
628 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
629 {
630 return (lpvalue);
631 }
632
633 if (lpvalue) xfree (lpvalue);
634
635 RegCloseKey (hrootkey);
636 }
637
638 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
639 {
640 lpvalue = NULL;
641
642 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
643 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
644 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
645 {
646 return (lpvalue);
647 }
648
649 if (lpvalue) xfree (lpvalue);
650
651 RegCloseKey (hrootkey);
652 }
653
654 return (NULL);
655 }
656
657 char *get_emacs_configuration (void);
658 extern Lisp_Object Vsystem_configuration;
659
660 void
661 init_environment (char ** argv)
662 {
663 int len;
664 static const char * const tempdirs[] = {
665 "$TMPDIR", "$TEMP", "$TMP", "c:/"
666 };
667 int i;
668 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
669
670 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
671 temporary files and assume "/tmp" if $TMPDIR is unset, which
672 will break on DOS/Windows. Refuse to work if we cannot find
673 a directory, not even "c:/", usable for that purpose. */
674 for (i = 0; i < imax ; i++)
675 {
676 const char *tmp = tempdirs[i];
677
678 if (*tmp == '$')
679 tmp = getenv (tmp + 1);
680 /* Note that `access' can lie to us if the directory resides on a
681 read-only filesystem, like CD-ROM or a write-protected floppy.
682 The only way to be really sure is to actually create a file and
683 see if it succeeds. But I think that's too much to ask. */
684 if (tmp && _access (tmp, D_OK) == 0)
685 {
686 char * var = alloca (strlen (tmp) + 8);
687 sprintf (var, "TMPDIR=%s", tmp);
688 _putenv (var);
689 break;
690 }
691 }
692 if (i >= imax)
693 cmd_error_internal
694 (Fcons (Qerror,
695 Fcons (build_string ("no usable temporary directories found!!"),
696 Qnil)),
697 "While setting TMPDIR: ");
698
699 /* Check for environment variables and use registry settings if they
700 don't exist. Fallback on default values where applicable. */
701 {
702 int i;
703 LPBYTE lpval;
704 DWORD dwType;
705
706 static struct env_entry
707 {
708 char * name;
709 char * def_value;
710 } env_vars[] =
711 {
712 {"HOME", "C:/"},
713 {"PRELOAD_WINSOCK", NULL},
714 {"emacs_dir", "C:/emacs"},
715 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
716 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
717 {"EMACSDATA", "%emacs_dir%/etc"},
718 {"EMACSPATH", "%emacs_dir%/bin"},
719 {"EMACSLOCKDIR", "%emacs_dir%/lock"},
720 /* We no longer set INFOPATH because Info-default-directory-list
721 is then ignored. */
722 /* {"INFOPATH", "%emacs_dir%/info"}, */
723 {"EMACSDOC", "%emacs_dir%/etc"},
724 {"TERM", "cmd"}
725 };
726
727 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
728
729 /* Treat emacs_dir specially: set it unconditionally based on our
730 location, if it appears that we are running from the bin subdir
731 of a standard installation. */
732 {
733 char *p;
734 char modname[MAX_PATH];
735
736 if (!GetModuleFileName (NULL, modname, MAX_PATH))
737 abort ();
738 if ((p = strrchr (modname, '\\')) == NULL)
739 abort ();
740 *p = 0;
741
742 if ((p = strrchr (modname, '\\')) && stricmp (p, "\\bin") == 0)
743 {
744 char buf[SET_ENV_BUF_SIZE];
745
746 *p = 0;
747 for (p = modname; *p; p++)
748 if (*p == '\\') *p = '/';
749
750 _snprintf (buf, sizeof(buf)-1, "emacs_dir=%s", modname);
751 _putenv (strdup (buf));
752 }
753 }
754
755 for (i = 0; i < (sizeof (env_vars) / sizeof (env_vars[0])); i++)
756 {
757 if (!getenv (env_vars[i].name))
758 {
759 int dont_free = 0;
760
761 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL)
762 {
763 lpval = env_vars[i].def_value;
764 dwType = REG_EXPAND_SZ;
765 dont_free = 1;
766 }
767
768 if (lpval)
769 {
770 if (dwType == REG_EXPAND_SZ)
771 {
772 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
773
774 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof(buf1));
775 _snprintf (buf2, sizeof(buf2)-1, "%s=%s", env_vars[i].name, buf1);
776 _putenv (strdup (buf2));
777 }
778 else if (dwType == REG_SZ)
779 {
780 char buf[SET_ENV_BUF_SIZE];
781
782 _snprintf (buf, sizeof(buf)-1, "%s=%s", env_vars[i].name, lpval);
783 _putenv (strdup (buf));
784 }
785
786 if (!dont_free)
787 xfree (lpval);
788 }
789 }
790 }
791 }
792
793 /* Rebuild system configuration to reflect invoking system. */
794 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
795
796 /* Another special case: on NT, the PATH variable is actually named
797 "Path" although cmd.exe (perhaps NT itself) arranges for
798 environment variable lookup and setting to be case insensitive.
799 However, Emacs assumes a fully case sensitive environment, so we
800 need to change "Path" to "PATH" to match the expectations of
801 various elisp packages. We do this by the sneaky method of
802 modifying the string in the C runtime environ entry.
803
804 The same applies to COMSPEC. */
805 {
806 char ** envp;
807
808 for (envp = environ; *envp; envp++)
809 if (_strnicmp (*envp, "PATH=", 5) == 0)
810 memcpy (*envp, "PATH=", 5);
811 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
812 memcpy (*envp, "COMSPEC=", 8);
813 }
814
815 /* Remember the initial working directory for getwd, then make the
816 real wd be the location of emacs.exe to avoid conflicts when
817 renaming or deleting directories. (We also don't call chdir when
818 running subprocesses for the same reason.) */
819 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
820 abort ();
821
822 {
823 char *p;
824 static char modname[MAX_PATH];
825
826 if (!GetModuleFileName (NULL, modname, MAX_PATH))
827 abort ();
828 if ((p = strrchr (modname, '\\')) == NULL)
829 abort ();
830 *p = 0;
831
832 SetCurrentDirectory (modname);
833
834 /* Ensure argv[0] has the full path to Emacs. */
835 *p = '\\';
836 argv[0] = modname;
837 }
838
839 /* Determine if there is a middle mouse button, to allow parse_button
840 to decide whether right mouse events should be mouse-2 or
841 mouse-3. */
842 XSETINT (Vw32_num_mouse_buttons, GetSystemMetrics (SM_CMOUSEBUTTONS));
843
844 init_user_info ();
845 }
846
847 /* We don't have scripts to automatically determine the system configuration
848 for Emacs before it's compiled, and we don't want to have to make the
849 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
850 routine. */
851
852 char *
853 get_emacs_configuration (void)
854 {
855 char *arch, *oem, *os;
856 int build_num;
857 static char configuration_buffer[32];
858
859 /* Determine the processor type. */
860 switch (get_processor_type ())
861 {
862
863 #ifdef PROCESSOR_INTEL_386
864 case PROCESSOR_INTEL_386:
865 case PROCESSOR_INTEL_486:
866 case PROCESSOR_INTEL_PENTIUM:
867 arch = "i386";
868 break;
869 #endif
870
871 #ifdef PROCESSOR_INTEL_860
872 case PROCESSOR_INTEL_860:
873 arch = "i860";
874 break;
875 #endif
876
877 #ifdef PROCESSOR_MIPS_R2000
878 case PROCESSOR_MIPS_R2000:
879 case PROCESSOR_MIPS_R3000:
880 case PROCESSOR_MIPS_R4000:
881 arch = "mips";
882 break;
883 #endif
884
885 #ifdef PROCESSOR_ALPHA_21064
886 case PROCESSOR_ALPHA_21064:
887 arch = "alpha";
888 break;
889 #endif
890
891 default:
892 arch = "unknown";
893 break;
894 }
895
896 /* Use the OEM field to reflect the compiler/library combination. */
897 #ifdef _MSC_VER
898 #define COMPILER_NAME "msvc"
899 #else
900 #ifdef __GNUC__
901 #define COMPILER_NAME "mingw"
902 #else
903 #define COMPILER_NAME "unknown"
904 #endif
905 #endif
906 oem = COMPILER_NAME;
907
908 switch (osinfo_cache.dwPlatformId) {
909 case VER_PLATFORM_WIN32_NT:
910 os = "nt";
911 build_num = osinfo_cache.dwBuildNumber;
912 break;
913 case VER_PLATFORM_WIN32_WINDOWS:
914 if (osinfo_cache.dwMinorVersion == 0) {
915 os = "windows95";
916 } else {
917 os = "windows98";
918 }
919 build_num = LOWORD (osinfo_cache.dwBuildNumber);
920 break;
921 case VER_PLATFORM_WIN32s:
922 /* Not supported, should not happen. */
923 os = "windows32s";
924 build_num = LOWORD (osinfo_cache.dwBuildNumber);
925 break;
926 default:
927 os = "unknown";
928 build_num = 0;
929 break;
930 }
931
932 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
933 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
934 get_w32_major_version (), get_w32_minor_version (), build_num);
935 } else {
936 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
937 }
938
939 return configuration_buffer;
940 }
941
942 char *
943 get_emacs_configuration_options (void)
944 {
945 static char options_buffer[256];
946
947 /* Work out the effective configure options for this build. */
948 #ifdef _MSC_VER
949 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
950 #else
951 #ifdef __GNUC__
952 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
953 #else
954 #define COMPILER_VERSION ""
955 #endif
956 #endif
957
958 sprintf (options_buffer, COMPILER_VERSION);
959 #ifdef EMACSDEBUG
960 strcat (options_buffer, " --no-opt");
961 #endif
962 #ifdef USER_CFLAGS
963 strcat (options_buffer, " --cflags");
964 strcat (options_buffer, USER_CFLAGS);
965 #endif
966 #ifdef USER_LDFLAGS
967 strcat (options_buffer, " --ldflags");
968 strcat (options_buffer, USER_LDFLAGS);
969 #endif
970 return options_buffer;
971 }
972
973
974 #include <sys/timeb.h>
975
976 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
977 void
978 gettimeofday (struct timeval *tv, struct timezone *tz)
979 {
980 struct timeb tb;
981 _ftime (&tb);
982
983 tv->tv_sec = tb.time;
984 tv->tv_usec = tb.millitm * 1000L;
985 if (tz)
986 {
987 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
988 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
989 }
990 }
991
992 /* ------------------------------------------------------------------------- */
993 /* IO support and wrapper functions for W32 API. */
994 /* ------------------------------------------------------------------------- */
995
996 /* Place a wrapper around the MSVC version of ctime. It returns NULL
997 on network directories, so we handle that case here.
998 (Ulrich Leodolter, 1/11/95). */
999 char *
1000 sys_ctime (const time_t *t)
1001 {
1002 char *str = (char *) ctime (t);
1003 return (str ? str : "Sun Jan 01 00:00:00 1970");
1004 }
1005
1006 /* Emulate sleep...we could have done this with a define, but that
1007 would necessitate including windows.h in the files that used it.
1008 This is much easier. */
1009 void
1010 sys_sleep (int seconds)
1011 {
1012 Sleep (seconds * 1000);
1013 }
1014
1015 /* Internal MSVC functions for low-level descriptor munging */
1016 extern int __cdecl _set_osfhnd (int fd, long h);
1017 extern int __cdecl _free_osfhnd (int fd);
1018
1019 /* parallel array of private info on file handles */
1020 filedesc fd_info [ MAXDESC ];
1021
1022 typedef struct volume_info_data {
1023 struct volume_info_data * next;
1024
1025 /* time when info was obtained */
1026 DWORD timestamp;
1027
1028 /* actual volume info */
1029 char * root_dir;
1030 DWORD serialnum;
1031 DWORD maxcomp;
1032 DWORD flags;
1033 char * name;
1034 char * type;
1035 } volume_info_data;
1036
1037 /* Global referenced by various functions. */
1038 static volume_info_data volume_info;
1039
1040 /* Vector to indicate which drives are local and fixed (for which cached
1041 data never expires). */
1042 static BOOL fixed_drives[26];
1043
1044 /* Consider cached volume information to be stale if older than 10s,
1045 at least for non-local drives. Info for fixed drives is never stale. */
1046 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
1047 #define VOLINFO_STILL_VALID( root_dir, info ) \
1048 ( ( isalpha (root_dir[0]) && \
1049 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
1050 || GetTickCount () - info->timestamp < 10000 )
1051
1052 /* Cache support functions. */
1053
1054 /* Simple linked list with linear search is sufficient. */
1055 static volume_info_data *volume_cache = NULL;
1056
1057 static volume_info_data *
1058 lookup_volume_info (char * root_dir)
1059 {
1060 volume_info_data * info;
1061
1062 for (info = volume_cache; info; info = info->next)
1063 if (stricmp (info->root_dir, root_dir) == 0)
1064 break;
1065 return info;
1066 }
1067
1068 static void
1069 add_volume_info (char * root_dir, volume_info_data * info)
1070 {
1071 info->root_dir = xstrdup (root_dir);
1072 info->next = volume_cache;
1073 volume_cache = info;
1074 }
1075
1076
1077 /* Wrapper for GetVolumeInformation, which uses caching to avoid
1078 performance penalty (~2ms on 486 for local drives, 7.5ms for local
1079 cdrom drive, ~5-10ms or more for remote drives on LAN). */
1080 volume_info_data *
1081 GetCachedVolumeInformation (char * root_dir)
1082 {
1083 volume_info_data * info;
1084 char default_root[ MAX_PATH ];
1085
1086 /* NULL for root_dir means use root from current directory. */
1087 if (root_dir == NULL)
1088 {
1089 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
1090 return NULL;
1091 parse_root (default_root, &root_dir);
1092 *root_dir = 0;
1093 root_dir = default_root;
1094 }
1095
1096 /* Local fixed drives can be cached permanently. Removable drives
1097 cannot be cached permanently, since the volume name and serial
1098 number (if nothing else) can change. Remote drives should be
1099 treated as if they are removable, since there is no sure way to
1100 tell whether they are or not. Also, the UNC association of drive
1101 letters mapped to remote volumes can be changed at any time (even
1102 by other processes) without notice.
1103
1104 As a compromise, so we can benefit from caching info for remote
1105 volumes, we use a simple expiry mechanism to invalidate cache
1106 entries that are more than ten seconds old. */
1107
1108 #if 0
1109 /* No point doing this, because WNetGetConnection is even slower than
1110 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
1111 GetDriveType is about the only call of this type which does not
1112 involve network access, and so is extremely quick). */
1113
1114 /* Map drive letter to UNC if remote. */
1115 if ( isalpha( root_dir[0] ) && !fixed[ DRIVE_INDEX( root_dir[0] ) ] )
1116 {
1117 char remote_name[ 256 ];
1118 char drive[3] = { root_dir[0], ':' };
1119
1120 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
1121 == NO_ERROR)
1122 /* do something */ ;
1123 }
1124 #endif
1125
1126 info = lookup_volume_info (root_dir);
1127
1128 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
1129 {
1130 char name[ 256 ];
1131 DWORD serialnum;
1132 DWORD maxcomp;
1133 DWORD flags;
1134 char type[ 256 ];
1135
1136 /* Info is not cached, or is stale. */
1137 if (!GetVolumeInformation (root_dir,
1138 name, sizeof (name),
1139 &serialnum,
1140 &maxcomp,
1141 &flags,
1142 type, sizeof (type)))
1143 return NULL;
1144
1145 /* Cache the volume information for future use, overwriting existing
1146 entry if present. */
1147 if (info == NULL)
1148 {
1149 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
1150 add_volume_info (root_dir, info);
1151 }
1152 else
1153 {
1154 xfree (info->name);
1155 xfree (info->type);
1156 }
1157
1158 info->name = xstrdup (name);
1159 info->serialnum = serialnum;
1160 info->maxcomp = maxcomp;
1161 info->flags = flags;
1162 info->type = xstrdup (type);
1163 info->timestamp = GetTickCount ();
1164 }
1165
1166 return info;
1167 }
1168
1169 /* Get information on the volume where name is held; set path pointer to
1170 start of pathname in name (past UNC header\volume header if present). */
1171 int
1172 get_volume_info (const char * name, const char ** pPath)
1173 {
1174 char temp[MAX_PATH];
1175 char *rootname = NULL; /* default to current volume */
1176 volume_info_data * info;
1177
1178 if (name == NULL)
1179 return FALSE;
1180
1181 /* find the root name of the volume if given */
1182 if (isalpha (name[0]) && name[1] == ':')
1183 {
1184 rootname = temp;
1185 temp[0] = *name++;
1186 temp[1] = *name++;
1187 temp[2] = '\\';
1188 temp[3] = 0;
1189 }
1190 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1191 {
1192 char *str = temp;
1193 int slashes = 4;
1194 rootname = temp;
1195 do
1196 {
1197 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1198 break;
1199 *str++ = *name++;
1200 }
1201 while ( *name );
1202
1203 *str++ = '\\';
1204 *str = 0;
1205 }
1206
1207 if (pPath)
1208 *pPath = name;
1209
1210 info = GetCachedVolumeInformation (rootname);
1211 if (info != NULL)
1212 {
1213 /* Set global referenced by other functions. */
1214 volume_info = *info;
1215 return TRUE;
1216 }
1217 return FALSE;
1218 }
1219
1220 /* Determine if volume is FAT format (ie. only supports short 8.3
1221 names); also set path pointer to start of pathname in name. */
1222 int
1223 is_fat_volume (const char * name, const char ** pPath)
1224 {
1225 if (get_volume_info (name, pPath))
1226 return (volume_info.maxcomp == 12);
1227 return FALSE;
1228 }
1229
1230 /* Map filename to a legal 8.3 name if necessary. */
1231 const char *
1232 map_w32_filename (const char * name, const char ** pPath)
1233 {
1234 static char shortname[MAX_PATH];
1235 char * str = shortname;
1236 char c;
1237 char * path;
1238 const char * save_name = name;
1239
1240 if (strlen (name) >= MAX_PATH)
1241 {
1242 /* Return a filename which will cause callers to fail. */
1243 strcpy (shortname, "?");
1244 return shortname;
1245 }
1246
1247 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
1248 {
1249 register int left = 8; /* maximum number of chars in part */
1250 register int extn = 0; /* extension added? */
1251 register int dots = 2; /* maximum number of dots allowed */
1252
1253 while (name < path)
1254 *str++ = *name++; /* skip past UNC header */
1255
1256 while ((c = *name++))
1257 {
1258 switch ( c )
1259 {
1260 case '\\':
1261 case '/':
1262 *str++ = '\\';
1263 extn = 0; /* reset extension flags */
1264 dots = 2; /* max 2 dots */
1265 left = 8; /* max length 8 for main part */
1266 break;
1267 case ':':
1268 *str++ = ':';
1269 extn = 0; /* reset extension flags */
1270 dots = 2; /* max 2 dots */
1271 left = 8; /* max length 8 for main part */
1272 break;
1273 case '.':
1274 if ( dots )
1275 {
1276 /* Convert path components of the form .xxx to _xxx,
1277 but leave . and .. as they are. This allows .emacs
1278 to be read as _emacs, for example. */
1279
1280 if (! *name ||
1281 *name == '.' ||
1282 IS_DIRECTORY_SEP (*name))
1283 {
1284 *str++ = '.';
1285 dots--;
1286 }
1287 else
1288 {
1289 *str++ = '_';
1290 left--;
1291 dots = 0;
1292 }
1293 }
1294 else if ( !extn )
1295 {
1296 *str++ = '.';
1297 extn = 1; /* we've got an extension */
1298 left = 3; /* 3 chars in extension */
1299 }
1300 else
1301 {
1302 /* any embedded dots after the first are converted to _ */
1303 *str++ = '_';
1304 }
1305 break;
1306 case '~':
1307 case '#': /* don't lose these, they're important */
1308 if ( ! left )
1309 str[-1] = c; /* replace last character of part */
1310 /* FALLTHRU */
1311 default:
1312 if ( left )
1313 {
1314 *str++ = tolower (c); /* map to lower case (looks nicer) */
1315 left--;
1316 dots = 0; /* started a path component */
1317 }
1318 break;
1319 }
1320 }
1321 *str = '\0';
1322 }
1323 else
1324 {
1325 strcpy (shortname, name);
1326 unixtodos_filename (shortname);
1327 }
1328
1329 if (pPath)
1330 *pPath = shortname + (path - save_name);
1331
1332 return shortname;
1333 }
1334
1335 static int
1336 is_exec (const char * name)
1337 {
1338 char * p = strrchr (name, '.');
1339 return
1340 (p != NULL
1341 && (stricmp (p, ".exe") == 0 ||
1342 stricmp (p, ".com") == 0 ||
1343 stricmp (p, ".bat") == 0 ||
1344 stricmp (p, ".cmd") == 0));
1345 }
1346
1347 /* Emulate the Unix directory procedures opendir, closedir,
1348 and readdir. We can't use the procedures supplied in sysdep.c,
1349 so we provide them here. */
1350
1351 struct direct dir_static; /* simulated directory contents */
1352 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
1353 static int dir_is_fat;
1354 static char dir_pathname[MAXPATHLEN+1];
1355 static WIN32_FIND_DATA dir_find_data;
1356
1357 /* Support shares on a network resource as subdirectories of a read-only
1358 root directory. */
1359 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
1360 HANDLE open_unc_volume (char *);
1361 char *read_unc_volume (HANDLE, char *, int);
1362 void close_unc_volume (HANDLE);
1363
1364 DIR *
1365 opendir (char *filename)
1366 {
1367 DIR *dirp;
1368
1369 /* Opening is done by FindFirstFile. However, a read is inherent to
1370 this operation, so we defer the open until read time. */
1371
1372 if (dir_find_handle != INVALID_HANDLE_VALUE)
1373 return NULL;
1374 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1375 return NULL;
1376
1377 if (is_unc_volume (filename))
1378 {
1379 wnet_enum_handle = open_unc_volume (filename);
1380 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
1381 return NULL;
1382 }
1383
1384 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
1385 return NULL;
1386
1387 dirp->dd_fd = 0;
1388 dirp->dd_loc = 0;
1389 dirp->dd_size = 0;
1390
1391 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
1392 dir_pathname[MAXPATHLEN] = '\0';
1393 dir_is_fat = is_fat_volume (filename, NULL);
1394
1395 return dirp;
1396 }
1397
1398 void
1399 closedir (DIR *dirp)
1400 {
1401 /* If we have a find-handle open, close it. */
1402 if (dir_find_handle != INVALID_HANDLE_VALUE)
1403 {
1404 FindClose (dir_find_handle);
1405 dir_find_handle = INVALID_HANDLE_VALUE;
1406 }
1407 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1408 {
1409 close_unc_volume (wnet_enum_handle);
1410 wnet_enum_handle = INVALID_HANDLE_VALUE;
1411 }
1412 xfree ((char *) dirp);
1413 }
1414
1415 struct direct *
1416 readdir (DIR *dirp)
1417 {
1418 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
1419 {
1420 if (!read_unc_volume (wnet_enum_handle,
1421 dir_find_data.cFileName,
1422 MAX_PATH))
1423 return NULL;
1424 }
1425 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
1426 else if (dir_find_handle == INVALID_HANDLE_VALUE)
1427 {
1428 char filename[MAXNAMLEN + 3];
1429 int ln;
1430
1431 strcpy (filename, dir_pathname);
1432 ln = strlen (filename) - 1;
1433 if (!IS_DIRECTORY_SEP (filename[ln]))
1434 strcat (filename, "\\");
1435 strcat (filename, "*");
1436
1437 dir_find_handle = FindFirstFile (filename, &dir_find_data);
1438
1439 if (dir_find_handle == INVALID_HANDLE_VALUE)
1440 return NULL;
1441 }
1442 else
1443 {
1444 if (!FindNextFile (dir_find_handle, &dir_find_data))
1445 return NULL;
1446 }
1447
1448 /* Emacs never uses this value, so don't bother making it match
1449 value returned by stat(). */
1450 dir_static.d_ino = 1;
1451
1452 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
1453 dir_static.d_namlen - dir_static.d_namlen % 4;
1454
1455 dir_static.d_namlen = strlen (dir_find_data.cFileName);
1456 strcpy (dir_static.d_name, dir_find_data.cFileName);
1457 if (dir_is_fat)
1458 _strlwr (dir_static.d_name);
1459 else if (!NILP (Vw32_downcase_file_names))
1460 {
1461 register char *p;
1462 for (p = dir_static.d_name; *p; p++)
1463 if (*p >= 'a' && *p <= 'z')
1464 break;
1465 if (!*p)
1466 _strlwr (dir_static.d_name);
1467 }
1468
1469 return &dir_static;
1470 }
1471
1472 HANDLE
1473 open_unc_volume (char *path)
1474 {
1475 NETRESOURCE nr;
1476 HANDLE henum;
1477 int result;
1478
1479 nr.dwScope = RESOURCE_GLOBALNET;
1480 nr.dwType = RESOURCETYPE_DISK;
1481 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
1482 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
1483 nr.lpLocalName = NULL;
1484 nr.lpRemoteName = map_w32_filename (path, NULL);
1485 nr.lpComment = NULL;
1486 nr.lpProvider = NULL;
1487
1488 result = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
1489 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
1490
1491 if (result == NO_ERROR)
1492 return henum;
1493 else
1494 return INVALID_HANDLE_VALUE;
1495 }
1496
1497 char *
1498 read_unc_volume (HANDLE henum, char *readbuf, int size)
1499 {
1500 DWORD count;
1501 int result;
1502 DWORD bufsize = 512;
1503 char *buffer;
1504 char *ptr;
1505
1506 count = 1;
1507 buffer = alloca (bufsize);
1508 result = WNetEnumResource (wnet_enum_handle, &count, buffer, &bufsize);
1509 if (result != NO_ERROR)
1510 return NULL;
1511
1512 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
1513 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
1514 ptr += 2;
1515 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
1516 ptr++;
1517
1518 strncpy (readbuf, ptr, size);
1519 return readbuf;
1520 }
1521
1522 void
1523 close_unc_volume (HANDLE henum)
1524 {
1525 if (henum != INVALID_HANDLE_VALUE)
1526 WNetCloseEnum (henum);
1527 }
1528
1529 DWORD
1530 unc_volume_file_attributes (char *path)
1531 {
1532 HANDLE henum;
1533 DWORD attrs;
1534
1535 henum = open_unc_volume (path);
1536 if (henum == INVALID_HANDLE_VALUE)
1537 return -1;
1538
1539 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
1540
1541 close_unc_volume (henum);
1542
1543 return attrs;
1544 }
1545
1546
1547 /* Shadow some MSVC runtime functions to map requests for long filenames
1548 to reasonable short names if necessary. This was originally added to
1549 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
1550 long file names. */
1551
1552 int
1553 sys_access (const char * path, int mode)
1554 {
1555 DWORD attributes;
1556
1557 /* MSVC implementation doesn't recognize D_OK. */
1558 path = map_w32_filename (path, NULL);
1559 if (is_unc_volume (path))
1560 {
1561 attributes = unc_volume_file_attributes (path);
1562 if (attributes == -1) {
1563 errno = EACCES;
1564 return -1;
1565 }
1566 }
1567 else if ((attributes = GetFileAttributes (path)) == -1)
1568 {
1569 /* Should try mapping GetLastError to errno; for now just indicate
1570 that path doesn't exist. */
1571 errno = EACCES;
1572 return -1;
1573 }
1574 if ((mode & X_OK) != 0 && !is_exec (path))
1575 {
1576 errno = EACCES;
1577 return -1;
1578 }
1579 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
1580 {
1581 errno = EACCES;
1582 return -1;
1583 }
1584 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1585 {
1586 errno = EACCES;
1587 return -1;
1588 }
1589 return 0;
1590 }
1591
1592 int
1593 sys_chdir (const char * path)
1594 {
1595 return _chdir (map_w32_filename (path, NULL));
1596 }
1597
1598 int
1599 sys_chmod (const char * path, int mode)
1600 {
1601 return _chmod (map_w32_filename (path, NULL), mode);
1602 }
1603
1604 int
1605 sys_creat (const char * path, int mode)
1606 {
1607 return _creat (map_w32_filename (path, NULL), mode);
1608 }
1609
1610 FILE *
1611 sys_fopen(const char * path, const char * mode)
1612 {
1613 int fd;
1614 int oflag;
1615 const char * mode_save = mode;
1616
1617 /* Force all file handles to be non-inheritable. This is necessary to
1618 ensure child processes don't unwittingly inherit handles that might
1619 prevent future file access. */
1620
1621 if (mode[0] == 'r')
1622 oflag = O_RDONLY;
1623 else if (mode[0] == 'w' || mode[0] == 'a')
1624 oflag = O_WRONLY | O_CREAT | O_TRUNC;
1625 else
1626 return NULL;
1627
1628 /* Only do simplistic option parsing. */
1629 while (*++mode)
1630 if (mode[0] == '+')
1631 {
1632 oflag &= ~(O_RDONLY | O_WRONLY);
1633 oflag |= O_RDWR;
1634 }
1635 else if (mode[0] == 'b')
1636 {
1637 oflag &= ~O_TEXT;
1638 oflag |= O_BINARY;
1639 }
1640 else if (mode[0] == 't')
1641 {
1642 oflag &= ~O_BINARY;
1643 oflag |= O_TEXT;
1644 }
1645 else break;
1646
1647 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
1648 if (fd < 0)
1649 return NULL;
1650
1651 return _fdopen (fd, mode_save);
1652 }
1653
1654 /* This only works on NTFS volumes, but is useful to have. */
1655 int
1656 sys_link (const char * old, const char * new)
1657 {
1658 HANDLE fileh;
1659 int result = -1;
1660 char oldname[MAX_PATH], newname[MAX_PATH];
1661
1662 if (old == NULL || new == NULL)
1663 {
1664 errno = ENOENT;
1665 return -1;
1666 }
1667
1668 strcpy (oldname, map_w32_filename (old, NULL));
1669 strcpy (newname, map_w32_filename (new, NULL));
1670
1671 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
1672 FILE_FLAG_BACKUP_SEMANTICS, NULL);
1673 if (fileh != INVALID_HANDLE_VALUE)
1674 {
1675 int wlen;
1676
1677 /* Confusingly, the "alternate" stream name field does not apply
1678 when restoring a hard link, and instead contains the actual
1679 stream data for the link (ie. the name of the link to create).
1680 The WIN32_STREAM_ID structure before the cStreamName field is
1681 the stream header, which is then immediately followed by the
1682 stream data. */
1683
1684 struct {
1685 WIN32_STREAM_ID wid;
1686 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
1687 } data;
1688
1689 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
1690 data.wid.cStreamName, MAX_PATH);
1691 if (wlen > 0)
1692 {
1693 LPVOID context = NULL;
1694 DWORD wbytes = 0;
1695
1696 data.wid.dwStreamId = BACKUP_LINK;
1697 data.wid.dwStreamAttributes = 0;
1698 data.wid.Size.LowPart = wlen * sizeof(WCHAR);
1699 data.wid.Size.HighPart = 0;
1700 data.wid.dwStreamNameSize = 0;
1701
1702 if (BackupWrite (fileh, (LPBYTE)&data,
1703 offsetof (WIN32_STREAM_ID, cStreamName)
1704 + data.wid.Size.LowPart,
1705 &wbytes, FALSE, FALSE, &context)
1706 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
1707 {
1708 /* succeeded */
1709 result = 0;
1710 }
1711 else
1712 {
1713 /* Should try mapping GetLastError to errno; for now just
1714 indicate a general error (eg. links not supported). */
1715 errno = EINVAL; // perhaps EMLINK?
1716 }
1717 }
1718
1719 CloseHandle (fileh);
1720 }
1721 else
1722 errno = ENOENT;
1723
1724 return result;
1725 }
1726
1727 int
1728 sys_mkdir (const char * path)
1729 {
1730 return _mkdir (map_w32_filename (path, NULL));
1731 }
1732
1733 /* Because of long name mapping issues, we need to implement this
1734 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
1735 a unique name, instead of setting the input template to an empty
1736 string.
1737
1738 Standard algorithm seems to be use pid or tid with a letter on the
1739 front (in place of the 6 X's) and cycle through the letters to find a
1740 unique name. We extend that to allow any reasonable character as the
1741 first of the 6 X's. */
1742 char *
1743 sys_mktemp (char * template)
1744 {
1745 char * p;
1746 int i;
1747 unsigned uid = GetCurrentThreadId ();
1748 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
1749
1750 if (template == NULL)
1751 return NULL;
1752 p = template + strlen (template);
1753 i = 5;
1754 /* replace up to the last 5 X's with uid in decimal */
1755 while (--p >= template && p[0] == 'X' && --i >= 0)
1756 {
1757 p[0] = '0' + uid % 10;
1758 uid /= 10;
1759 }
1760
1761 if (i < 0 && p[0] == 'X')
1762 {
1763 i = 0;
1764 do
1765 {
1766 int save_errno = errno;
1767 p[0] = first_char[i];
1768 if (sys_access (template, 0) < 0)
1769 {
1770 errno = save_errno;
1771 return template;
1772 }
1773 }
1774 while (++i < sizeof (first_char));
1775 }
1776
1777 /* Template is badly formed or else we can't generate a unique name,
1778 so return empty string */
1779 template[0] = 0;
1780 return template;
1781 }
1782
1783 int
1784 sys_open (const char * path, int oflag, int mode)
1785 {
1786 /* Force all file handles to be non-inheritable. */
1787 return _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, mode);
1788 }
1789
1790 int
1791 sys_rename (const char * oldname, const char * newname)
1792 {
1793 int result;
1794 char temp[MAX_PATH];
1795
1796 /* MoveFile on Windows 95 doesn't correctly change the short file name
1797 alias in a number of circumstances (it is not easy to predict when
1798 just by looking at oldname and newname, unfortunately). In these
1799 cases, renaming through a temporary name avoids the problem.
1800
1801 A second problem on Windows 95 is that renaming through a temp name when
1802 newname is uppercase fails (the final long name ends up in
1803 lowercase, although the short alias might be uppercase) UNLESS the
1804 long temp name is not 8.3.
1805
1806 So, on Windows 95 we always rename through a temp name, and we make sure
1807 the temp name has a long extension to ensure correct renaming. */
1808
1809 strcpy (temp, map_w32_filename (oldname, NULL));
1810
1811 if (os_subtype == OS_WIN95)
1812 {
1813 char * o;
1814 char * p;
1815 int i = 0;
1816
1817 oldname = map_w32_filename (oldname, NULL);
1818 if (o = strrchr (oldname, '\\'))
1819 o++;
1820 else
1821 o = (char *) oldname;
1822
1823 if (p = strrchr (temp, '\\'))
1824 p++;
1825 else
1826 p = temp;
1827
1828 do
1829 {
1830 /* Force temp name to require a manufactured 8.3 alias - this
1831 seems to make the second rename work properly. */
1832 sprintf (p, "_.%s.%u", o, i);
1833 i++;
1834 result = rename (oldname, temp);
1835 }
1836 /* This loop must surely terminate! */
1837 while (result < 0 && (errno == EEXIST || errno == EACCES));
1838 if (result < 0)
1839 return -1;
1840 }
1841
1842 /* Emulate Unix behaviour - newname is deleted if it already exists
1843 (at least if it is a file; don't do this for directories).
1844
1845 Since we mustn't do this if we are just changing the case of the
1846 file name (we would end up deleting the file we are trying to
1847 rename!), we let rename detect if the destination file already
1848 exists - that way we avoid the possible pitfalls of trying to
1849 determine ourselves whether two names really refer to the same
1850 file, which is not always possible in the general case. (Consider
1851 all the permutations of shared or subst'd drives, etc.) */
1852
1853 newname = map_w32_filename (newname, NULL);
1854 result = rename (temp, newname);
1855
1856 if (result < 0
1857 && (errno == EEXIST || errno == EACCES)
1858 && _chmod (newname, 0666) == 0
1859 && _unlink (newname) == 0)
1860 result = rename (temp, newname);
1861
1862 return result;
1863 }
1864
1865 int
1866 sys_rmdir (const char * path)
1867 {
1868 return _rmdir (map_w32_filename (path, NULL));
1869 }
1870
1871 int
1872 sys_unlink (const char * path)
1873 {
1874 path = map_w32_filename (path, NULL);
1875
1876 /* On Unix, unlink works without write permission. */
1877 _chmod (path, 0666);
1878 return _unlink (path);
1879 }
1880
1881 static FILETIME utc_base_ft;
1882 static long double utc_base;
1883 static int init = 0;
1884
1885 static time_t
1886 convert_time (FILETIME ft)
1887 {
1888 long double ret;
1889
1890 if (!init)
1891 {
1892 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1893 SYSTEMTIME st;
1894
1895 st.wYear = 1970;
1896 st.wMonth = 1;
1897 st.wDay = 1;
1898 st.wHour = 0;
1899 st.wMinute = 0;
1900 st.wSecond = 0;
1901 st.wMilliseconds = 0;
1902
1903 SystemTimeToFileTime (&st, &utc_base_ft);
1904 utc_base = (long double) utc_base_ft.dwHighDateTime
1905 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1906 init = 1;
1907 }
1908
1909 if (CompareFileTime (&ft, &utc_base_ft) < 0)
1910 return 0;
1911
1912 ret = (long double) ft.dwHighDateTime * 4096 * 1024 * 1024 + ft.dwLowDateTime;
1913 ret -= utc_base;
1914 return (time_t) (ret * 1e-7);
1915 }
1916
1917 void
1918 convert_from_time_t (time_t time, FILETIME * pft)
1919 {
1920 long double tmp;
1921
1922 if (!init)
1923 {
1924 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
1925 SYSTEMTIME st;
1926
1927 st.wYear = 1970;
1928 st.wMonth = 1;
1929 st.wDay = 1;
1930 st.wHour = 0;
1931 st.wMinute = 0;
1932 st.wSecond = 0;
1933 st.wMilliseconds = 0;
1934
1935 SystemTimeToFileTime (&st, &utc_base_ft);
1936 utc_base = (long double) utc_base_ft.dwHighDateTime
1937 * 4096 * 1024 * 1024 + utc_base_ft.dwLowDateTime;
1938 init = 1;
1939 }
1940
1941 /* time in 100ns units since 1-Jan-1601 */
1942 tmp = (long double) time * 1e7 + utc_base;
1943 pft->dwHighDateTime = (DWORD) (tmp / (4096.0 * 1024 * 1024));
1944 pft->dwLowDateTime = (DWORD) (tmp - (4096.0 * 1024 * 1024) * pft->dwHighDateTime);
1945 }
1946
1947 #if 0
1948 /* No reason to keep this; faking inode values either by hashing or even
1949 using the file index from GetInformationByHandle, is not perfect and
1950 so by default Emacs doesn't use the inode values on Windows.
1951 Instead, we now determine file-truename correctly (except for
1952 possible drive aliasing etc). */
1953
1954 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
1955 static unsigned
1956 hashval (const unsigned char * str)
1957 {
1958 unsigned h = 0;
1959 while (*str)
1960 {
1961 h = (h << 4) + *str++;
1962 h ^= (h >> 28);
1963 }
1964 return h;
1965 }
1966
1967 /* Return the hash value of the canonical pathname, excluding the
1968 drive/UNC header, to get a hopefully unique inode number. */
1969 static DWORD
1970 generate_inode_val (const char * name)
1971 {
1972 char fullname[ MAX_PATH ];
1973 char * p;
1974 unsigned hash;
1975
1976 /* Get the truly canonical filename, if it exists. (Note: this
1977 doesn't resolve aliasing due to subst commands, or recognise hard
1978 links. */
1979 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
1980 abort ();
1981
1982 parse_root (fullname, &p);
1983 /* Normal W32 filesystems are still case insensitive. */
1984 _strlwr (p);
1985 return hashval (p);
1986 }
1987
1988 #endif
1989
1990 /* MSVC stat function can't cope with UNC names and has other bugs, so
1991 replace it with our own. This also allows us to calculate consistent
1992 inode values without hacks in the main Emacs code. */
1993 int
1994 stat (const char * path, struct stat * buf)
1995 {
1996 char *name, *r;
1997 WIN32_FIND_DATA wfd;
1998 HANDLE fh;
1999 DWORD fake_inode;
2000 int permission;
2001 int len;
2002 int rootdir = FALSE;
2003
2004 if (path == NULL || buf == NULL)
2005 {
2006 errno = EFAULT;
2007 return -1;
2008 }
2009
2010 name = (char *) map_w32_filename (path, &path);
2011 /* must be valid filename, no wild cards or other invalid characters */
2012 if (strpbrk (name, "*?|<>\""))
2013 {
2014 errno = ENOENT;
2015 return -1;
2016 }
2017
2018 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
2019 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
2020 if (IS_DIRECTORY_SEP (r[0]) && r[1] == '.' && r[2] == '.' && r[3] == '\0')
2021 {
2022 r[1] = r[2] = '\0';
2023 }
2024
2025 /* Remove trailing directory separator, unless name is the root
2026 directory of a drive or UNC volume in which case ensure there
2027 is a trailing separator. */
2028 len = strlen (name);
2029 rootdir = (path >= name + len - 1
2030 && (IS_DIRECTORY_SEP (*path) || *path == 0));
2031 name = strcpy (alloca (len + 2), name);
2032
2033 if (is_unc_volume (name))
2034 {
2035 DWORD attrs = unc_volume_file_attributes (name);
2036
2037 if (attrs == -1)
2038 return -1;
2039
2040 memset (&wfd, 0, sizeof (wfd));
2041 wfd.dwFileAttributes = attrs;
2042 wfd.ftCreationTime = utc_base_ft;
2043 wfd.ftLastAccessTime = utc_base_ft;
2044 wfd.ftLastWriteTime = utc_base_ft;
2045 strcpy (wfd.cFileName, name);
2046 }
2047 else if (rootdir)
2048 {
2049 if (!IS_DIRECTORY_SEP (name[len-1]))
2050 strcat (name, "\\");
2051 if (GetDriveType (name) < 2)
2052 {
2053 errno = ENOENT;
2054 return -1;
2055 }
2056 memset (&wfd, 0, sizeof (wfd));
2057 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
2058 wfd.ftCreationTime = utc_base_ft;
2059 wfd.ftLastAccessTime = utc_base_ft;
2060 wfd.ftLastWriteTime = utc_base_ft;
2061 strcpy (wfd.cFileName, name);
2062 }
2063 else
2064 {
2065 if (IS_DIRECTORY_SEP (name[len-1]))
2066 name[len - 1] = 0;
2067
2068 /* (This is hacky, but helps when doing file completions on
2069 network drives.) Optimize by using information available from
2070 active readdir if possible. */
2071 len = strlen (dir_pathname);
2072 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
2073 len--;
2074 if (dir_find_handle != INVALID_HANDLE_VALUE
2075 && strnicmp (name, dir_pathname, len) == 0
2076 && IS_DIRECTORY_SEP (name[len])
2077 && stricmp (name + len + 1, dir_static.d_name) == 0)
2078 {
2079 /* This was the last entry returned by readdir. */
2080 wfd = dir_find_data;
2081 }
2082 else
2083 {
2084 fh = FindFirstFile (name, &wfd);
2085 if (fh == INVALID_HANDLE_VALUE)
2086 {
2087 errno = ENOENT;
2088 return -1;
2089 }
2090 FindClose (fh);
2091 }
2092 }
2093
2094 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2095 {
2096 buf->st_mode = _S_IFDIR;
2097 buf->st_nlink = 2; /* doesn't really matter */
2098 fake_inode = 0; /* this doesn't either I think */
2099 }
2100 else if (!NILP (Vw32_get_true_file_attributes)
2101 /* No access rights required to get info. */
2102 && (fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING, 0, NULL))
2103 != INVALID_HANDLE_VALUE)
2104 {
2105 /* This is more accurate in terms of gettting the correct number
2106 of links, but is quite slow (it is noticable when Emacs is
2107 making a list of file name completions). */
2108 BY_HANDLE_FILE_INFORMATION info;
2109
2110 if (GetFileInformationByHandle (fh, &info))
2111 {
2112 buf->st_nlink = info.nNumberOfLinks;
2113 /* Might as well use file index to fake inode values, but this
2114 is not guaranteed to be unique unless we keep a handle open
2115 all the time (even then there are situations where it is
2116 not unique). Reputedly, there are at most 48 bits of info
2117 (on NTFS, presumably less on FAT). */
2118 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
2119 }
2120 else
2121 {
2122 buf->st_nlink = 1;
2123 fake_inode = 0;
2124 }
2125
2126 switch (GetFileType (fh))
2127 {
2128 case FILE_TYPE_DISK:
2129 buf->st_mode = _S_IFREG;
2130 break;
2131 case FILE_TYPE_PIPE:
2132 buf->st_mode = _S_IFIFO;
2133 break;
2134 case FILE_TYPE_CHAR:
2135 case FILE_TYPE_UNKNOWN:
2136 default:
2137 buf->st_mode = _S_IFCHR;
2138 }
2139 CloseHandle (fh);
2140 }
2141 else
2142 {
2143 /* Don't bother to make this information more accurate. */
2144 buf->st_mode = _S_IFREG;
2145 buf->st_nlink = 1;
2146 fake_inode = 0;
2147 }
2148
2149 #if 0
2150 /* Not sure if there is any point in this. */
2151 if (!NILP (Vw32_generate_fake_inodes))
2152 fake_inode = generate_inode_val (name);
2153 else if (fake_inode == 0)
2154 {
2155 /* For want of something better, try to make everything unique. */
2156 static DWORD gen_num = 0;
2157 fake_inode = ++gen_num;
2158 }
2159 #endif
2160
2161 /* MSVC defines _ino_t to be short; other libc's might not. */
2162 if (sizeof (buf->st_ino) == 2)
2163 buf->st_ino = fake_inode ^ (fake_inode >> 16);
2164 else
2165 buf->st_ino = fake_inode;
2166
2167 /* consider files to belong to current user */
2168 buf->st_uid = the_passwd.pw_uid;
2169 buf->st_gid = the_passwd.pw_gid;
2170
2171 /* volume_info is set indirectly by map_w32_filename */
2172 buf->st_dev = volume_info.serialnum;
2173 buf->st_rdev = volume_info.serialnum;
2174
2175
2176 buf->st_size = wfd.nFileSizeLow;
2177
2178 /* Convert timestamps to Unix format. */
2179 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
2180 buf->st_atime = convert_time (wfd.ftLastAccessTime);
2181 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
2182 buf->st_ctime = convert_time (wfd.ftCreationTime);
2183 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
2184
2185 /* determine rwx permissions */
2186 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2187 permission = _S_IREAD;
2188 else
2189 permission = _S_IREAD | _S_IWRITE;
2190
2191 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2192 permission |= _S_IEXEC;
2193 else if (is_exec (name))
2194 permission |= _S_IEXEC;
2195
2196 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
2197
2198 return 0;
2199 }
2200
2201 /* Provide fstat and utime as well as stat for consistent handling of
2202 file timestamps. */
2203 int
2204 fstat (int desc, struct stat * buf)
2205 {
2206 HANDLE fh = (HANDLE) _get_osfhandle (desc);
2207 BY_HANDLE_FILE_INFORMATION info;
2208 DWORD fake_inode;
2209 int permission;
2210
2211 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
2212 {
2213 case FILE_TYPE_DISK:
2214 buf->st_mode = _S_IFREG;
2215 if (!GetFileInformationByHandle (fh, &info))
2216 {
2217 errno = EACCES;
2218 return -1;
2219 }
2220 break;
2221 case FILE_TYPE_PIPE:
2222 buf->st_mode = _S_IFIFO;
2223 goto non_disk;
2224 case FILE_TYPE_CHAR:
2225 case FILE_TYPE_UNKNOWN:
2226 default:
2227 buf->st_mode = _S_IFCHR;
2228 non_disk:
2229 memset (&info, 0, sizeof (info));
2230 info.dwFileAttributes = 0;
2231 info.ftCreationTime = utc_base_ft;
2232 info.ftLastAccessTime = utc_base_ft;
2233 info.ftLastWriteTime = utc_base_ft;
2234 }
2235
2236 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2237 {
2238 buf->st_mode = _S_IFDIR;
2239 buf->st_nlink = 2; /* doesn't really matter */
2240 fake_inode = 0; /* this doesn't either I think */
2241 }
2242 else
2243 {
2244 buf->st_nlink = info.nNumberOfLinks;
2245 /* Might as well use file index to fake inode values, but this
2246 is not guaranteed to be unique unless we keep a handle open
2247 all the time (even then there are situations where it is
2248 not unique). Reputedly, there are at most 48 bits of info
2249 (on NTFS, presumably less on FAT). */
2250 fake_inode = info.nFileIndexLow ^ info.nFileIndexHigh;
2251 }
2252
2253 /* MSVC defines _ino_t to be short; other libc's might not. */
2254 if (sizeof (buf->st_ino) == 2)
2255 buf->st_ino = fake_inode ^ (fake_inode >> 16);
2256 else
2257 buf->st_ino = fake_inode;
2258
2259 /* consider files to belong to current user */
2260 buf->st_uid = 0;
2261 buf->st_gid = 0;
2262
2263 buf->st_dev = info.dwVolumeSerialNumber;
2264 buf->st_rdev = info.dwVolumeSerialNumber;
2265
2266 buf->st_size = info.nFileSizeLow;
2267
2268 /* Convert timestamps to Unix format. */
2269 buf->st_mtime = convert_time (info.ftLastWriteTime);
2270 buf->st_atime = convert_time (info.ftLastAccessTime);
2271 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
2272 buf->st_ctime = convert_time (info.ftCreationTime);
2273 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
2274
2275 /* determine rwx permissions */
2276 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2277 permission = _S_IREAD;
2278 else
2279 permission = _S_IREAD | _S_IWRITE;
2280
2281 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2282 permission |= _S_IEXEC;
2283 else
2284 {
2285 #if 0 /* no way of knowing the filename */
2286 char * p = strrchr (name, '.');
2287 if (p != NULL &&
2288 (stricmp (p, ".exe") == 0 ||
2289 stricmp (p, ".com") == 0 ||
2290 stricmp (p, ".bat") == 0 ||
2291 stricmp (p, ".cmd") == 0))
2292 permission |= _S_IEXEC;
2293 #endif
2294 }
2295
2296 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
2297
2298 return 0;
2299 }
2300
2301 int
2302 utime (const char *name, struct utimbuf *times)
2303 {
2304 struct utimbuf deftime;
2305 HANDLE fh;
2306 FILETIME mtime;
2307 FILETIME atime;
2308
2309 if (times == NULL)
2310 {
2311 deftime.modtime = deftime.actime = time (NULL);
2312 times = &deftime;
2313 }
2314
2315 /* Need write access to set times. */
2316 fh = CreateFile (name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
2317 0, OPEN_EXISTING, 0, NULL);
2318 if (fh)
2319 {
2320 convert_from_time_t (times->actime, &atime);
2321 convert_from_time_t (times->modtime, &mtime);
2322 if (!SetFileTime (fh, NULL, &atime, &mtime))
2323 {
2324 CloseHandle (fh);
2325 errno = EACCES;
2326 return -1;
2327 }
2328 CloseHandle (fh);
2329 }
2330 else
2331 {
2332 errno = EINVAL;
2333 return -1;
2334 }
2335 return 0;
2336 }
2337
2338 #ifdef HAVE_SOCKETS
2339
2340 /* Wrappers for winsock functions to map between our file descriptors
2341 and winsock's handles; also set h_errno for convenience.
2342
2343 To allow Emacs to run on systems which don't have winsock support
2344 installed, we dynamically link to winsock on startup if present, and
2345 otherwise provide the minimum necessary functionality
2346 (eg. gethostname). */
2347
2348 /* function pointers for relevant socket functions */
2349 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
2350 void (PASCAL *pfn_WSASetLastError) (int iError);
2351 int (PASCAL *pfn_WSAGetLastError) (void);
2352 int (PASCAL *pfn_socket) (int af, int type, int protocol);
2353 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
2354 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
2355 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
2356 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
2357 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
2358 int (PASCAL *pfn_closesocket) (SOCKET s);
2359 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
2360 int (PASCAL *pfn_WSACleanup) (void);
2361
2362 u_short (PASCAL *pfn_htons) (u_short hostshort);
2363 u_short (PASCAL *pfn_ntohs) (u_short netshort);
2364 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
2365 int (PASCAL *pfn_gethostname) (char * name, int namelen);
2366 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
2367 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
2368
2369 /* SetHandleInformation is only needed to make sockets non-inheritable. */
2370 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
2371 #ifndef HANDLE_FLAG_INHERIT
2372 #define HANDLE_FLAG_INHERIT 1
2373 #endif
2374
2375 HANDLE winsock_lib;
2376 static int winsock_inuse;
2377
2378 BOOL
2379 term_winsock (void)
2380 {
2381 if (winsock_lib != NULL && winsock_inuse == 0)
2382 {
2383 /* Not sure what would cause WSAENETDOWN, or even if it can happen
2384 after WSAStartup returns successfully, but it seems reasonable
2385 to allow unloading winsock anyway in that case. */
2386 if (pfn_WSACleanup () == 0 ||
2387 pfn_WSAGetLastError () == WSAENETDOWN)
2388 {
2389 if (FreeLibrary (winsock_lib))
2390 winsock_lib = NULL;
2391 return TRUE;
2392 }
2393 }
2394 return FALSE;
2395 }
2396
2397 BOOL
2398 init_winsock (int load_now)
2399 {
2400 WSADATA winsockData;
2401
2402 if (winsock_lib != NULL)
2403 return TRUE;
2404
2405 pfn_SetHandleInformation = NULL;
2406 pfn_SetHandleInformation
2407 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2408 "SetHandleInformation");
2409
2410 winsock_lib = LoadLibrary ("wsock32.dll");
2411
2412 if (winsock_lib != NULL)
2413 {
2414 /* dynamically link to socket functions */
2415
2416 #define LOAD_PROC(fn) \
2417 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2418 goto fail;
2419
2420 LOAD_PROC( WSAStartup );
2421 LOAD_PROC( WSASetLastError );
2422 LOAD_PROC( WSAGetLastError );
2423 LOAD_PROC( socket );
2424 LOAD_PROC( bind );
2425 LOAD_PROC( connect );
2426 LOAD_PROC( ioctlsocket );
2427 LOAD_PROC( recv );
2428 LOAD_PROC( send );
2429 LOAD_PROC( closesocket );
2430 LOAD_PROC( shutdown );
2431 LOAD_PROC( htons );
2432 LOAD_PROC( ntohs );
2433 LOAD_PROC( inet_addr );
2434 LOAD_PROC( gethostname );
2435 LOAD_PROC( gethostbyname );
2436 LOAD_PROC( getservbyname );
2437 LOAD_PROC( WSACleanup );
2438
2439 #undef LOAD_PROC
2440
2441 /* specify version 1.1 of winsock */
2442 if (pfn_WSAStartup (0x101, &winsockData) == 0)
2443 {
2444 if (winsockData.wVersion != 0x101)
2445 goto fail;
2446
2447 if (!load_now)
2448 {
2449 /* Report that winsock exists and is usable, but leave
2450 socket functions disabled. I am assuming that calling
2451 WSAStartup does not require any network interaction,
2452 and in particular does not cause or require a dial-up
2453 connection to be established. */
2454
2455 pfn_WSACleanup ();
2456 FreeLibrary (winsock_lib);
2457 winsock_lib = NULL;
2458 }
2459 winsock_inuse = 0;
2460 return TRUE;
2461 }
2462
2463 fail:
2464 FreeLibrary (winsock_lib);
2465 winsock_lib = NULL;
2466 }
2467
2468 return FALSE;
2469 }
2470
2471
2472 int h_errno = 0;
2473
2474 /* function to set h_errno for compatability; map winsock error codes to
2475 normal system codes where they overlap (non-overlapping definitions
2476 are already in <sys/socket.h> */
2477 static void set_errno ()
2478 {
2479 if (winsock_lib == NULL)
2480 h_errno = EINVAL;
2481 else
2482 h_errno = pfn_WSAGetLastError ();
2483
2484 switch (h_errno)
2485 {
2486 case WSAEACCES: h_errno = EACCES; break;
2487 case WSAEBADF: h_errno = EBADF; break;
2488 case WSAEFAULT: h_errno = EFAULT; break;
2489 case WSAEINTR: h_errno = EINTR; break;
2490 case WSAEINVAL: h_errno = EINVAL; break;
2491 case WSAEMFILE: h_errno = EMFILE; break;
2492 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
2493 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
2494 }
2495 errno = h_errno;
2496 }
2497
2498 static void check_errno ()
2499 {
2500 if (h_errno == 0 && winsock_lib != NULL)
2501 pfn_WSASetLastError (0);
2502 }
2503
2504 /* Extend strerror to handle the winsock-specific error codes. */
2505 struct {
2506 int errnum;
2507 char * msg;
2508 } _wsa_errlist[] = {
2509 WSAEINTR , "Interrupted function call",
2510 WSAEBADF , "Bad file descriptor",
2511 WSAEACCES , "Permission denied",
2512 WSAEFAULT , "Bad address",
2513 WSAEINVAL , "Invalid argument",
2514 WSAEMFILE , "Too many open files",
2515
2516 WSAEWOULDBLOCK , "Resource temporarily unavailable",
2517 WSAEINPROGRESS , "Operation now in progress",
2518 WSAEALREADY , "Operation already in progress",
2519 WSAENOTSOCK , "Socket operation on non-socket",
2520 WSAEDESTADDRREQ , "Destination address required",
2521 WSAEMSGSIZE , "Message too long",
2522 WSAEPROTOTYPE , "Protocol wrong type for socket",
2523 WSAENOPROTOOPT , "Bad protocol option",
2524 WSAEPROTONOSUPPORT , "Protocol not supported",
2525 WSAESOCKTNOSUPPORT , "Socket type not supported",
2526 WSAEOPNOTSUPP , "Operation not supported",
2527 WSAEPFNOSUPPORT , "Protocol family not supported",
2528 WSAEAFNOSUPPORT , "Address family not supported by protocol family",
2529 WSAEADDRINUSE , "Address already in use",
2530 WSAEADDRNOTAVAIL , "Cannot assign requested address",
2531 WSAENETDOWN , "Network is down",
2532 WSAENETUNREACH , "Network is unreachable",
2533 WSAENETRESET , "Network dropped connection on reset",
2534 WSAECONNABORTED , "Software caused connection abort",
2535 WSAECONNRESET , "Connection reset by peer",
2536 WSAENOBUFS , "No buffer space available",
2537 WSAEISCONN , "Socket is already connected",
2538 WSAENOTCONN , "Socket is not connected",
2539 WSAESHUTDOWN , "Cannot send after socket shutdown",
2540 WSAETOOMANYREFS , "Too many references", /* not sure */
2541 WSAETIMEDOUT , "Connection timed out",
2542 WSAECONNREFUSED , "Connection refused",
2543 WSAELOOP , "Network loop", /* not sure */
2544 WSAENAMETOOLONG , "Name is too long",
2545 WSAEHOSTDOWN , "Host is down",
2546 WSAEHOSTUNREACH , "No route to host",
2547 WSAENOTEMPTY , "Buffer not empty", /* not sure */
2548 WSAEPROCLIM , "Too many processes",
2549 WSAEUSERS , "Too many users", /* not sure */
2550 WSAEDQUOT , "Double quote in host name", /* really not sure */
2551 WSAESTALE , "Data is stale", /* not sure */
2552 WSAEREMOTE , "Remote error", /* not sure */
2553
2554 WSASYSNOTREADY , "Network subsystem is unavailable",
2555 WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range",
2556 WSANOTINITIALISED , "Winsock not initialized successfully",
2557 WSAEDISCON , "Graceful shutdown in progress",
2558 #ifdef WSAENOMORE
2559 WSAENOMORE , "No more operations allowed", /* not sure */
2560 WSAECANCELLED , "Operation cancelled", /* not sure */
2561 WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider",
2562 WSAEINVALIDPROVIDER , "Invalid service provider version number",
2563 WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider",
2564 WSASYSCALLFAILURE , "System call failured",
2565 WSASERVICE_NOT_FOUND , "Service not found", /* not sure */
2566 WSATYPE_NOT_FOUND , "Class type not found",
2567 WSA_E_NO_MORE , "No more resources available", /* really not sure */
2568 WSA_E_CANCELLED , "Operation already cancelled", /* really not sure */
2569 WSAEREFUSED , "Operation refused", /* not sure */
2570 #endif
2571
2572 WSAHOST_NOT_FOUND , "Host not found",
2573 WSATRY_AGAIN , "Authoritative host not found during name lookup",
2574 WSANO_RECOVERY , "Non-recoverable error during name lookup",
2575 WSANO_DATA , "Valid name, no data record of requested type",
2576
2577 -1, NULL
2578 };
2579
2580 char *
2581 sys_strerror(int error_no)
2582 {
2583 int i;
2584 static char unknown_msg[40];
2585
2586 if (error_no >= 0 && error_no < sys_nerr)
2587 return sys_errlist[error_no];
2588
2589 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
2590 if (_wsa_errlist[i].errnum == error_no)
2591 return _wsa_errlist[i].msg;
2592
2593 sprintf(unknown_msg, "Unidentified error: %d", error_no);
2594 return unknown_msg;
2595 }
2596
2597 /* [andrewi 3-May-96] I've had conflicting results using both methods,
2598 but I believe the method of keeping the socket handle separate (and
2599 insuring it is not inheritable) is the correct one. */
2600
2601 //#define SOCK_REPLACE_HANDLE
2602
2603 #ifdef SOCK_REPLACE_HANDLE
2604 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2605 #else
2606 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2607 #endif
2608
2609 int
2610 sys_socket(int af, int type, int protocol)
2611 {
2612 int fd;
2613 long s;
2614 child_process * cp;
2615
2616 if (winsock_lib == NULL)
2617 {
2618 h_errno = ENETDOWN;
2619 return INVALID_SOCKET;
2620 }
2621
2622 check_errno ();
2623
2624 /* call the real socket function */
2625 s = (long) pfn_socket (af, type, protocol);
2626
2627 if (s != INVALID_SOCKET)
2628 {
2629 /* Although under NT 3.5 _open_osfhandle will accept a socket
2630 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
2631 that does not work under NT 3.1. However, we can get the same
2632 effect by using a backdoor function to replace an existing
2633 descriptor handle with the one we want. */
2634
2635 /* allocate a file descriptor (with appropriate flags) */
2636 fd = _open ("NUL:", _O_RDWR);
2637 if (fd >= 0)
2638 {
2639 #ifdef SOCK_REPLACE_HANDLE
2640 /* now replace handle to NUL with our socket handle */
2641 CloseHandle ((HANDLE) _get_osfhandle (fd));
2642 _free_osfhnd (fd);
2643 _set_osfhnd (fd, s);
2644 /* setmode (fd, _O_BINARY); */
2645 #else
2646 /* Make a non-inheritable copy of the socket handle. Note
2647 that it is possible that sockets aren't actually kernel
2648 handles, which appears to be the case on Windows 9x when
2649 the MS Proxy winsock client is installed. */
2650 {
2651 /* Apparently there is a bug in NT 3.51 with some service
2652 packs, which prevents using DuplicateHandle to make a
2653 socket handle non-inheritable (causes WSACleanup to
2654 hang). The work-around is to use SetHandleInformation
2655 instead if it is available and implemented. */
2656 if (pfn_SetHandleInformation)
2657 {
2658 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
2659 }
2660 else
2661 {
2662 HANDLE parent = GetCurrentProcess ();
2663 HANDLE new_s = INVALID_HANDLE_VALUE;
2664
2665 if (DuplicateHandle (parent,
2666 (HANDLE) s,
2667 parent,
2668 &new_s,
2669 0,
2670 FALSE,
2671 DUPLICATE_SAME_ACCESS))
2672 {
2673 /* It is possible that DuplicateHandle succeeds even
2674 though the socket wasn't really a kernel handle,
2675 because a real handle has the same value. So
2676 test whether the new handle really is a socket. */
2677 long nonblocking = 0;
2678 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
2679 {
2680 pfn_closesocket (s);
2681 s = (SOCKET) new_s;
2682 }
2683 else
2684 {
2685 CloseHandle (new_s);
2686 }
2687 }
2688 }
2689 }
2690 fd_info[fd].hnd = (HANDLE) s;
2691 #endif
2692
2693 /* set our own internal flags */
2694 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
2695
2696 cp = new_child ();
2697 if (cp)
2698 {
2699 cp->fd = fd;
2700 cp->status = STATUS_READ_ACKNOWLEDGED;
2701
2702 /* attach child_process to fd_info */
2703 if (fd_info[ fd ].cp != NULL)
2704 {
2705 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
2706 abort ();
2707 }
2708
2709 fd_info[ fd ].cp = cp;
2710
2711 /* success! */
2712 winsock_inuse++; /* count open sockets */
2713 return fd;
2714 }
2715
2716 /* clean up */
2717 _close (fd);
2718 }
2719 pfn_closesocket (s);
2720 h_errno = EMFILE;
2721 }
2722 set_errno ();
2723
2724 return -1;
2725 }
2726
2727
2728 int
2729 sys_bind (int s, const struct sockaddr * addr, int namelen)
2730 {
2731 if (winsock_lib == NULL)
2732 {
2733 h_errno = ENOTSOCK;
2734 return SOCKET_ERROR;
2735 }
2736
2737 check_errno ();
2738 if (fd_info[s].flags & FILE_SOCKET)
2739 {
2740 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
2741 if (rc == SOCKET_ERROR)
2742 set_errno ();
2743 return rc;
2744 }
2745 h_errno = ENOTSOCK;
2746 return SOCKET_ERROR;
2747 }
2748
2749
2750 int
2751 sys_connect (int s, const struct sockaddr * name, int namelen)
2752 {
2753 if (winsock_lib == NULL)
2754 {
2755 h_errno = ENOTSOCK;
2756 return SOCKET_ERROR;
2757 }
2758
2759 check_errno ();
2760 if (fd_info[s].flags & FILE_SOCKET)
2761 {
2762 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
2763 if (rc == SOCKET_ERROR)
2764 set_errno ();
2765 return rc;
2766 }
2767 h_errno = ENOTSOCK;
2768 return SOCKET_ERROR;
2769 }
2770
2771 u_short
2772 sys_htons (u_short hostshort)
2773 {
2774 return (winsock_lib != NULL) ?
2775 pfn_htons (hostshort) : hostshort;
2776 }
2777
2778 u_short
2779 sys_ntohs (u_short netshort)
2780 {
2781 return (winsock_lib != NULL) ?
2782 pfn_ntohs (netshort) : netshort;
2783 }
2784
2785 unsigned long
2786 sys_inet_addr (const char * cp)
2787 {
2788 return (winsock_lib != NULL) ?
2789 pfn_inet_addr (cp) : INADDR_NONE;
2790 }
2791
2792 int
2793 sys_gethostname (char * name, int namelen)
2794 {
2795 if (winsock_lib != NULL)
2796 return pfn_gethostname (name, namelen);
2797
2798 if (namelen > MAX_COMPUTERNAME_LENGTH)
2799 return !GetComputerName (name, (DWORD *)&namelen);
2800
2801 h_errno = EFAULT;
2802 return SOCKET_ERROR;
2803 }
2804
2805 struct hostent *
2806 sys_gethostbyname(const char * name)
2807 {
2808 struct hostent * host;
2809
2810 if (winsock_lib == NULL)
2811 {
2812 h_errno = ENETDOWN;
2813 return NULL;
2814 }
2815
2816 check_errno ();
2817 host = pfn_gethostbyname (name);
2818 if (!host)
2819 set_errno ();
2820 return host;
2821 }
2822
2823 struct servent *
2824 sys_getservbyname(const char * name, const char * proto)
2825 {
2826 struct servent * serv;
2827
2828 if (winsock_lib == NULL)
2829 {
2830 h_errno = ENETDOWN;
2831 return NULL;
2832 }
2833
2834 check_errno ();
2835 serv = pfn_getservbyname (name, proto);
2836 if (!serv)
2837 set_errno ();
2838 return serv;
2839 }
2840
2841 int
2842 sys_shutdown (int s, int how)
2843 {
2844 int rc;
2845
2846 if (winsock_lib == NULL)
2847 {
2848 h_errno = ENETDOWN;
2849 return SOCKET_ERROR;
2850 }
2851
2852 check_errno ();
2853 if (fd_info[s].flags & FILE_SOCKET)
2854 {
2855 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
2856 if (rc == SOCKET_ERROR)
2857 set_errno ();
2858 return rc;
2859 }
2860 h_errno = ENOTSOCK;
2861 return SOCKET_ERROR;
2862 }
2863
2864 #endif /* HAVE_SOCKETS */
2865
2866
2867 /* Shadow main io functions: we need to handle pipes and sockets more
2868 intelligently, and implement non-blocking mode as well. */
2869
2870 int
2871 sys_close (int fd)
2872 {
2873 int rc;
2874
2875 if (fd < 0 || fd >= MAXDESC)
2876 {
2877 errno = EBADF;
2878 return -1;
2879 }
2880
2881 if (fd_info[fd].cp)
2882 {
2883 child_process * cp = fd_info[fd].cp;
2884
2885 fd_info[fd].cp = NULL;
2886
2887 if (CHILD_ACTIVE (cp))
2888 {
2889 /* if last descriptor to active child_process then cleanup */
2890 int i;
2891 for (i = 0; i < MAXDESC; i++)
2892 {
2893 if (i == fd)
2894 continue;
2895 if (fd_info[i].cp == cp)
2896 break;
2897 }
2898 if (i == MAXDESC)
2899 {
2900 #ifdef HAVE_SOCKETS
2901 if (fd_info[fd].flags & FILE_SOCKET)
2902 {
2903 #ifndef SOCK_REPLACE_HANDLE
2904 if (winsock_lib == NULL) abort ();
2905
2906 pfn_shutdown (SOCK_HANDLE (fd), 2);
2907 rc = pfn_closesocket (SOCK_HANDLE (fd));
2908 #endif
2909 winsock_inuse--; /* count open sockets */
2910 }
2911 #endif
2912 delete_child (cp);
2913 }
2914 }
2915 }
2916
2917 /* Note that sockets do not need special treatment here (at least on
2918 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
2919 closesocket is equivalent to CloseHandle, which is to be expected
2920 because socket handles are fully fledged kernel handles. */
2921 rc = _close (fd);
2922
2923 if (rc == 0)
2924 fd_info[fd].flags = 0;
2925
2926 return rc;
2927 }
2928
2929 int
2930 sys_dup (int fd)
2931 {
2932 int new_fd;
2933
2934 new_fd = _dup (fd);
2935 if (new_fd >= 0)
2936 {
2937 /* duplicate our internal info as well */
2938 fd_info[new_fd] = fd_info[fd];
2939 }
2940 return new_fd;
2941 }
2942
2943
2944 int
2945 sys_dup2 (int src, int dst)
2946 {
2947 int rc;
2948
2949 if (dst < 0 || dst >= MAXDESC)
2950 {
2951 errno = EBADF;
2952 return -1;
2953 }
2954
2955 /* make sure we close the destination first if it's a pipe or socket */
2956 if (src != dst && fd_info[dst].flags != 0)
2957 sys_close (dst);
2958
2959 rc = _dup2 (src, dst);
2960 if (rc == 0)
2961 {
2962 /* duplicate our internal info as well */
2963 fd_info[dst] = fd_info[src];
2964 }
2965 return rc;
2966 }
2967
2968 /* Unix pipe() has only one arg */
2969 int
2970 sys_pipe (int * phandles)
2971 {
2972 int rc;
2973 unsigned flags;
2974 child_process * cp;
2975
2976 /* make pipe handles non-inheritable; when we spawn a child, we
2977 replace the relevant handle with an inheritable one. Also put
2978 pipes into binary mode; we will do text mode translation ourselves
2979 if required. */
2980 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
2981
2982 if (rc == 0)
2983 {
2984 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
2985 fd_info[phandles[0]].flags = flags;
2986
2987 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
2988 fd_info[phandles[1]].flags = flags;
2989 }
2990
2991 return rc;
2992 }
2993
2994 /* From ntproc.c */
2995 extern Lisp_Object Vw32_pipe_read_delay;
2996
2997 /* Function to do blocking read of one byte, needed to implement
2998 select. It is only allowed on sockets and pipes. */
2999 int
3000 _sys_read_ahead (int fd)
3001 {
3002 child_process * cp;
3003 int rc;
3004
3005 if (fd < 0 || fd >= MAXDESC)
3006 return STATUS_READ_ERROR;
3007
3008 cp = fd_info[fd].cp;
3009
3010 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
3011 return STATUS_READ_ERROR;
3012
3013 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET)) == 0
3014 || (fd_info[fd].flags & FILE_READ) == 0)
3015 {
3016 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd));
3017 abort ();
3018 }
3019
3020 cp->status = STATUS_READ_IN_PROGRESS;
3021
3022 if (fd_info[fd].flags & FILE_PIPE)
3023 {
3024 rc = _read (fd, &cp->chr, sizeof (char));
3025
3026 /* Give subprocess time to buffer some more output for us before
3027 reporting that input is available; we need this because Windows 95
3028 connects DOS programs to pipes by making the pipe appear to be
3029 the normal console stdout - as a result most DOS programs will
3030 write to stdout without buffering, ie. one character at a
3031 time. Even some W32 programs do this - "dir" in a command
3032 shell on NT is very slow if we don't do this. */
3033 if (rc > 0)
3034 {
3035 int wait = XINT (Vw32_pipe_read_delay);
3036
3037 if (wait > 0)
3038 Sleep (wait);
3039 else if (wait < 0)
3040 while (++wait <= 0)
3041 /* Yield remainder of our time slice, effectively giving a
3042 temporary priority boost to the child process. */
3043 Sleep (0);
3044 }
3045 }
3046 #ifdef HAVE_SOCKETS
3047 else if (fd_info[fd].flags & FILE_SOCKET)
3048 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
3049 #endif
3050
3051 if (rc == sizeof (char))
3052 cp->status = STATUS_READ_SUCCEEDED;
3053 else
3054 cp->status = STATUS_READ_FAILED;
3055
3056 return cp->status;
3057 }
3058
3059 int
3060 sys_read (int fd, char * buffer, unsigned int count)
3061 {
3062 int nchars;
3063 int to_read;
3064 DWORD waiting;
3065 char * orig_buffer = buffer;
3066
3067 if (fd < 0 || fd >= MAXDESC)
3068 {
3069 errno = EBADF;
3070 return -1;
3071 }
3072
3073 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
3074 {
3075 child_process *cp = fd_info[fd].cp;
3076
3077 if ((fd_info[fd].flags & FILE_READ) == 0)
3078 {
3079 errno = EBADF;
3080 return -1;
3081 }
3082
3083 nchars = 0;
3084
3085 /* re-read CR carried over from last read */
3086 if (fd_info[fd].flags & FILE_LAST_CR)
3087 {
3088 if (fd_info[fd].flags & FILE_BINARY) abort ();
3089 *buffer++ = 0x0d;
3090 count--;
3091 nchars++;
3092 fd_info[fd].flags &= ~FILE_LAST_CR;
3093 }
3094
3095 /* presence of a child_process structure means we are operating in
3096 non-blocking mode - otherwise we just call _read directly.
3097 Note that the child_process structure might be missing because
3098 reap_subprocess has been called; in this case the pipe is
3099 already broken, so calling _read on it is okay. */
3100 if (cp)
3101 {
3102 int current_status = cp->status;
3103
3104 switch (current_status)
3105 {
3106 case STATUS_READ_FAILED:
3107 case STATUS_READ_ERROR:
3108 /* report normal EOF if nothing in buffer */
3109 if (nchars <= 0)
3110 fd_info[fd].flags |= FILE_AT_EOF;
3111 return nchars;
3112
3113 case STATUS_READ_READY:
3114 case STATUS_READ_IN_PROGRESS:
3115 DebPrint (("sys_read called when read is in progress\n"));
3116 errno = EWOULDBLOCK;
3117 return -1;
3118
3119 case STATUS_READ_SUCCEEDED:
3120 /* consume read-ahead char */
3121 *buffer++ = cp->chr;
3122 count--;
3123 nchars++;
3124 cp->status = STATUS_READ_ACKNOWLEDGED;
3125 ResetEvent (cp->char_avail);
3126
3127 case STATUS_READ_ACKNOWLEDGED:
3128 break;
3129
3130 default:
3131 DebPrint (("sys_read: bad status %d\n", current_status));
3132 errno = EBADF;
3133 return -1;
3134 }
3135
3136 if (fd_info[fd].flags & FILE_PIPE)
3137 {
3138 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
3139 to_read = min (waiting, (DWORD) count);
3140
3141 if (to_read > 0)
3142 nchars += _read (fd, buffer, to_read);
3143 }
3144 #ifdef HAVE_SOCKETS
3145 else /* FILE_SOCKET */
3146 {
3147 if (winsock_lib == NULL) abort ();
3148
3149 /* do the equivalent of a non-blocking read */
3150 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
3151 if (waiting == 0 && nchars == 0)
3152 {
3153 h_errno = errno = EWOULDBLOCK;
3154 return -1;
3155 }
3156
3157 if (waiting)
3158 {
3159 /* always use binary mode for sockets */
3160 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
3161 if (res == SOCKET_ERROR)
3162 {
3163 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
3164 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
3165 set_errno ();
3166 return -1;
3167 }
3168 nchars += res;
3169 }
3170 }
3171 #endif
3172 }
3173 else
3174 {
3175 int nread = _read (fd, buffer, count);
3176 if (nread >= 0)
3177 nchars += nread;
3178 else if (nchars == 0)
3179 nchars = nread;
3180 }
3181
3182 if (nchars <= 0)
3183 fd_info[fd].flags |= FILE_AT_EOF;
3184 /* Perform text mode translation if required. */
3185 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
3186 {
3187 nchars = crlf_to_lf (nchars, orig_buffer);
3188 /* If buffer contains only CR, return that. To be absolutely
3189 sure we should attempt to read the next char, but in
3190 practice a CR to be followed by LF would not appear by
3191 itself in the buffer. */
3192 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
3193 {
3194 fd_info[fd].flags |= FILE_LAST_CR;
3195 nchars--;
3196 }
3197 }
3198 }
3199 else
3200 nchars = _read (fd, buffer, count);
3201
3202 return nchars;
3203 }
3204
3205 /* For now, don't bother with a non-blocking mode */
3206 int
3207 sys_write (int fd, const void * buffer, unsigned int count)
3208 {
3209 int nchars;
3210
3211 if (fd < 0 || fd >= MAXDESC)
3212 {
3213 errno = EBADF;
3214 return -1;
3215 }
3216
3217 if (fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET))
3218 {
3219 if ((fd_info[fd].flags & FILE_WRITE) == 0)
3220 {
3221 errno = EBADF;
3222 return -1;
3223 }
3224
3225 /* Perform text mode translation if required. */
3226 if ((fd_info[fd].flags & FILE_BINARY) == 0)
3227 {
3228 char * tmpbuf = alloca (count * 2);
3229 unsigned char * src = (void *)buffer;
3230 unsigned char * dst = tmpbuf;
3231 int nbytes = count;
3232
3233 while (1)
3234 {
3235 unsigned char *next;
3236 /* copy next line or remaining bytes */
3237 next = _memccpy (dst, src, '\n', nbytes);
3238 if (next)
3239 {
3240 /* copied one line ending with '\n' */
3241 int copied = next - dst;
3242 nbytes -= copied;
3243 src += copied;
3244 /* insert '\r' before '\n' */
3245 next[-1] = '\r';
3246 next[0] = '\n';
3247 dst = next + 1;
3248 count++;
3249 }
3250 else
3251 /* copied remaining partial line -> now finished */
3252 break;
3253 }
3254 buffer = tmpbuf;
3255 }
3256 }
3257
3258 #ifdef HAVE_SOCKETS
3259 if (fd_info[fd].flags & FILE_SOCKET)
3260 {
3261 if (winsock_lib == NULL) abort ();
3262 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
3263 if (nchars == SOCKET_ERROR)
3264 {
3265 DebPrint(("sys_read.send failed with error %d on socket %ld\n",
3266 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
3267 set_errno ();
3268 }
3269 }
3270 else
3271 #endif
3272 nchars = _write (fd, buffer, count);
3273
3274 return nchars;
3275 }
3276
3277 static void
3278 check_windows_init_file ()
3279 {
3280 extern int noninteractive, inhibit_window_system;
3281
3282 /* A common indication that Emacs is not installed properly is when
3283 it cannot find the Windows installation file. If this file does
3284 not exist in the expected place, tell the user. */
3285
3286 if (!noninteractive && !inhibit_window_system)
3287 {
3288 extern Lisp_Object Vwindow_system, Vload_path, Qfile_exists_p;
3289 Lisp_Object objs[2];
3290 Lisp_Object full_load_path;
3291 Lisp_Object init_file;
3292 int fd;
3293
3294 objs[0] = Vload_path;
3295 objs[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
3296 full_load_path = Fappend (2, objs);
3297 init_file = build_string ("term/w32-win");
3298 fd = openp (full_load_path, init_file, ".el:.elc", NULL, 0);
3299 if (fd < 0)
3300 {
3301 Lisp_Object load_path_print = Fprin1_to_string (full_load_path, Qnil);
3302 char *init_file_name = XSTRING (init_file)->data;
3303 char *load_path = XSTRING (load_path_print)->data;
3304 char *buffer = alloca (1024);
3305
3306 sprintf (buffer,
3307 "The Emacs Windows initialization file \"%s.el\" "
3308 "could not be found in your Emacs installation. "
3309 "Emacs checked the following directories for this file:\n"
3310 "\n%s\n\n"
3311 "When Emacs cannot find this file, it usually means that it "
3312 "was not installed properly, or its distribution file was "
3313 "not unpacked properly.\nSee the README.W32 file in the "
3314 "top-level Emacs directory for more information.",
3315 init_file_name, load_path);
3316 MessageBox (NULL,
3317 buffer,
3318 "Emacs Abort Dialog",
3319 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
3320 /* Use the low-level Emacs abort. */
3321 #undef abort
3322 abort ();
3323 }
3324 else
3325 {
3326 _close (fd);
3327 }
3328 }
3329 }
3330
3331 void
3332 term_ntproc ()
3333 {
3334 #ifdef HAVE_SOCKETS
3335 /* shutdown the socket interface if necessary */
3336 term_winsock ();
3337 #endif
3338 }
3339
3340 void
3341 init_ntproc ()
3342 {
3343 #ifdef HAVE_SOCKETS
3344 /* Initialise the socket interface now if available and requested by
3345 the user by defining PRELOAD_WINSOCK; otherwise loading will be
3346 delayed until open-network-stream is called (w32-has-winsock can
3347 also be used to dynamically load or reload winsock).
3348
3349 Conveniently, init_environment is called before us, so
3350 PRELOAD_WINSOCK can be set in the registry. */
3351
3352 /* Always initialize this correctly. */
3353 winsock_lib = NULL;
3354
3355 if (getenv ("PRELOAD_WINSOCK") != NULL)
3356 init_winsock (TRUE);
3357 #endif
3358
3359 /* Initial preparation for subprocess support: replace our standard
3360 handles with non-inheritable versions. */
3361 {
3362 HANDLE parent;
3363 HANDLE stdin_save = INVALID_HANDLE_VALUE;
3364 HANDLE stdout_save = INVALID_HANDLE_VALUE;
3365 HANDLE stderr_save = INVALID_HANDLE_VALUE;
3366
3367 parent = GetCurrentProcess ();
3368
3369 /* ignore errors when duplicating and closing; typically the
3370 handles will be invalid when running as a gui program. */
3371 DuplicateHandle (parent,
3372 GetStdHandle (STD_INPUT_HANDLE),
3373 parent,
3374 &stdin_save,
3375 0,
3376 FALSE,
3377 DUPLICATE_SAME_ACCESS);
3378
3379 DuplicateHandle (parent,
3380 GetStdHandle (STD_OUTPUT_HANDLE),
3381 parent,
3382 &stdout_save,
3383 0,
3384 FALSE,
3385 DUPLICATE_SAME_ACCESS);
3386
3387 DuplicateHandle (parent,
3388 GetStdHandle (STD_ERROR_HANDLE),
3389 parent,
3390 &stderr_save,
3391 0,
3392 FALSE,
3393 DUPLICATE_SAME_ACCESS);
3394
3395 fclose (stdin);
3396 fclose (stdout);
3397 fclose (stderr);
3398
3399 if (stdin_save != INVALID_HANDLE_VALUE)
3400 _open_osfhandle ((long) stdin_save, O_TEXT);
3401 else
3402 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
3403 _fdopen (0, "r");
3404
3405 if (stdout_save != INVALID_HANDLE_VALUE)
3406 _open_osfhandle ((long) stdout_save, O_TEXT);
3407 else
3408 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
3409 _fdopen (1, "w");
3410
3411 if (stderr_save != INVALID_HANDLE_VALUE)
3412 _open_osfhandle ((long) stderr_save, O_TEXT);
3413 else
3414 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
3415 _fdopen (2, "w");
3416 }
3417
3418 /* unfortunately, atexit depends on implementation of malloc */
3419 /* atexit (term_ntproc); */
3420 signal (SIGABRT, term_ntproc);
3421
3422 /* determine which drives are fixed, for GetCachedVolumeInformation */
3423 {
3424 /* GetDriveType must have trailing backslash. */
3425 char drive[] = "A:\\";
3426
3427 /* Loop over all possible drive letters */
3428 while (*drive <= 'Z')
3429 {
3430 /* Record if this drive letter refers to a fixed drive. */
3431 fixed_drives[DRIVE_INDEX (*drive)] =
3432 (GetDriveType (drive) == DRIVE_FIXED);
3433
3434 (*drive)++;
3435 }
3436
3437 /* Reset the volume info cache. */
3438 volume_cache = NULL;
3439 }
3440
3441 /* Check to see if Emacs has been installed correctly. */
3442 check_windows_init_file ();
3443 }
3444
3445 /* end of nt.c */