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