1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 API.
2 Copyright (C) 1994, 1995, 2000, 2001 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
23 #include <stddef.h> /* for offsetof */
33 #include <sys/utime.h>
35 /* must include CRT headers *before* config.h */
70 #define _ANONYMOUS_UNION
71 #define _ANONYMOUS_STRUCT
76 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
77 #include <sys/socket.h>
102 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
103 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
105 void globals_of_w32 ();
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
;
114 Initialization states
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
;
123 BEGIN: Wrapper functions around OpenProcessToken
124 and other functions in advapi32.dll that are only
125 supported in Windows NT / 2k / XP
127 /* ** Function pointer typedefs ** */
128 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
129 HANDLE ProcessHandle
,
131 PHANDLE TokenHandle
);
132 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
134 TOKEN_INFORMATION_CLASS TokenInformationClass
,
135 LPVOID TokenInformation
,
136 DWORD TokenInformationLength
,
137 PDWORD ReturnLength
);
139 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
141 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
143 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
144 LPCTSTR lpSystemName
,
149 LPDWORD cbDomainName
,
150 PSID_NAME_USE peUse
);
151 typedef PSID_IDENTIFIER_AUTHORITY (WINAPI
* GetSidIdentifierAuthority_Proc
) (
154 /* ** A utility function ** */
155 static BOOL
is_windows_9x ()
157 static BOOL s_b_ret
=0;
158 OSVERSIONINFO os_ver
;
159 if (g_b_init_is_windows_9x
== 0)
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
))
166 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
172 /* ** The wrapper functions ** */
174 BOOL WINAPI
open_process_token (
175 HANDLE ProcessHandle
,
179 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
180 HMODULE hm_advapi32
= NULL
;
181 if (is_windows_9x () == TRUE
)
185 if (g_b_init_open_process_token
== 0)
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");
192 if (s_pfn_Open_Process_Token
== NULL
)
197 s_pfn_Open_Process_Token (
204 BOOL WINAPI
get_token_information (
206 TOKEN_INFORMATION_CLASS TokenInformationClass
,
207 LPVOID TokenInformation
,
208 DWORD TokenInformationLength
,
211 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
212 HMODULE hm_advapi32
= NULL
;
213 if (is_windows_9x () == TRUE
)
217 if (g_b_init_get_token_information
== 0)
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");
224 if (s_pfn_Get_Token_Information
== NULL
)
229 s_pfn_Get_Token_Information (
231 TokenInformationClass
,
233 TokenInformationLength
,
238 BOOL WINAPI
lookup_account_sid (
239 LPCTSTR lpSystemName
,
244 LPDWORD cbDomainName
,
247 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
248 HMODULE hm_advapi32
= NULL
;
249 if (is_windows_9x () == TRUE
)
253 if (g_b_init_lookup_account_sid
== 0)
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
);
260 if (s_pfn_Lookup_Account_Sid
== NULL
)
265 s_pfn_Lookup_Account_Sid (
276 PSID_IDENTIFIER_AUTHORITY WINAPI
get_sid_identifier_authority (
279 static GetSidIdentifierAuthority_Proc s_pfn_Get_Sid_Identifier_Authority
= NULL
;
280 HMODULE hm_advapi32
= NULL
;
281 if (is_windows_9x () == TRUE
)
285 if (g_b_init_get_sid_identifier_authority
== 0)
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");
293 if (s_pfn_Get_Sid_Identifier_Authority
== NULL
)
297 return (s_pfn_Get_Sid_Identifier_Authority (pSid
));
301 END: Wrapper functions around OpenProcessToken
302 and other functions in advapi32.dll that are only
303 supported in Windows NT / 2k / XP
307 /* Equivalent of strerror for W32 error codes. */
309 w32_strerror (int error_no
)
311 static char buf
[500];
314 error_no
= GetLastError ();
317 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
, NULL
,
319 0, /* choose most suitable language */
320 buf
, sizeof (buf
), NULL
))
321 sprintf (buf
, "w32 error %u", error_no
);
325 static char startup_dir
[MAXPATHLEN
];
327 /* Get the current working directory. */
332 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
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
);
345 /* Emulate gethostname. */
347 gethostname (char *buffer
, int size
)
349 /* NT only allows small host names, so the buffer is
350 certainly large enough. */
351 return !GetComputerName (buffer
, &size
);
353 #endif /* HAVE_SOCKETS */
355 /* Emulate getloadavg. */
357 getloadavg (double loadavg
[], int nelem
)
361 /* A faithful emulation is going to have to be saved for a rainy day. */
362 for (i
= 0; i
< nelem
; i
++)
369 /* Emulate getpwuid, getpwnam and others. */
371 #define PASSWD_FIELD_SIZE 256
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
];
379 static struct passwd the_passwd
=
391 static struct group the_group
=
393 /* There are no groups on NT, so we just return "root" as the
401 return the_passwd
.pw_uid
;
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. */
416 return the_passwd
.pw_gid
;
428 if (uid
== the_passwd
.pw_uid
)
440 getpwnam (char *name
)
444 pw
= getpwuid (getuid ());
448 if (stricmp (name
, pw
->pw_name
))
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.
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). */
464 char user_sid
[256], name
[256], domain
[256];
465 DWORD length
= sizeof (name
), dlength
= sizeof (domain
), trash
;
467 SID_NAME_USE user_type
;
470 open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
)
471 && get_token_information (
473 (PVOID
) user_sid
, sizeof (user_sid
), &trash
)
474 && lookup_account_sid (
475 NULL
, *((PSID
*) user_sid
), name
, &length
,
476 domain
, &dlength
, &user_type
)
479 strcpy (the_passwd
.pw_name
, name
);
480 /* Determine a reasonable uid value. */
481 if (stricmp ("administrator", name
) == 0)
483 the_passwd
.pw_uid
= 0;
484 the_passwd
.pw_gid
= 0;
488 SID_IDENTIFIER_AUTHORITY
* pSIA
;
490 pSIA
= get_sid_identifier_authority (*((PSID
*) user_sid
));
491 /* I believe the relative portion is the last 4 bytes (of 6)
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;
501 if (get_token_information (token
, TokenPrimaryGroup
,
502 (PVOID
) user_sid
, sizeof (user_sid
), &trash
))
504 SID_IDENTIFIER_AUTHORITY
* pSIA
;
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;
515 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
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
))
522 strcpy (the_passwd
.pw_name
, name
);
523 if (stricmp ("administrator", name
) == 0)
524 the_passwd
.pw_uid
= 0;
526 the_passwd
.pw_uid
= 123;
527 the_passwd
.pw_gid
= the_passwd
.pw_uid
;
531 strcpy (the_passwd
.pw_name
, "unknown");
532 the_passwd
.pw_uid
= 123;
533 the_passwd
.pw_gid
= 123;
536 /* Ensure HOME and SHELL are defined. */
537 if (getenv ("HOME") == NULL
)
539 if (getenv ("SHELL") == NULL
)
542 /* Set dir and shell from environment variables. */
543 strcpy (the_passwd
.pw_dir
, getenv ("HOME"));
544 strcpy (the_passwd
.pw_shell
, getenv ("SHELL"));
553 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
554 return ((rand () << 15) | rand ());
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. */
569 normalize_filename (fp
, path_sep
)
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')
587 if (NILP (Vw32_downcase_file_names
))
591 if (*fp
== '/' || *fp
== '\\')
598 sep
= path_sep
; /* convert to this path separator */
599 elem
= fp
; /* start of current path element */
602 if (*fp
>= 'a' && *fp
<= 'z')
603 elem
= 0; /* don't convert this element */
605 if (*fp
== 0 || *fp
== ':')
607 sep
= *fp
; /* restore current separator (or 0) */
608 *fp
= '/'; /* after conversion of this element */
611 if (*fp
== '/' || *fp
== '\\')
613 if (elem
&& elem
!= fp
)
615 *fp
= 0; /* temporary end of string */
616 _strlwr (elem
); /* while we convert to lower case */
618 *fp
= sep
; /* convert (or restore) path separator */
619 elem
= fp
+ 1; /* next element starts after separator */
625 /* Destructively turn backslashes into slashes. */
627 dostounix_filename (p
)
630 normalize_filename (p
, '/');
633 /* Destructively turn slashes into backslashes. */
635 unixtodos_filename (p
)
638 normalize_filename (p
, '\\');
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.) */
647 register unsigned char *buf
;
649 unsigned char *np
= buf
;
650 unsigned char *startp
= buf
;
651 unsigned char *endp
= buf
+ n
;
655 while (buf
< endp
- 1)
659 if (*(++buf
) != 0x0a)
670 /* Parse the root part of file name, if present. Return length and
671 optionally store pointer to char after root. */
673 parse_root (char * name
, char ** pPath
)
680 /* find the root name of the volume if given */
681 if (isalpha (name
[0]) && name
[1] == ':')
683 /* skip past drive specifier */
685 if (IS_DIRECTORY_SEP (name
[0]))
688 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
694 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
699 if (IS_DIRECTORY_SEP (name
[0]))
709 /* Get long base name for name; name is assumed to be absolute. */
711 get_long_basename (char * name
, char * buf
, int size
)
713 WIN32_FIND_DATA find_data
;
717 /* must be valid filename, no wild cards or other invalid characters */
718 if (strpbrk (name
, "*?|<>\""))
721 dir_handle
= FindFirstFile (name
, &find_data
);
722 if (dir_handle
!= INVALID_HANDLE_VALUE
)
724 if ((len
= strlen (find_data
.cFileName
)) < size
)
725 memcpy (buf
, find_data
.cFileName
, len
+ 1);
728 FindClose (dir_handle
);
733 /* Get long name for file, if possible (assumed to be absolute). */
735 w32_get_long_filename (char * name
, char * buf
, int size
)
740 char full
[ MAX_PATH
];
747 /* Use local copy for destructive modification. */
748 memcpy (full
, name
, len
+1);
749 unixtodos_filename (full
);
751 /* Copy root part verbatim. */
752 len
= parse_root (full
, &p
);
753 memcpy (o
, full
, len
);
758 while (p
!= NULL
&& *p
)
761 p
= strchr (q
, '\\');
763 len
= get_long_basename (full
, o
, size
);
786 is_unc_volume (const char *filename
)
788 const char *ptr
= filename
;
790 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
793 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
799 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
802 sigsetmask (int signal_mask
)
826 setpgrp (int pid
, int gid
)
838 unrequest_sigio (void)
849 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
852 w32_get_resource (key
, lpdwtype
)
857 HKEY hrootkey
= NULL
;
861 /* Check both the current user and the local machine to see if
862 we have any resources. */
864 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
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
)
875 if (lpvalue
) xfree (lpvalue
);
877 RegCloseKey (hrootkey
);
880 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
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
)
891 if (lpvalue
) xfree (lpvalue
);
893 RegCloseKey (hrootkey
);
899 char *get_emacs_configuration (void);
900 extern Lisp_Object Vsystem_configuration
;
903 init_environment (char ** argv
)
905 static const char * const tempdirs
[] = {
906 "$TMPDIR", "$TEMP", "$TMP", "c:/"
911 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
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
++)
919 const char *tmp
= tempdirs
[i
];
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)
929 char * var
= alloca (strlen (tmp
) + 8);
930 sprintf (var
, "TMPDIR=%s", tmp
);
931 _putenv (strdup (var
));
938 Fcons (build_string ("no usable temporary directories found!!"),
940 "While setting TMPDIR: ");
942 /* Check for environment variables and use registry settings if they
943 don't exist. Fallback on default values where applicable. */
948 char locale_name
[32];
950 char default_home
[MAX_PATH
];
952 static struct env_entry
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
967 /* {"INFOPATH", "%emacs_dir%/info"}, */
968 {"EMACSDOC", "%emacs_dir%/etc"},
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)
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. */
983 ShGetFolderPath_fn get_folder_path
;
984 shell32_dll
= GetModuleHandle ("shell32.dll");
985 get_folder_path
= (ShGetFolderPath_fn
)
986 GetProcAddress (shell32_dll
, "SHGetFolderPathA");
988 if (get_folder_path
!= NULL
)
990 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
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
;
998 /* Unload shell32.dll, it is not needed anymore. */
999 FreeLibrary (shell32_dll
);
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
)))
1007 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
1009 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
1011 env_vars
[i
].def_value
= locale_name
;
1017 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
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. */
1024 char modname
[MAX_PATH
];
1026 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1028 if ((p
= strrchr (modname
, '\\')) == NULL
)
1032 if ((p
= strrchr (modname
, '\\')) && stricmp (p
, "\\bin") == 0)
1034 char buf
[SET_ENV_BUF_SIZE
];
1037 for (p
= modname
; *p
; p
++)
1038 if (*p
== '\\') *p
= '/';
1040 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
1041 _putenv (strdup (buf
));
1043 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
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)
1051 p
= strrchr (modname
, '\\');
1055 p
= strrchr (modname
, '\\');
1056 if (p
&& stricmp (p
, "\\src") == 0)
1058 char buf
[SET_ENV_BUF_SIZE
];
1061 for (p
= modname
; *p
; p
++)
1062 if (*p
== '\\') *p
= '/';
1064 _snprintf (buf
, sizeof(buf
)-1, "emacs_dir=%s", modname
);
1065 _putenv (strdup (buf
));
1071 for (i
= 0; i
< (sizeof (env_vars
) / sizeof (env_vars
[0])); i
++)
1073 if (!getenv (env_vars
[i
].name
))
1077 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
)
1079 lpval
= env_vars
[i
].def_value
;
1080 dwType
= REG_EXPAND_SZ
;
1086 if (dwType
== REG_EXPAND_SZ
)
1088 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
1090 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof(buf1
));
1091 _snprintf (buf2
, sizeof(buf2
)-1, "%s=%s", env_vars
[i
].name
, buf1
);
1092 _putenv (strdup (buf2
));
1094 else if (dwType
== REG_SZ
)
1096 char buf
[SET_ENV_BUF_SIZE
];
1098 _snprintf (buf
, sizeof(buf
)-1, "%s=%s", env_vars
[i
].name
, lpval
);
1099 _putenv (strdup (buf
));
1109 /* Rebuild system configuration to reflect invoking system. */
1110 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
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.
1120 The same applies to COMSPEC. */
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);
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
))
1140 static char modname
[MAX_PATH
];
1142 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1144 if ((p
= strrchr (modname
, '\\')) == NULL
)
1148 SetCurrentDirectory (modname
);
1150 /* Ensure argv[0] has the full path to Emacs. */
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
1158 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
1164 emacs_root_dir (void)
1166 static char root_dir
[FILENAME_MAX
];
1169 p
= getenv ("emacs_dir");
1172 strcpy (root_dir
, p
);
1173 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
1174 dostounix_filename (root_dir
);
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
1184 get_emacs_configuration (void)
1186 char *arch
, *oem
, *os
;
1188 static char configuration_buffer
[32];
1190 /* Determine the processor type. */
1191 switch (get_processor_type ())
1194 #ifdef PROCESSOR_INTEL_386
1195 case PROCESSOR_INTEL_386
:
1196 case PROCESSOR_INTEL_486
:
1197 case PROCESSOR_INTEL_PENTIUM
:
1202 #ifdef PROCESSOR_INTEL_860
1203 case PROCESSOR_INTEL_860
:
1208 #ifdef PROCESSOR_MIPS_R2000
1209 case PROCESSOR_MIPS_R2000
:
1210 case PROCESSOR_MIPS_R3000
:
1211 case PROCESSOR_MIPS_R4000
:
1216 #ifdef PROCESSOR_ALPHA_21064
1217 case PROCESSOR_ALPHA_21064
:
1227 /* Use the OEM field to reflect the compiler/library combination. */
1229 #define COMPILER_NAME "msvc"
1232 #define COMPILER_NAME "mingw"
1234 #define COMPILER_NAME "unknown"
1237 oem
= COMPILER_NAME
;
1239 switch (osinfo_cache
.dwPlatformId
) {
1240 case VER_PLATFORM_WIN32_NT
:
1242 build_num
= osinfo_cache
.dwBuildNumber
;
1244 case VER_PLATFORM_WIN32_WINDOWS
:
1245 if (osinfo_cache
.dwMinorVersion
== 0) {
1250 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1252 case VER_PLATFORM_WIN32s
:
1253 /* Not supported, should not happen. */
1255 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
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
);
1267 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
1270 return configuration_buffer
;
1274 get_emacs_configuration_options (void)
1276 static char options_buffer
[256];
1278 /* Work out the effective configure options for this build. */
1280 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1283 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1285 #define COMPILER_VERSION ""
1289 sprintf (options_buffer
, COMPILER_VERSION
);
1291 strcat (options_buffer
, " --no-opt");
1294 strcat (options_buffer
, " --cflags");
1295 strcat (options_buffer
, USER_CFLAGS
);
1298 strcat (options_buffer
, " --ldflags");
1299 strcat (options_buffer
, USER_LDFLAGS
);
1301 return options_buffer
;
1305 #include <sys/timeb.h>
1307 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1309 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
1314 tv
->tv_sec
= tb
.time
;
1315 tv
->tv_usec
= tb
.millitm
* 1000L;
1318 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
1319 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
1323 /* ------------------------------------------------------------------------- */
1324 /* IO support and wrapper functions for W32 API. */
1325 /* ------------------------------------------------------------------------- */
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). */
1331 sys_ctime (const time_t *t
)
1333 char *str
= (char *) ctime (t
);
1334 return (str
? str
: "Sun Jan 01 00:00:00 1970");
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. */
1341 sys_sleep (int seconds
)
1343 Sleep (seconds
* 1000);
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
);
1350 /* parallel array of private info on file handles */
1351 filedesc fd_info
[ MAXDESC
];
1353 typedef struct volume_info_data
{
1354 struct volume_info_data
* next
;
1356 /* time when info was obtained */
1359 /* actual volume info */
1368 /* Global referenced by various functions. */
1369 static volume_info_data volume_info
;
1371 /* Vector to indicate which drives are local and fixed (for which cached
1372 data never expires). */
1373 static BOOL fixed_drives
[26];
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 )
1383 /* Cache support functions. */
1385 /* Simple linked list with linear search is sufficient. */
1386 static volume_info_data
*volume_cache
= NULL
;
1388 static volume_info_data
*
1389 lookup_volume_info (char * root_dir
)
1391 volume_info_data
* info
;
1393 for (info
= volume_cache
; info
; info
= info
->next
)
1394 if (stricmp (info
->root_dir
, root_dir
) == 0)
1400 add_volume_info (char * root_dir
, volume_info_data
* info
)
1402 info
->root_dir
= xstrdup (root_dir
);
1403 info
->next
= volume_cache
;
1404 volume_cache
= info
;
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). */
1412 GetCachedVolumeInformation (char * root_dir
)
1414 volume_info_data
* info
;
1415 char default_root
[ MAX_PATH
];
1417 /* NULL for root_dir means use root from current directory. */
1418 if (root_dir
== NULL
)
1420 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
1422 parse_root (default_root
, &root_dir
);
1424 root_dir
= default_root
;
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.
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. */
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). */
1445 /* Map drive letter to UNC if remote. */
1446 if ( isalpha( root_dir
[0] ) && !fixed
[ DRIVE_INDEX( root_dir
[0] ) ] )
1448 char remote_name
[ 256 ];
1449 char drive
[3] = { root_dir
[0], ':' };
1451 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
1453 /* do something */ ;
1457 info
= lookup_volume_info (root_dir
);
1459 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
1467 /* Info is not cached, or is stale. */
1468 if (!GetVolumeInformation (root_dir
,
1469 name
, sizeof (name
),
1473 type
, sizeof (type
)))
1476 /* Cache the volume information for future use, overwriting existing
1477 entry if present. */
1480 info
= (volume_info_data
*) xmalloc (sizeof (volume_info_data
));
1481 add_volume_info (root_dir
, info
);
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 ();
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). */
1503 get_volume_info (const char * name
, const char ** pPath
)
1505 char temp
[MAX_PATH
];
1506 char *rootname
= NULL
; /* default to current volume */
1507 volume_info_data
* info
;
1512 /* find the root name of the volume if given */
1513 if (isalpha (name
[0]) && name
[1] == ':')
1521 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1528 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1541 info
= GetCachedVolumeInformation (rootname
);
1544 /* Set global referenced by other functions. */
1545 volume_info
= *info
;
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. */
1554 is_fat_volume (const char * name
, const char ** pPath
)
1556 if (get_volume_info (name
, pPath
))
1557 return (volume_info
.maxcomp
== 12);
1561 /* Map filename to a legal 8.3 name if necessary. */
1563 map_w32_filename (const char * name
, const char ** pPath
)
1565 static char shortname
[MAX_PATH
];
1566 char * str
= shortname
;
1569 const char * save_name
= name
;
1571 if (strlen (name
) >= MAX_PATH
)
1573 /* Return a filename which will cause callers to fail. */
1574 strcpy (shortname
, "?");
1578 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
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 */
1585 *str
++ = *name
++; /* skip past UNC header */
1587 while ((c
= *name
++))
1594 extn
= 0; /* reset extension flags */
1595 dots
= 2; /* max 2 dots */
1596 left
= 8; /* max length 8 for main part */
1600 extn
= 0; /* reset extension flags */
1601 dots
= 2; /* max 2 dots */
1602 left
= 8; /* max length 8 for main part */
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. */
1613 IS_DIRECTORY_SEP (*name
))
1628 extn
= 1; /* we've got an extension */
1629 left
= 3; /* 3 chars in extension */
1633 /* any embedded dots after the first are converted to _ */
1638 case '#': /* don't lose these, they're important */
1640 str
[-1] = c
; /* replace last character of part */
1645 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
1647 dots
= 0; /* started a path component */
1656 strcpy (shortname
, name
);
1657 unixtodos_filename (shortname
);
1661 *pPath
= shortname
+ (path
- save_name
);
1667 is_exec (const char * name
)
1669 char * p
= strrchr (name
, '.');
1672 && (stricmp (p
, ".exe") == 0 ||
1673 stricmp (p
, ".com") == 0 ||
1674 stricmp (p
, ".bat") == 0 ||
1675 stricmp (p
, ".cmd") == 0));
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. */
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
;
1688 /* Support shares on a network resource as subdirectories of a read-only
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
);
1696 opendir (char *filename
)
1700 /* Opening is done by FindFirstFile. However, a read is inherent to
1701 this operation, so we defer the open until read time. */
1703 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1705 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1708 if (is_unc_volume (filename
))
1710 wnet_enum_handle
= open_unc_volume (filename
);
1711 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
1715 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
1722 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
1723 dir_pathname
[MAXPATHLEN
] = '\0';
1724 dir_is_fat
= is_fat_volume (filename
, NULL
);
1730 closedir (DIR *dirp
)
1732 /* If we have a find-handle open, close it. */
1733 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
1735 FindClose (dir_find_handle
);
1736 dir_find_handle
= INVALID_HANDLE_VALUE
;
1738 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1740 close_unc_volume (wnet_enum_handle
);
1741 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
1743 xfree ((char *) dirp
);
1749 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
1751 if (!read_unc_volume (wnet_enum_handle
,
1752 dir_find_data
.cFileName
,
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
)
1759 char filename
[MAXNAMLEN
+ 3];
1762 strcpy (filename
, dir_pathname
);
1763 ln
= strlen (filename
) - 1;
1764 if (!IS_DIRECTORY_SEP (filename
[ln
]))
1765 strcat (filename
, "\\");
1766 strcat (filename
, "*");
1768 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
1770 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
1775 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
1779 /* Emacs never uses this value, so don't bother making it match
1780 value returned by stat(). */
1781 dir_static
.d_ino
= 1;
1783 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
1784 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
1786 dir_static
.d_namlen
= strlen (dir_find_data
.cFileName
);
1787 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
1789 _strlwr (dir_static
.d_name
);
1790 else if (!NILP (Vw32_downcase_file_names
))
1793 for (p
= dir_static
.d_name
; *p
; p
++)
1794 if (*p
>= 'a' && *p
<= 'z')
1797 _strlwr (dir_static
.d_name
);
1804 open_unc_volume (const char *path
)
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
;
1819 result
= WNetOpenEnum(RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
1820 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
1822 if (result
== NO_ERROR
)
1825 return INVALID_HANDLE_VALUE
;
1829 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
1833 DWORD bufsize
= 512;
1838 buffer
= alloca (bufsize
);
1839 result
= WNetEnumResource (wnet_enum_handle
, &count
, buffer
, &bufsize
);
1840 if (result
!= NO_ERROR
)
1843 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
1844 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
1846 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
1849 strncpy (readbuf
, ptr
, size
);
1854 close_unc_volume (HANDLE henum
)
1856 if (henum
!= INVALID_HANDLE_VALUE
)
1857 WNetCloseEnum (henum
);
1861 unc_volume_file_attributes (const char *path
)
1866 henum
= open_unc_volume (path
);
1867 if (henum
== INVALID_HANDLE_VALUE
)
1870 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
1872 close_unc_volume (henum
);
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
1884 sys_access (const char * path
, int mode
)
1888 /* MSVC implementation doesn't recognize D_OK. */
1889 path
= map_w32_filename (path
, NULL
);
1890 if (is_unc_volume (path
))
1892 attributes
= unc_volume_file_attributes (path
);
1893 if (attributes
== -1) {
1898 else if ((attributes
= GetFileAttributes (path
)) == -1)
1900 /* Should try mapping GetLastError to errno; for now just indicate
1901 that path doesn't exist. */
1905 if ((mode
& X_OK
) != 0 && !is_exec (path
))
1910 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
1915 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
1924 sys_chdir (const char * path
)
1926 return _chdir (map_w32_filename (path
, NULL
));
1930 sys_chmod (const char * path
, int mode
)
1932 return _chmod (map_w32_filename (path
, NULL
), mode
);
1936 sys_chown (const char *path
, uid_t owner
, gid_t group
)
1938 if (sys_chmod (path
, _S_IREAD
) == -1) /* check if file exists */
1944 sys_creat (const char * path
, int mode
)
1946 return _creat (map_w32_filename (path
, NULL
), mode
);
1950 sys_fopen(const char * path
, const char * mode
)
1954 const char * mode_save
= mode
;
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. */
1962 else if (mode
[0] == 'w' || mode
[0] == 'a')
1963 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1967 /* Only do simplistic option parsing. */
1971 oflag
&= ~(O_RDONLY
| O_WRONLY
);
1974 else if (mode
[0] == 'b')
1979 else if (mode
[0] == 't')
1986 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
1990 return _fdopen (fd
, mode_save
);
1993 /* This only works on NTFS volumes, but is useful to have. */
1995 sys_link (const char * old
, const char * new)
1999 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
2001 if (old
== NULL
|| new == NULL
)
2007 strcpy (oldname
, map_w32_filename (old
, NULL
));
2008 strcpy (newname
, map_w32_filename (new, NULL
));
2010 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
2011 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2012 if (fileh
!= INVALID_HANDLE_VALUE
)
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
2024 WIN32_STREAM_ID wid
;
2025 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
2028 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
2029 data
.wid
.cStreamName
, MAX_PATH
);
2032 LPVOID context
= NULL
;
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;
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
))
2052 /* Should try mapping GetLastError to errno; for now just
2053 indicate a general error (eg. links not supported). */
2054 errno
= EINVAL
; // perhaps EMLINK?
2058 CloseHandle (fileh
);
2067 sys_mkdir (const char * path
)
2069 return _mkdir (map_w32_filename (path
, NULL
));
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
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. */
2082 sys_mktemp (char * template)
2086 unsigned uid
= GetCurrentThreadId ();
2087 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2089 if (template == NULL
)
2091 p
= template + strlen (template);
2093 /* replace up to the last 5 X's with uid in decimal */
2094 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
2096 p
[0] = '0' + uid
% 10;
2100 if (i
< 0 && p
[0] == 'X')
2105 int save_errno
= errno
;
2106 p
[0] = first_char
[i
];
2107 if (sys_access (template, 0) < 0)
2113 while (++i
< sizeof (first_char
));
2116 /* Template is badly formed or else we can't generate a unique name,
2117 so return empty string */
2123 sys_open (const char * path
, int oflag
, int mode
)
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
2129 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
2132 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
2136 sys_rename (const char * oldname
, const char * newname
)
2139 char temp
[MAX_PATH
];
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.
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.
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. */
2154 strcpy (temp
, map_w32_filename (oldname
, NULL
));
2156 if (os_subtype
== OS_WIN95
)
2162 oldname
= map_w32_filename (oldname
, NULL
);
2163 if (o
= strrchr (oldname
, '\\'))
2166 o
= (char *) oldname
;
2168 if (p
= strrchr (temp
, '\\'))
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
);
2179 result
= rename (oldname
, temp
);
2181 /* This loop must surely terminate! */
2182 while (result
< 0 && errno
== EEXIST
);
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).
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.) */
2198 newname
= map_w32_filename (newname
, NULL
);
2199 result
= rename (temp
, newname
);
2203 && _chmod (newname
, 0666) == 0
2204 && _unlink (newname
) == 0)
2205 result
= rename (temp
, newname
);
2211 sys_rmdir (const char * path
)
2213 return _rmdir (map_w32_filename (path
, NULL
));
2217 sys_unlink (const char * path
)
2219 path
= map_w32_filename (path
, NULL
);
2221 /* On Unix, unlink works without write permission. */
2222 _chmod (path
, 0666);
2223 return _unlink (path
);
2226 static FILETIME utc_base_ft
;
2227 static long double utc_base
;
2228 static int init
= 0;
2231 convert_time (FILETIME ft
)
2237 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
2246 st
.wMilliseconds
= 0;
2248 SystemTimeToFileTime (&st
, &utc_base_ft
);
2249 utc_base
= (long double) utc_base_ft
.dwHighDateTime
2250 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
2254 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
2257 ret
= (long double) ft
.dwHighDateTime
* 4096 * 1024 * 1024 + ft
.dwLowDateTime
;
2259 return (time_t) (ret
* 1e-7);
2263 convert_from_time_t (time_t time
, FILETIME
* pft
)
2269 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
2278 st
.wMilliseconds
= 0;
2280 SystemTimeToFileTime (&st
, &utc_base_ft
);
2281 utc_base
= (long double) utc_base_ft
.dwHighDateTime
2282 * 4096 * 1024 * 1024 + utc_base_ft
.dwLowDateTime
;
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
);
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). */
2299 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
2301 hashval (const unsigned char * str
)
2306 h
= (h
<< 4) + *str
++;
2312 /* Return the hash value of the canonical pathname, excluding the
2313 drive/UNC header, to get a hopefully unique inode number. */
2315 generate_inode_val (const char * name
)
2317 char fullname
[ MAX_PATH
];
2321 /* Get the truly canonical filename, if it exists. (Note: this
2322 doesn't resolve aliasing due to subst commands, or recognise hard
2324 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
2327 parse_root (fullname
, &p
);
2328 /* Normal W32 filesystems are still case insensitive. */
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. */
2339 stat (const char * path
, struct stat
* buf
)
2342 WIN32_FIND_DATA wfd
;
2347 int rootdir
= FALSE
;
2349 if (path
== NULL
|| buf
== NULL
)
2355 name
= (char *) map_w32_filename (path
, &path
);
2356 /* must be valid filename, no wild cards or other invalid characters */
2357 if (strpbrk (name
, "*?|<>\""))
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')
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
);
2378 if (is_unc_volume (name
))
2380 DWORD attrs
= unc_volume_file_attributes (name
);
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
);
2394 if (!IS_DIRECTORY_SEP (name
[len
-1]))
2395 strcat (name
, "\\");
2396 if (GetDriveType (name
) < 2)
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
);
2410 if (IS_DIRECTORY_SEP (name
[len
-1]))
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]))
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)
2424 /* This was the last entry returned by readdir. */
2425 wfd
= dir_find_data
;
2429 fh
= FindFirstFile (name
, &wfd
);
2430 if (fh
== INVALID_HANDLE_VALUE
)
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
)
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
;
2450 if (GetFileInformationByHandle (fh
, &info
))
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
;
2466 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2468 buf
->st_mode
= _S_IFDIR
;
2472 switch (GetFileType (fh
))
2474 case FILE_TYPE_DISK
:
2475 buf
->st_mode
= _S_IFREG
;
2477 case FILE_TYPE_PIPE
:
2478 buf
->st_mode
= _S_IFIFO
;
2480 case FILE_TYPE_CHAR
:
2481 case FILE_TYPE_UNKNOWN
:
2483 buf
->st_mode
= _S_IFCHR
;
2490 /* Don't bother to make this information more accurate. */
2491 buf
->st_mode
= (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ?
2492 _S_IFDIR
: _S_IFREG
;
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)
2503 /* For want of something better, try to make everything unique. */
2504 static DWORD gen_num
= 0;
2505 fake_inode
= ++gen_num
;
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);
2513 buf
->st_ino
= fake_inode
;
2515 /* consider files to belong to current user */
2516 buf
->st_uid
= the_passwd
.pw_uid
;
2517 buf
->st_gid
= the_passwd
.pw_gid
;
2519 /* volume_info is set indirectly by map_w32_filename */
2520 buf
->st_dev
= volume_info
.serialnum
;
2521 buf
->st_rdev
= volume_info
.serialnum
;
2524 buf
->st_size
= wfd
.nFileSizeLow
;
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
;
2533 /* determine rwx permissions */
2534 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2535 permission
= _S_IREAD
;
2537 permission
= _S_IREAD
| _S_IWRITE
;
2539 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2540 permission
|= _S_IEXEC
;
2541 else if (is_exec (name
))
2542 permission
|= _S_IEXEC
;
2544 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2549 /* Provide fstat and utime as well as stat for consistent handling of
2552 fstat (int desc
, struct stat
* buf
)
2554 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
2555 BY_HANDLE_FILE_INFORMATION info
;
2559 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
2561 case FILE_TYPE_DISK
:
2562 buf
->st_mode
= _S_IFREG
;
2563 if (!GetFileInformationByHandle (fh
, &info
))
2569 case FILE_TYPE_PIPE
:
2570 buf
->st_mode
= _S_IFIFO
;
2572 case FILE_TYPE_CHAR
:
2573 case FILE_TYPE_UNKNOWN
:
2575 buf
->st_mode
= _S_IFCHR
;
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
;
2584 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2585 buf
->st_mode
= _S_IFDIR
;
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
;
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);
2599 buf
->st_ino
= fake_inode
;
2601 /* consider files to belong to current user */
2605 buf
->st_dev
= info
.dwVolumeSerialNumber
;
2606 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
2608 buf
->st_size
= info
.nFileSizeLow
;
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
;
2617 /* determine rwx permissions */
2618 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
2619 permission
= _S_IREAD
;
2621 permission
= _S_IREAD
| _S_IWRITE
;
2623 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
2624 permission
|= _S_IEXEC
;
2627 #if 0 /* no way of knowing the filename */
2628 char * p
= strrchr (name
, '.');
2630 (stricmp (p
, ".exe") == 0 ||
2631 stricmp (p
, ".com") == 0 ||
2632 stricmp (p
, ".bat") == 0 ||
2633 stricmp (p
, ".cmd") == 0))
2634 permission
|= _S_IEXEC
;
2638 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
2644 utime (const char *name
, struct utimbuf
*times
)
2646 struct utimbuf deftime
;
2653 deftime
.modtime
= deftime
.actime
= time (NULL
);
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
);
2662 convert_from_time_t (times
->actime
, &atime
);
2663 convert_from_time_t (times
->modtime
, &mtime
);
2664 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
2682 /* Wrappers for winsock functions to map between our file descriptors
2683 and winsock's handles; also set h_errno for convenience.
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). */
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);
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
,
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
);
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
2729 static int winsock_inuse
;
2734 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
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
)
2742 if (FreeLibrary (winsock_lib
))
2751 init_winsock (int load_now
)
2753 WSADATA winsockData
;
2755 if (winsock_lib
!= NULL
)
2758 pfn_SetHandleInformation
= NULL
;
2759 pfn_SetHandleInformation
2760 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2761 "SetHandleInformation");
2763 winsock_lib
= LoadLibrary ("wsock32.dll");
2765 if (winsock_lib
!= NULL
)
2767 /* dynamically link to socket functions */
2769 #define LOAD_PROC(fn) \
2770 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
2773 LOAD_PROC( WSAStartup
);
2774 LOAD_PROC( WSASetLastError
);
2775 LOAD_PROC( WSAGetLastError
);
2776 LOAD_PROC( socket
);
2778 LOAD_PROC( connect
);
2779 LOAD_PROC( ioctlsocket
);
2782 LOAD_PROC( closesocket
);
2783 LOAD_PROC( shutdown
);
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
);
2800 /* specify version 1.1 of winsock */
2801 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
2803 if (winsockData
.wVersion
!= 0x101)
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. */
2815 FreeLibrary (winsock_lib
);
2823 FreeLibrary (winsock_lib
);
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 ()
2838 if (winsock_lib
== NULL
)
2841 h_errno
= pfn_WSAGetLastError ();
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;
2857 static void check_errno ()
2859 if (h_errno
== 0 && winsock_lib
!= NULL
)
2860 pfn_WSASetLastError (0);
2863 /* Extend strerror to handle the winsock-specific error codes. */
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",
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 */
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",
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 */
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",
2940 sys_strerror(int error_no
)
2943 static char unknown_msg
[40];
2945 if (error_no
>= 0 && error_no
< sys_nerr
)
2946 return sys_errlist
[error_no
];
2948 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
2949 if (_wsa_errlist
[i
].errnum
== error_no
)
2950 return _wsa_errlist
[i
].msg
;
2952 sprintf(unknown_msg
, "Unidentified error: %d", error_no
);
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. */
2960 //#define SOCK_REPLACE_HANDLE
2962 #ifdef SOCK_REPLACE_HANDLE
2963 #define SOCK_HANDLE(fd) ((SOCKET) _get_osfhandle (fd))
2965 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
2968 int socket_to_fd (SOCKET s
);
2971 sys_socket(int af
, int type
, int protocol
)
2975 if (winsock_lib
== NULL
)
2978 return INVALID_SOCKET
;
2983 /* call the real socket function */
2984 s
= pfn_socket (af
, type
, protocol
);
2986 if (s
!= INVALID_SOCKET
)
2987 return socket_to_fd (s
);
2993 /* Convert a SOCKET to a file descriptor. */
2995 socket_to_fd (SOCKET s
)
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. */
3006 /* allocate a file descriptor (with appropriate flags) */
3007 fd
= _open ("NUL:", _O_RDWR
);
3010 #ifdef SOCK_REPLACE_HANDLE
3011 /* now replace handle to NUL with our socket handle */
3012 CloseHandle ((HANDLE
) _get_osfhandle (fd
));
3014 _set_osfhnd (fd
, s
);
3015 /* setmode (fd, _O_BINARY); */
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. */
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
)
3029 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
3033 HANDLE parent
= GetCurrentProcess ();
3034 HANDLE new_s
= INVALID_HANDLE_VALUE
;
3036 if (DuplicateHandle (parent
,
3042 DUPLICATE_SAME_ACCESS
))
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)
3051 pfn_closesocket (s
);
3056 CloseHandle (new_s
);
3061 fd_info
[fd
].hnd
= (HANDLE
) s
;
3064 /* set our own internal flags */
3065 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
3071 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3073 /* attach child_process to fd_info */
3074 if (fd_info
[ fd
].cp
!= NULL
)
3076 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
3080 fd_info
[ fd
].cp
= cp
;
3083 winsock_inuse
++; /* count open sockets */
3090 pfn_closesocket (s
);
3097 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
3099 if (winsock_lib
== NULL
)
3102 return SOCKET_ERROR
;
3106 if (fd_info
[s
].flags
& FILE_SOCKET
)
3108 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
3109 if (rc
== SOCKET_ERROR
)
3114 return SOCKET_ERROR
;
3119 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
3121 if (winsock_lib
== NULL
)
3124 return SOCKET_ERROR
;
3128 if (fd_info
[s
].flags
& FILE_SOCKET
)
3130 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
3131 if (rc
== SOCKET_ERROR
)
3136 return SOCKET_ERROR
;
3140 sys_htons (u_short hostshort
)
3142 return (winsock_lib
!= NULL
) ?
3143 pfn_htons (hostshort
) : hostshort
;
3147 sys_ntohs (u_short netshort
)
3149 return (winsock_lib
!= NULL
) ?
3150 pfn_ntohs (netshort
) : netshort
;
3154 sys_inet_addr (const char * cp
)
3156 return (winsock_lib
!= NULL
) ?
3157 pfn_inet_addr (cp
) : INADDR_NONE
;
3161 sys_gethostname (char * name
, int namelen
)
3163 if (winsock_lib
!= NULL
)
3164 return pfn_gethostname (name
, namelen
);
3166 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
3167 return !GetComputerName (name
, (DWORD
*)&namelen
);
3170 return SOCKET_ERROR
;
3174 sys_gethostbyname(const char * name
)
3176 struct hostent
* host
;
3178 if (winsock_lib
== NULL
)
3185 host
= pfn_gethostbyname (name
);
3192 sys_getservbyname(const char * name
, const char * proto
)
3194 struct servent
* serv
;
3196 if (winsock_lib
== NULL
)
3203 serv
= pfn_getservbyname (name
, proto
);
3210 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
3212 if (winsock_lib
== NULL
)
3215 return SOCKET_ERROR
;
3219 if (fd_info
[s
].flags
& FILE_SOCKET
)
3221 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
3222 if (rc
== SOCKET_ERROR
)
3227 return SOCKET_ERROR
;
3232 sys_shutdown (int s
, int how
)
3234 if (winsock_lib
== NULL
)
3237 return SOCKET_ERROR
;
3241 if (fd_info
[s
].flags
& FILE_SOCKET
)
3243 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
3244 if (rc
== SOCKET_ERROR
)
3249 return SOCKET_ERROR
;
3253 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
3255 if (winsock_lib
== NULL
)
3258 return SOCKET_ERROR
;
3262 if (fd_info
[s
].flags
& FILE_SOCKET
)
3264 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
3265 (const char *)optval
, optlen
);
3266 if (rc
== SOCKET_ERROR
)
3271 return SOCKET_ERROR
;
3275 sys_listen (int s
, int backlog
)
3277 if (winsock_lib
== NULL
)
3280 return SOCKET_ERROR
;
3284 if (fd_info
[s
].flags
& FILE_SOCKET
)
3286 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
3287 if (rc
== SOCKET_ERROR
)
3292 return SOCKET_ERROR
;
3296 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
3298 if (winsock_lib
== NULL
)
3301 return SOCKET_ERROR
;
3305 if (fd_info
[s
].flags
& FILE_SOCKET
)
3307 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
3308 if (rc
== SOCKET_ERROR
)
3313 return SOCKET_ERROR
;
3317 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
3319 if (winsock_lib
== NULL
)
3326 if (fd_info
[s
].flags
& FILE_SOCKET
)
3328 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
3329 if (t
!= INVALID_SOCKET
)
3330 return socket_to_fd (t
);
3340 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
3341 struct sockaddr
* from
, int * fromlen
)
3343 if (winsock_lib
== NULL
)
3346 return SOCKET_ERROR
;
3350 if (fd_info
[s
].flags
& FILE_SOCKET
)
3352 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
3353 if (rc
== SOCKET_ERROR
)
3358 return SOCKET_ERROR
;
3362 sys_sendto (int s
, const char * buf
, int len
, int flags
,
3363 const struct sockaddr
* to
, int tolen
)
3365 if (winsock_lib
== NULL
)
3368 return SOCKET_ERROR
;
3372 if (fd_info
[s
].flags
& FILE_SOCKET
)
3374 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
3375 if (rc
== SOCKET_ERROR
)
3380 return SOCKET_ERROR
;
3383 /* Windows does not have an fcntl function. Provide an implementation
3384 solely for making sockets non-blocking. */
3386 fcntl (int s
, int cmd
, int options
)
3388 if (winsock_lib
== NULL
)
3395 if (fd_info
[s
].flags
& FILE_SOCKET
)
3397 if (cmd
== F_SETFL
&& options
== O_NDELAY
)
3399 unsigned long nblock
= 1;
3400 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
3401 if (rc
== SOCKET_ERROR
)
3403 /* Keep track of the fact that we set this to non-blocking. */
3404 fd_info
[s
].flags
|= FILE_NDELAY
;
3410 return SOCKET_ERROR
;
3414 return SOCKET_ERROR
;
3417 #endif /* HAVE_SOCKETS */
3420 /* Shadow main io functions: we need to handle pipes and sockets more
3421 intelligently, and implement non-blocking mode as well. */
3428 if (fd
< 0 || fd
>= MAXDESC
)
3436 child_process
* cp
= fd_info
[fd
].cp
;
3438 fd_info
[fd
].cp
= NULL
;
3440 if (CHILD_ACTIVE (cp
))
3442 /* if last descriptor to active child_process then cleanup */
3444 for (i
= 0; i
< MAXDESC
; i
++)
3448 if (fd_info
[i
].cp
== cp
)
3454 if (fd_info
[fd
].flags
& FILE_SOCKET
)
3456 #ifndef SOCK_REPLACE_HANDLE
3457 if (winsock_lib
== NULL
) abort ();
3459 pfn_shutdown (SOCK_HANDLE (fd
), 2);
3460 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
3462 winsock_inuse
--; /* count open sockets */
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. */
3477 fd_info
[fd
].flags
= 0;
3490 /* duplicate our internal info as well */
3491 fd_info
[new_fd
] = fd_info
[fd
];
3498 sys_dup2 (int src
, int dst
)
3502 if (dst
< 0 || dst
>= MAXDESC
)
3508 /* make sure we close the destination first if it's a pipe or socket */
3509 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
3512 rc
= _dup2 (src
, dst
);
3515 /* duplicate our internal info as well */
3516 fd_info
[dst
] = fd_info
[src
];
3521 /* Unix pipe() has only one arg */
3523 sys_pipe (int * phandles
)
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
3532 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
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
)
3540 _close (phandles
[0]);
3541 _close (phandles
[1]);
3546 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
3547 fd_info
[phandles
[0]].flags
= flags
;
3549 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
3550 fd_info
[phandles
[1]].flags
= flags
;
3558 extern int w32_pipe_read_delay
;
3560 /* Function to do blocking read of one byte, needed to implement
3561 select. It is only allowed on sockets and pipes. */
3563 _sys_read_ahead (int fd
)
3568 if (fd
< 0 || fd
>= MAXDESC
)
3569 return STATUS_READ_ERROR
;
3571 cp
= fd_info
[fd
].cp
;
3573 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
3574 return STATUS_READ_ERROR
;
3576 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
)) == 0
3577 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
3579 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe or socket!\n", fd
));
3583 cp
->status
= STATUS_READ_IN_PROGRESS
;
3585 if (fd_info
[fd
].flags
& FILE_PIPE
)
3587 rc
= _read (fd
, &cp
->chr
, sizeof (char));
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. */
3598 int wait
= w32_pipe_read_delay
;
3604 /* Yield remainder of our time slice, effectively giving a
3605 temporary priority boost to the child process. */
3610 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
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
);
3617 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
3619 if (fd_info
[fd
].flags
& FILE_NDELAY
)
3622 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
3627 if (rc
== sizeof (char))
3628 cp
->status
= STATUS_READ_SUCCEEDED
;
3630 cp
->status
= STATUS_READ_FAILED
;
3636 sys_read (int fd
, char * buffer
, unsigned int count
)
3641 char * orig_buffer
= buffer
;
3643 if (fd
< 0 || fd
>= MAXDESC
)
3649 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3651 child_process
*cp
= fd_info
[fd
].cp
;
3653 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
3661 /* re-read CR carried over from last read */
3662 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
3664 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
3668 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
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. */
3678 int current_status
= cp
->status
;
3680 switch (current_status
)
3682 case STATUS_READ_FAILED
:
3683 case STATUS_READ_ERROR
:
3684 /* report normal EOF if nothing in buffer */
3686 fd_info
[fd
].flags
|= FILE_AT_EOF
;
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
;
3695 case STATUS_READ_SUCCEEDED
:
3696 /* consume read-ahead char */
3697 *buffer
++ = cp
->chr
;
3700 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
3701 ResetEvent (cp
->char_avail
);
3703 case STATUS_READ_ACKNOWLEDGED
:
3707 DebPrint (("sys_read: bad status %d\n", current_status
));
3712 if (fd_info
[fd
].flags
& FILE_PIPE
)
3714 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
3715 to_read
= min (waiting
, (DWORD
) count
);
3718 nchars
+= _read (fd
, buffer
, to_read
);
3721 else /* FILE_SOCKET */
3723 if (winsock_lib
== NULL
) abort ();
3725 /* do the equivalent of a non-blocking read */
3726 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
3727 if (waiting
== 0 && nchars
== 0)
3729 h_errno
= errno
= EWOULDBLOCK
;
3735 /* always use binary mode for sockets */
3736 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
3737 if (res
== SOCKET_ERROR
)
3739 DebPrint(("sys_read.recv failed with error %d on socket %ld\n",
3740 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3751 int nread
= _read (fd
, buffer
, count
);
3754 else 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)
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)
3770 fd_info
[fd
].flags
|= FILE_LAST_CR
;
3776 nchars
= _read (fd
, buffer
, count
);
3781 /* For now, don't bother with a non-blocking mode */
3783 sys_write (int fd
, const void * buffer
, unsigned int count
)
3787 if (fd
< 0 || fd
>= MAXDESC
)
3793 if (fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
))
3795 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
3801 /* Perform text mode translation if required. */
3802 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
3804 char * tmpbuf
= alloca (count
* 2);
3805 unsigned char * src
= (void *)buffer
;
3806 unsigned char * dst
= tmpbuf
;
3811 unsigned char *next
;
3812 /* copy next line or remaining bytes */
3813 next
= _memccpy (dst
, src
, '\n', nbytes
);
3816 /* copied one line ending with '\n' */
3817 int copied
= next
- dst
;
3820 /* insert '\r' before '\n' */
3827 /* copied remaining partial line -> now finished */
3835 if (fd_info
[fd
].flags
& FILE_SOCKET
)
3837 unsigned long nblock
= 0;
3838 if (winsock_lib
== NULL
) abort ();
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
);
3845 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
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
)
3852 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
3855 if (nchars
== SOCKET_ERROR
)
3857 DebPrint(("sys_write.send failed with error %d on socket %ld\n",
3858 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
3864 nchars
= _write (fd
, buffer
, count
);
3870 check_windows_init_file ()
3872 extern int noninteractive
, inhibit_window_system
;
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. */
3878 if (!noninteractive
&& !inhibit_window_system
)
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
;
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
);
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);
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"
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
);
3910 "Emacs Abort Dialog",
3911 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
3912 /* Use the low-level Emacs abort. */
3927 /* shutdown the socket interface if necessary */
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).
3943 Conveniently, init_environment is called before us, so
3944 PRELOAD_WINSOCK can be set in the registry. */
3946 /* Always initialize this correctly. */
3949 if (getenv ("PRELOAD_WINSOCK") != NULL
)
3950 init_winsock (TRUE
);
3953 /* Initial preparation for subprocess support: replace our standard
3954 handles with non-inheritable versions. */
3957 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
3958 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
3959 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
3961 parent
= GetCurrentProcess ();
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
),
3971 DUPLICATE_SAME_ACCESS
);
3973 DuplicateHandle (parent
,
3974 GetStdHandle (STD_OUTPUT_HANDLE
),
3979 DUPLICATE_SAME_ACCESS
);
3981 DuplicateHandle (parent
,
3982 GetStdHandle (STD_ERROR_HANDLE
),
3987 DUPLICATE_SAME_ACCESS
);
3993 if (stdin_save
!= INVALID_HANDLE_VALUE
)
3994 _open_osfhandle ((long) stdin_save
, O_TEXT
);
3996 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
3999 if (stdout_save
!= INVALID_HANDLE_VALUE
)
4000 _open_osfhandle ((long) stdout_save
, O_TEXT
);
4002 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
4005 if (stderr_save
!= INVALID_HANDLE_VALUE
)
4006 _open_osfhandle ((long) stderr_save
, O_TEXT
);
4008 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
4012 /* unfortunately, atexit depends on implementation of malloc */
4013 /* atexit (term_ntproc); */
4014 signal (SIGABRT
, term_ntproc
);
4016 /* determine which drives are fixed, for GetCachedVolumeInformation */
4018 /* GetDriveType must have trailing backslash. */
4019 char drive
[] = "A:\\";
4021 /* Loop over all possible drive letters */
4022 while (*drive
<= 'Z')
4024 /* Record if this drive letter refers to a fixed drive. */
4025 fixed_drives
[DRIVE_INDEX (*drive
)] =
4026 (GetDriveType (drive
) == DRIVE_FIXED
);
4031 /* Reset the volume info cache. */
4032 volume_cache
= NULL
;
4035 /* Check to see if Emacs has been installed correctly. */
4036 check_windows_init_file ();
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).
4044 void globals_of_w32 ()
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;
4055 /* arch-tag: 90442dd3-37be-482b-b272-ac752e3049f1
4056 (do not change this comment) */