home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / e20313sr.zip / emacs / 20.3.1 / src / w32.c < prev    next >
C/C++ Source or Header  |  1999-07-31  |  81KB  |  3,178 lines

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