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