home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / posix / sys / stat / ~stat.c next >
Encoding:
C/C++ Source or Header  |  1996-10-19  |  31.7 KB  |  874 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  3. /* This is file STAT.C */
  4. /*
  5.  *   Almost a 100% U**X-compatible stat() substitute.
  6.  *
  7.  * Usage:
  8.  *
  9.  *   That's easy: put this into libc.a, then just call stat() as usual.
  10.  *
  11.  * Rationale:
  12.  *
  13.  *   Many Unix-born programs make heavy use of stat() library
  14.  *   function to make decisions on files' equality, size, access
  15.  *   attributes etc.  In the MS-DOS environment, many implementations
  16.  *   of stat() are crippled, because DOS makes it very hard to get to
  17.  *   certain pieces of information about files and directories.  Thus
  18.  *   porting a program to DOS is usually an exercise in #ifdef'ing.
  19.  *   This implementation facilitates porting Unix programs to MS-DOS
  20.  *   by providing stat() which is much more Unix-compatible than those
  21.  *   of most DOS-based C compilers (e.g., Borland's).
  22.  *   Specifically, the following issues are taken care of:
  23.  *
  24.  *      1. This stat() doesn't fail for root directories, returning
  25.  *         valid information.
  26.  *      2. Directory size is not reported zero; the number of used
  27.  *         directory entries multiplied by entry size is returned instead.
  28.  *      3. Mode bits are set for all 3 groups (user, group, other).
  29.  *      4. Directories are NOT reported read-only, unless one of R, H or S
  30.  *         attributes is set.
  31.  *      5. Directories have their execute bit set, as they do under Unix.
  32.  *      6. Device names (such as /dev/con, lpt1, aux etc.) are treated as
  33.  *         if they were on a special drive called `@:' (st_dev = -1).
  34.  *         The "character special" mode bit is set for these devices.
  35.  *      7. The inode number (st_ino) is taken from the starting cluster
  36.  *         number of the file.  If the cluster number is unavailable, it
  37.  *         is invented using the file's name in a manner that minimizes
  38.  *         the possibility of inventing an inode which already belongs
  39.  *         to another file.  See below for details.
  40.  *      8. Executable files are found based on files' extensions and
  41.  *         magic numbers present at their beginning, and their execute
  42.  *         bits are set.
  43.  *
  44.  *   Lossage:
  45.  *
  46.  *      Beautiful as the above sounds, this implementation does fail
  47.  *      under certain circumstances.  The following is a list of known
  48.  *      problems:
  49.  *
  50.  *      1. The time fields for a root directory cannot be obtained, so
  51.  *         they are set to the beginning of the Epoch.
  52.  *      2. For files which reside on networked drives, the inode number
  53.  *         is invented, because network redirectors usually do not
  54.  *         bring that info with them.  This is not a total lossage, but
  55.  *         it could get us a different inode for each program run.
  56.  *      3. Empty files do not have a starting cluster number, because
  57.  *         DOS doesn't allocate one until you actually write something
  58.  *         to a file.  For these the inode is also invented.
  59.  *      4. If the st_ino field is a 16 bit number, the invented inode
  60.  *         numbers are from 65535 and down, assuming that most disks have
  61.  *         unused portions near their end.  Valid cluster numbers are 16-bit
  62.  *         unsigned integers, so a possibility of a clash exists, although
  63.  *         the last 80 or more cluster numbers are unused on all drives
  64.  *         I've seen.  If the st_ino is 32 bit, then invented inodes are
  65.  *         all greater than 64k, which totally eliminates a possibility
  66.  *         of a clash with an actual cluster number.
  67.  *      5. The method of computing directory size is an approximation:
  68.  *         a directory might consume much more space, if it has many
  69.  *         deleted entries.  Still, this is a close approximation, and
  70.  *         it does follow the logic of reporting size for a regular file:
  71.  *         only the actually used space is returned.
  72.  *      6. As this implementation relies heavily on undocumented DOS
  73.  *         features, it will fail to get actual file info in environments
  74.  *         other than native DOS, such as DR-DOS, OS/2 etc.  For these,
  75.  *         the function will return whatever info is available with
  76.  *         conventional DOS calls, which is no less than any other
  77.  *         implementation could do.  This stat() might also fail for
  78.  *         future DOS versions, if the layout of internal DOS data
  79.  *         area is changed; however, this seems unlikely.
  80.  *
  81.  * Copyright (c) 1994-96 Eli Zaretskii <eliz@is.elta.co.il>
  82.  *
  83.  * This software may be used freely so long as this copyright notice is
  84.  * left intact.  There is no warranty on this software.
  85.  *
  86.  */
  87.  
  88. /*
  89.  * Tested with DJGPP port of GNU C compiler, versions 1.11maint5 and 1.12,
  90.  * under MS-DOS 3.3, 4.01, 5.0, 6.20 (with and without DoubleSpace) and
  91.  * with networked drives under XFS 1.86, Novell Netware 3.22, and
  92.  * TSoft NFS 0.24Beta.
  93.  *
  94.  */
  95.  
  96. #include <libc/stubs.h>
  97. #include <stdlib.h>
  98. #include <stddef.h>
  99. #include <unistd.h>
  100. #include <time.h>
  101. #include <stdio.h>
  102. #include <string.h>
  103. #include <ctype.h>
  104. #include <errno.h>
  105. #include <fcntl.h>
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <dos.h>
  109. #include <dir.h>
  110.  
  111. #include <dpmi.h>
  112. #include <go32.h>
  113. #include <libc/farptrgs.h>
  114. #include <libc/bss.h>
  115.  
  116. #include "xstat.h"
  117.  
  118. int __getdisk(void);
  119. int __findfirst(const char *, struct ffblk *, int);
  120. int __findnext(struct ffblk *);
  121.  
  122. #define ALL_FILES   (FA_RDONLY|FA_HIDDEN|FA_SYSTEM|FA_DIREC|FA_ARCH)
  123.  
  124. #define _STAT_INODE         1   /* should we bother getting inode numbers? */
  125. #define _STAT_EXEC_EXT      2   /* get execute bits from file extension? */
  126. #define _STAT_EXEC_MAGIC    4   /* get execute bits from magic signature? */
  127. #define _STAT_DIRSIZE       8   /* compute directory size? */
  128. #define _STAT_ROOT_TIME  0x10   /* try to get root dir time stamp? */
  129. #define _STAT_WRITEBIT   0x20   /* fstat() needs write bit? */
  130.  
  131. /* Should we bother about executables at all? */
  132. #define _STAT_EXECBIT       (_STAT_EXEC_EXT | _STAT_EXEC_MAGIC)
  133.  
  134. /* The structure of the full directory entry.  This is the 32-byte
  135.    record present for each file/subdirectory in a DOS directory.
  136.    Although the ``packed'' attribute seems to be unnecessary, I use
  137.    it to be sure it will still work for future versions of GCC.  */
  138.  
  139. struct full_dirent {
  140.   char           fname[8]      __attribute__ ((packed));
  141.   char           fext[3]       __attribute__ ((packed));
  142.   unsigned char  fattr         __attribute__ ((packed));
  143.   unsigned char  freserved[10] __attribute__ ((packed));
  144.   unsigned short ftime         __attribute__ ((packed));
  145.   unsigned short fdate         __attribute__ ((packed));
  146.   unsigned short fcluster      __attribute__ ((packed));
  147.   unsigned int   fsize         __attribute__ ((packed));
  148. };
  149.  
  150.  
  151. /* Static variables to speed up SDA DOS Swappable Data Area access on
  152.    subsequent calls.  */
  153.  
  154. /* The count of number of SDA's we have.  It is more than 1 for DOS
  155.    4.x only.  If it has a value of 0, the function init_dirent_table()
  156.    will be called to compute the addresses where we are to look for
  157.    directory entry of our file.  A value of -1 means this method is
  158.    unsupported for this version of DOS.  */
  159. static int  dirent_count;
  160.  
  161. /* The table of places to look for our directory entry.
  162.    Each entry in the table is a linear offset from the beginning of
  163.    conventional memory which points to a particular location within
  164.    one of the SDA's, where the entry of a file being stat()'ed could
  165.    appear.  The offsets are computed once (when the routine is first
  166.    called) and then reused for other calls.  The actual storage for
  167.    the table is malloc()'ed when this function is first called.  */
  168. static unsigned int * dirent_table;
  169.  
  170. /* When we have only one SDA, this is where its only place to look for
  171.    directory entry is stored.  */
  172. static unsigned int   dirent_place;
  173.  
  174. /* This holds the fail bits from the last call to init_dirent_table(),
  175.    so we can return them every time get_inode_from_sda() is called.  */
  176. static unsigned short init_dirent_table_bits;
  177.  
  178. /* Holds the last seen value of __bss_count, to be safe for
  179.    restarted programs (emacs).  */
  180. static int stat_count = -1;
  181.  
  182. /*
  183.  * Parts of the following code is derived from file DOSSWAP.C,
  184.  * which came with ``Undocumented DOS'', 1st edition.
  185.  */
  186.  
  187. /* Compute table of pointers to look for directory entry of a file.  */
  188. static int
  189. init_dirent_table (void)
  190. {
  191.   short          get_sda_func;
  192.   unsigned short dirent_offset;
  193.   unsigned short true_dos_version;
  194.   unsigned short dos_major, dos_minor;
  195.   __dpmi_regs    regs;
  196.  
  197.   if (dirent_count == -1)     /* we already tried and found we can't */
  198.     return 0;
  199.  
  200.   /* Compute INT 21h function number and offset of directory entry
  201.      from start of SDA.  These depend on the DOS version.
  202.      We need exact knowledge about DOS internals, so we need the
  203.      TRUE DOS version (not the simulated one by SETVER), if that's
  204.      available.  */
  205.   true_dos_version = _get_dos_version(1);
  206.   dos_major = true_dos_version >> 8;
  207.   dos_minor = true_dos_version & 0xff;
  208.  
  209.   if ((dos_major == 3) && (dos_minor >= 10))
  210.     {
  211.       get_sda_func  = 0x5d06;
  212.       dirent_offset = 0x1a7;
  213.     }
  214.   else if (dos_major == 4)
  215.     {
  216.       /* According to ``Undocumented DOS, 2nd edition'', I could have
  217.          used 5d06 here, as for DOS 5 and above, but I like to be
  218.          defensive.  In fact, the above book itself uses 5d0b, contrary
  219.          to its own recommendation.  */
  220.       get_sda_func  = 0x5d0b;
  221.       dirent_offset = 0x1b3;
  222.     }
  223.   else if (dos_major >= 5)
  224.     {
  225.       get_sda_func  = 0x5d06;
  226.       dirent_offset = 0x1b3;
  227.     }
  228.   else
  229.     {
  230.       _djstat_fail_bits |= _STFAIL_OSVER;
  231.       dirent_count = -1;
  232.       return 0;
  233.     }
  234.  
  235.   _djstat_fail_bits &= ~_STFAIL_OSVER;  /* version is OK */
  236.  
  237.   /* Get the pointer to SDA by calling undocumented function 5dh of INT 21. */
  238.   regs.x.ax = get_sda_func;
  239.   __dpmi_int(0x21, ®s);
  240.   if (regs.x.flags & 1)
  241.     {
  242.       _djstat_fail_bits |= _STFAIL_SDA;
  243.       dirent_count = -1;      /* if the call failed, never try this later */
  244.       return 0;
  245.     }
  246.  
  247.   _djstat_fail_bits &= ~_STFAIL_SDA;    /* Get SDA succeeded */
  248.  
  249.   /* DOS 4.x might have several SDA's, which means we might have more
  250.      than one place to look into.  (It is typical of DOS 4 to complicate
  251.      things.)
  252.      Compute all the possible addresses where we will have to look.  */
  253.   if (dos_major == 4)
  254.     {
  255.       /* The pointer returned by INT 21h, AX=5D0b points to a header
  256.          which holds a number of SDA's and then an array of that number
  257.          of records each one of which includes address of an SDA (DWORD)
  258.          and its length and type (encoded in a WORD).
  259.          While walking this list of SDA's, we add to each pointer the
  260.          offset of directory entry and stash the resulting address in
  261.          our table for later use.  */
  262.  
  263.       int  sda_list_walker = MK_FOFF(regs.x.ds, regs.x.si);
  264.       int  i;
  265.       int *tbl;
  266.  
  267.       dirent_count = _farpeekw(_dos_ds, sda_list_walker); /* number of SDA's */
  268.  
  269.       /* Allocate storage for table.  */
  270.       tbl = dirent_table = (int *)malloc(dirent_count*sizeof(int));
  271.       if (!dirent_table)
  272.         {
  273.           /* If malloc() failed, maybe later it will succeed, so don't
  274.              store -1 in dirent_count.  */
  275.           dirent_count = 0;
  276.           _djstat_fail_bits |= _STFAIL_DCOUNT;
  277.           return 0;
  278.         }
  279.  
  280.       memset(dirent_table, 0, dirent_count*sizeof(int));
  281.       _djstat_fail_bits &= ~_STFAIL_DCOUNT; /* dirent_count seems OK */
  282.  
  283.       /* Walk the array of pointers, computing addresses of directory
  284.          entries and stashing them in our table.  */
  285.       _farsetsel(_dos_ds);
  286.       for (i = dirent_count, sda_list_walker += 2; i--; sda_list_walker += 6)
  287.         {
  288.           int            sda_start = _farnspeekl(sda_list_walker);
  289.           unsigned short sda_len   = _farnspeekw(sda_list_walker + 4) & 0x7fff;
  290.  
  291.           /* Let's be defensive here: if this SDA is too short to have
  292.              place for directory entry, we won't use it.  */
  293.           if (sda_len > dirent_offset)
  294.             *tbl++ = sda_start + dirent_offset;
  295.           else
  296.             dirent_count--;
  297.         }
  298.     }
  299.  
  300.   /* DOS 3.1 and 5.0 or later.  We have only one SDA pointed to by
  301.      whatever INT 21h, AH=5d returns.  */
  302.   else
  303.     {
  304.       dirent_count = 1;
  305.       dirent_place = MK_FOFF(regs.x.ds, regs.x.si) + dirent_offset;
  306.       dirent_table = &dirent_place;
  307.     }
  308.  
  309.   return 1;
  310. }
  311.  
  312. /* Get inode number by searching DOS Swappable Data Area.
  313.    The entire directory entry for a file found by FindFirst/FindNext
  314.    appears at a certain (version-dependent) offset in the SDA after
  315.    one of those function is called.
  316.    Should be called immediately after calling DOS FindFirst function,
  317.    before the info is overwritten by somebody who calls it again.  */
  318. static unsigned int
  319. get_inode_from_sda(const char *basename)
  320. {
  321.   int            count          = dirent_count;
  322.   unsigned int * dirent_p       = dirent_table;
  323.   unsigned short dos_mem_base   = _dos_ds;
  324.   unsigned short our_mem_base   = _my_ds();
  325.   char  * dot                   = strchr(basename, '.');
  326.   size_t  total_len             = strlen(basename);
  327.   int     name_len              = dot ? dot - basename : total_len;
  328.   int     ext_len               = dot ? total_len - name_len - 1 : 0;
  329.   int     cluster_offset        = offsetof(struct full_dirent, fcluster);
  330.  
  331.   /* Restore failure bits set by last call to init_dirent_table(), so
  332.      they will be reported as if it were called now.  */
  333.   _djstat_fail_bits |= init_dirent_table_bits;
  334.  
  335.   /* Force reinitialization in restarted programs (emacs).  */
  336.   if (stat_count != __bss_count)
  337.     {
  338.       stat_count = __bss_count;
  339.       dirent_count = 0;
  340.     }
  341.  
  342.   /* Initialize the table of SDA entries where we are to look for
  343.      our file.  */
  344.   if (!dirent_count && !init_dirent_table())
  345.     {
  346.       /* Don't save the truename failure bit.  */
  347.       init_dirent_table_bits = (_djstat_fail_bits & ~_STFAIL_TRUENAME);
  348.       return 0;
  349.     }
  350.   init_dirent_table_bits = (_djstat_fail_bits & ~_STFAIL_TRUENAME);
  351.   if (dirent_count == -1)
  352.     return 0;
  353.  
  354.   count = dirent_count;
  355.   dirent_p = dirent_table;
  356.  
  357.   _farsetsel(dos_mem_base);
  358.  
  359.   /* This is DOS 4.x lossage: this loop might execute many times.
  360.      For other DOS versions it is executed exactly once.  */
  361.   while (count--)
  362.     {
  363.       unsigned int  src_address = *dirent_p & 0x000fffff;
  364.       char          cmp_buf[sizeof(struct full_dirent)];
  365.  
  366.       /* Copy the directory entry from the SDA to local storage.
  367.          The filename is stored there in infamous DOS format: name and
  368.          extension blank-padded to 8/3 characters, no dot between them.  */
  369.       movedata(dos_mem_base, src_address, our_mem_base, (unsigned int)cmp_buf,
  370.                sizeof(struct full_dirent));
  371.  
  372.       /* If this is the filename we are looking for, return
  373.          its starting cluster. */
  374.       if (!strncmp(cmp_buf, basename, name_len) &&
  375.           (ext_len == 0 || !strncmp(cmp_buf + 8, dot + 1, ext_len)))
  376.         return (unsigned int)_farnspeekw(*dirent_p + cluster_offset);
  377.  
  378.       /* This is not our file.  Search more, if more addresses left. */
  379.       dirent_p++;
  380.     }
  381.  
  382.   /* If not found, give up.  */
  383.   _djstat_fail_bits |= _STFAIL_BADSDA;
  384.   return 0;
  385. }
  386.  
  387. static char blanks_8[] = "        ";
  388.  
  389. static int
  390. stat_assist(const char *path, struct stat *statbuf)
  391. {
  392.   struct   ffblk ff_blk;
  393.   char     canon_path[MAX_TRUE_NAME];
  394.   short    drv_no;
  395.   unsigned dos_ftime;
  396.  
  397.   _djstat_fail_bits = 0;
  398.  
  399.   memset(statbuf, 0, sizeof(struct stat));
  400.   memset(&dos_ftime, 0, sizeof(dos_ftime));
  401.  
  402.   /* Fields which are constant under DOS.  */
  403.   statbuf->st_uid     = getuid();
  404.   statbuf->st_gid     = getgid();
  405.   statbuf->st_nlink   = 1;
  406. #ifndef  NO_ST_BLKSIZE
  407.   statbuf->st_blksize = _go32_info_block.size_of_transfer_buffer;
  408. #endif
  409.  
  410.   /* Get the drive number.  It is always explicit, since we
  411.      called `_fixpath' on the original pathname.  */
  412.   drv_no = toupper(*path) - 'A';
  413.  
  414.   /* Produce canonical pathname, with all the defaults resolved and
  415.      all redundant parts removed.  This calls undocumented DOS
  416.      function 60h.  */
  417.   if (_truename(path, canon_path))
  418.     {
  419.       /* Detect character device names which must be treated specially.
  420.          We could simply call FindFirst and test the 6th bit, but some
  421.          versions of DOS have trouble with this (see Ralph Brown's
  422.          Interrupt List, ``214E'', under `Bugs').  Instead we use
  423.          truename() which calls INT 21/AX=6000H.  For character devices
  424.          it returns X:/DEVNAME, where ``X'' is the current drive letter
  425.          (note the FORWARD slash!).  E.g., for CON or \dev\con it will
  426.          return C:/CON.
  427.          We will pretend that devices all reside on a special drive
  428.          called `@', which corresponds to st_dev = -1.  This is because
  429.          these devices have no files, and we must invent inode numbers
  430.          for them; this scheme allows to lower a risk of clash between
  431.          invented inode and one which belongs to a real file.  This is
  432.          also compatible with what our fstat() does.
  433.       */
  434.       if (canon_path[2] == '/')
  435.         {
  436.           char dev_name[9];     /* devices are at most 8 characters long */
  437.  
  438.           strncpy(dev_name, canon_path + 3, 8); /* the name without `X:/' */
  439.           dev_name[8] = '\0';
  440.           strcpy(canon_path, "@:\\dev\\");
  441.           strcat(canon_path, dev_name);
  442.           strncat(canon_path, blanks_8, 8 - strlen(dev_name)); /* blank-pad */
  443.           canon_path[15] = '\0';   /* ensure zero-termination */
  444.  
  445.           /* Invent inode */
  446.           statbuf->st_ino = _invent_inode(canon_path, 0, 0);
  447.  
  448.           /* Device code. */
  449.           statbuf->st_dev = -1;
  450. #ifdef  HAVE_ST_RDEV
  451.           statbuf->st_rdev = -1;
  452. #endif
  453.  
  454.           /* Set mode bits, including character special bit.
  455.              Should we treat printer devices as write-only?  */
  456.           statbuf->st_mode |= (S_IFCHR | READ_ACCESS | WRITE_ACCESS);
  457.  
  458.           /* We will arrange things so that devices have current time in
  459.              the access-time and modified-time fields of struct stat, and
  460.              zero (the beginning of times) in creation-time field.  This
  461.              is consistent with what DOS FindFirst function returns for
  462.              character device names (if it succeeds--see above).  */
  463.           statbuf->st_atime = statbuf->st_mtime = time(0);
  464.           statbuf->st_ctime = _file_time_stamp(dos_ftime);
  465.  
  466.           return 0;
  467.         }
  468.       else if (canon_path[0] >= 'A' && canon_path[0] <= 'z' &&
  469.                canon_path[1] == ':' && canon_path[2] == '\\')
  470.         {
  471.           /* _truename() returned a name with a drive letter.  (This is
  472.              always so for local drives, but some network redirectors
  473.              also do this.)  We will take this to be the TRUE drive
  474.              letter, because _truename() knows about SUBST and JOIN.
  475.              If the canonicalized path returns in the UNC form (which
  476.              means the drive is remote), it cannot be SUBSTed or JOINed,
  477.              because SUBST.EXE and JOIN.EXE won't let you do it; so, for
  478.              these cases, there is no problem in believing the drive
  479.              number we've got from the original path (or is there?).  */
  480.           drv_no = toupper(canon_path[0]) - 'A';
  481.         }
  482.     }
  483.   else
  484.     {
  485.       /* _truename() failed.  (This really shouldn't happen, but who knows?)
  486.          At least uppercase all letters, convert forward slashes to backward
  487.          ones, and pray... */
  488.       register const char *src = path;
  489.       register       char *dst = canon_path;
  490.  
  491.       while ( (*dst = (*src > 'a' && *src < 'z'
  492.                        ? *src++ - ('a' - 'A')
  493.                        : *src++)) != '\0')
  494.         {
  495.           if (*dst == '/')
  496.             *dst = '\\';
  497.           dst++;
  498.         }
  499.  
  500.       _djstat_fail_bits |= _STFAIL_TRUENAME;
  501.     }
  502.  
  503.   /* Call DOS FindFirst function, which will bring us most of the info.  */
  504.   if (!__findfirst(path, &ff_blk, ALL_FILES))
  505.     {
  506.       /* Time fields. */
  507.       dos_ftime =
  508.         ( (unsigned short)ff_blk.ff_fdate << 16 ) +
  509.           (unsigned short)ff_blk.ff_ftime;
  510.  
  511.       if ( (_djstat_flags & _STAT_INODE) == 0 )
  512.         {
  513.  
  514.           /* For networked drives, don't believe the starting cluster
  515.              that the network redirector feeds us; always invent inode.
  516.              This is because network redirectors leave bogus values there,
  517.              and we don't have enough info to decide if the starting
  518.              cluster value is real or just a left-over from previous call.
  519.              For local files, try first using DOS SDA to get the inode from
  520.              the file's starting cluster number; if that fails, invent inode.
  521.              Note that the if clause below tests for non-zero value returned
  522.              by is_remote_drive(), which includes possible failure (-1).
  523.              This is because findfirst() already succeeded for our pathname,
  524.              and therefore the drive is a legal one; the only possibility that
  525.              is_remote_drive() fails is that some network redirector takes
  526.              over IOCTL functions in an incompatible way, which means the
  527.              drive is remote.  QED.  */
  528.           if (_is_remote_drive(drv_no) ||
  529.               (statbuf->st_ino = get_inode_from_sda(ff_blk.ff_name)) == 0)
  530.             {
  531.               _djstat_fail_bits |= _STFAIL_HASH;
  532.               statbuf->st_ino =
  533.                 _invent_inode(canon_path, dos_ftime, ff_blk.ff_fsize);
  534.             }
  535.       else if (toupper (canon_path[0]) != toupper (path[0])
  536.            && canon_path[1] == ':'
  537.            && canon_path[2] == '\\'
  538.            && canon_path[3] == '\0')
  539.         /* The starting cluster in SDA for the root of JOINed drive
  540.            actually belongs to the directory where that drive is
  541.            ``mounted''.  This can potentially be the cluster of
  542.            another file on the JOINed drive.  We cannot allow this.  */
  543.         statbuf->st_ino = 1;
  544.         }
  545.  
  546.       /* File size. */
  547.       statbuf->st_size = ff_blk.ff_fsize;
  548.  
  549.       /* Mode bits. */
  550.       statbuf->st_mode |= READ_ACCESS;
  551.       if ( !(ff_blk.ff_attrib & 0x07) )  /* no R, H or S bits set */
  552.         statbuf->st_mode |= WRITE_ACCESS;
  553.  
  554.       /* Directories should have Execute bits set. */
  555.       if (ff_blk.ff_attrib & 0x10)
  556.         statbuf->st_mode |= (S_IFDIR | EXEC_ACCESS);
  557.  
  558.       else
  559.         {
  560.           /* This is a regular file. */
  561.           char *extension  = strrchr(ff_blk.ff_name, '.');
  562.  
  563.           /* Set regular file bit.  */
  564.           statbuf->st_mode |= S_IFREG;
  565.  
  566.           if ((_djstat_flags & _STAT_EXECBIT) != _STAT_EXECBIT)
  567.             {
  568.               /* Set execute bits based on file's extension and
  569.                  first 2 bytes. */
  570.               if (extension)
  571.                 extension++;    /* get past the dot */
  572.               if (_is_executable(path, -1, extension))
  573.                 statbuf->st_mode |= EXEC_ACCESS;
  574.             }
  575.         }
  576.     }
  577.   else if ((_djstat_fail_bits & _STFAIL_TRUENAME))
  578.     {
  579.       /* If both `findfirst' and `_truename' failed, this must
  580.      be a non-existent file or an illegal/inaccessible drive.  */
  581.       if (errno == ENMFILE)
  582.     errno = ENODEV;
  583.       return -1;
  584.     }
  585.   else if (path[3] == '\0')
  586.     {
  587.       /* Detect root directories.  These are special because, unlike
  588.      subdirectories, FindFirst fails for them.  We look at PATH
  589.      because a network redirector could tweak what `_truename'
  590.      returns to be utterly unrecognizable as root directory.
  591.      PATH always begins with "d:/", so it is root if PATH[3] = 0.  */
  592.  
  593.       /* Mode bits. */
  594.       statbuf->st_mode |= (S_IFDIR|READ_ACCESS|WRITE_ACCESS|EXEC_ACCESS);
  595.  
  596.       /* Root directory will have an inode = 1.  Valid cluster numbers
  597.          for real files under DOS start with 2. */
  598.       statbuf->st_ino = 1;
  599.  
  600.       /* Simulate zero size.  This is what FindFirst returns for every
  601.          sub-directory.  Later we might compute a better approximation
  602.          (see below).  */
  603.       ff_blk.ff_fsize = 0L;
  604.  
  605.       /* The time fields are left to be zero, unless the user wants us
  606.          to try harder.  In the latter case, we check if the root has
  607.          a volume label entry, and use its time if it has. */
  608.  
  609.       if ( (_djstat_flags & _STAT_ROOT_TIME) == 0 )
  610.     {
  611.       char buf[7];
  612.  
  613.       strcpy(buf, path);
  614.       strcat(buf, "*.*");
  615.       if (!__findfirst(buf, &ff_blk, FA_LABEL))
  616.         dos_ftime = ( (unsigned)ff_blk.ff_fdate << 16 ) + ff_blk.ff_ftime;
  617.       else
  618.         _djstat_fail_bits |= _STFAIL_LABEL;
  619.     }
  620.     }
  621.   else
  622.     {
  623.       /* Check for volume labels.  We did not mix FA_LABEL with
  624.      other attributes in the call to `__findfirst' above,
  625.      because some environments will return bogus info in
  626.      that case.  For instance, Win95 and WinNT seem to
  627.      ignore `path' and return the volume label even if it
  628.      doesn't fit the name in `path'.  This fools us to
  629.      think that a non-existent file exists and is a volume
  630.      label.  Hence we test the returned name to be PATH.  */
  631.       if (!__findfirst(path, &ff_blk, FA_LABEL))
  632.     {
  633.       int i = strlen (ff_blk.ff_name) - 1;
  634.       int j = strlen (path) - 1;
  635.  
  636.       if (j >= i)
  637.         {
  638.           for ( ; i >= 0 && j >= 0; i--, j--)
  639.         if (toupper (ff_blk.ff_name[i]) != toupper (path[j]))
  640.           break;
  641.         }
  642.  
  643.       if (i < 0 && path[j] == '/')
  644.         {
  645.           /* Indeed a label.  */
  646.           statbuf->st_mode = READ_ACCESS;
  647. #ifdef  S_IFLABEL
  648.           statbuf->st_mode |= S_IFLABEL;
  649. #endif
  650.           statbuf->st_ino = 1;
  651.           statbuf->st_size = 0;
  652.           dos_ftime =
  653.         ( (unsigned)ff_blk.ff_fdate << 16 ) + ff_blk.ff_ftime;
  654.         }
  655.     }
  656.       else
  657.     {
  658.       /* FindFirst might set errno to ENMFILE; correct that.  */
  659.       if (errno == ENMFILE)
  660.         errno = ENOENT;
  661.       return -1;
  662.     }
  663.     }
  664.  
  665.   /* Device code. */
  666.   statbuf->st_dev = drv_no;
  667. #ifdef  HAVE_ST_RDEV
  668.   statbuf->st_rdev = drv_no;
  669. #endif
  670.  
  671.   /* Time fields. */
  672.   statbuf->st_atime = statbuf->st_mtime = statbuf->st_ctime =
  673.     _file_time_stamp(dos_ftime);
  674.  
  675.   if ( ! strcmp(ff_blk.lfn_magic,"LFN32") )
  676.     {
  677.       unsigned xtime;
  678.       xtime = *(unsigned *)&ff_blk.lfn_ctime;
  679.       if(xtime)            /* May be zero if file written w/o lfn active */
  680.         statbuf->st_ctime = _file_time_stamp(xtime);
  681.       xtime = *(unsigned *)&ff_blk.lfn_atime;
  682.       if(xtime > dos_ftime)    /* Accessed time is date only, no time */
  683.         statbuf->st_atime = _file_time_stamp(xtime);
  684.     }
  685.  
  686.   if ( (statbuf->st_mode & S_IFMT) == S_IFDIR
  687.        && (_djstat_flags & _STAT_DIRSIZE) == 0 )
  688.     {
  689.       /* Under DOS, directory entries for subdirectories have
  690.          zero size.  Therefore, FindFirst brings us zero size
  691.          when called on a directory.  (Some network redirectors
  692.          might do a better job, thus below we also test for zero size
  693.          actually being returned.)  If we have zero-size directory,
  694.          we compute here the actual directory size by reading its
  695.          entries, then multiply their number by 32 (the size of a
  696.          directory entry under DOS).  This might lose in the case
  697.          that many files were deleted from a once huge directory,
  698.          because AFAIK, directories don't return unused clusters to
  699.          the disk pool.  Still, it is a good approximation of the
  700.          actual directory size.
  701.  
  702.          We also take this opportunity to return the number of links
  703.          for directories as Unix programs expect it to be: the number
  704.          of subdirectories, plus 2 (the directory itself and the ``.''
  705.          entry).
  706.  
  707.          The (max) size of the root directory could also be taken from
  708.          the disk BIOS Parameter Block (BPB) which can be obtained
  709.          by calling IOCTL (INT 21/AH=44H), subfunction 0DH, minor
  710.          function 60H.  But we will treat all directories the same,
  711.          even at performance cost, because it's more robust for
  712.          networked drives.  */
  713.  
  714.       size_t pathlen = strlen (path);
  715.       char   lastc   = path[pathlen - 1];
  716.       char  *search_spec = (char *)alloca (pathlen + 10); /* need only +5 */
  717.       int nfiles = 0, nsubdirs = 0, done;
  718.       size_t extra = 0;
  719.       int add_extra = 0;
  720.  
  721.       strcpy(search_spec, path);
  722.       if (lastc == '/')
  723.         strcat(search_spec, "*.*");
  724.       else
  725.         strcat(search_spec, "/*.*");
  726.  
  727.       if (statbuf->st_size == 0 && _USE_LFN)
  728.     {
  729.       /* VFAT filesystems use additional directory entries to
  730.          store the long filenames.  */
  731.       char fstype[40];
  732.  
  733.       if ((_get_volume_info(path, 0, 0, fstype) & _FILESYS_LFN_SUPPORTED)
  734.           && strncmp(fstype, "FAT", 4) == 0)
  735.         add_extra = 1;
  736.     }
  737.  
  738.       /* Count files and subdirectories.  */
  739.       for (done = __findfirst(search_spec, &ff_blk, ALL_FILES);
  740.        !done;
  741.        done = __findnext(&ff_blk))
  742.     {
  743.       register char *fname = ff_blk.ff_name;
  744.  
  745.       /* Don't count "." and ".." entries.  This will show empty
  746.          directories as size 0.  */
  747.       if (! (fname[0] == '.'
  748.          && (fname[1] == '\0'
  749.              || (fname[1] == '.'
  750.              && fname[2] == '\0'))))
  751.         {
  752.           char fn[13];
  753.  
  754.           nfiles++;
  755.           if (ff_blk.ff_attrib & 0x10)
  756.         nsubdirs++;
  757.           /* For each 13 characters of the long filename, a
  758.          32-byte directory entry is used.  */
  759.           if (add_extra && strcmp(_lfn_gen_short_fname(fname, fn), fname))
  760.         extra += (strlen(fname) + 12) / 13;
  761.         }
  762.     }
  763.  
  764.       statbuf->st_nlink = nsubdirs + 2;
  765.       if (statbuf->st_size == 0)
  766.     statbuf->st_size  = (nfiles + extra) * sizeof(struct full_dirent);
  767.     }
  768.  
  769.   return 0;
  770. }
  771.  
  772. /* Main entry point.  This is library stat() function.
  773.  */
  774.  
  775. int
  776. stat(const char *path, struct stat *statbuf)
  777. {
  778.   int  e = errno;
  779.   char pathname[MAX_TRUE_NAME];
  780.   int  pathlen;
  781.  
  782.   if (!path || !statbuf)
  783.     {
  784.       errno = EFAULT;
  785.       return -1;
  786.     }
  787.  
  788.   if ((pathlen = strlen (path)) >= MAX_TRUE_NAME)
  789.     {
  790.       errno = ENAMETOOLONG;
  791.       return -1;
  792.     }
  793.  
  794.   /* Fail if PATH includes wildcard characters supported by FindFirst.  */
  795.   if (memchr(path, '*', pathlen) || memchr(path, '?', pathlen))
  796.     {
  797.       errno = ENOENT;    /* since no such filename is possible */
  798.       return -1;
  799.     }
  800.  
  801.   /* Make the path explicit.  This makes the rest of our job much
  802.      easier by getting rid of some constructs which, if present,
  803.      confuse `_truename' and/or `findfirst'.  In particular, it
  804.      deletes trailing slashes, makes "d:" explicit, and allows us
  805.      to make an illusion of having a ".." entry in root directories.  */
  806.   _fixpath (path, pathname);
  807.  
  808.   if (stat_assist(pathname, statbuf) == -1)
  809.     {
  810.       return -1;      /* errno set by stat_assist() */
  811.     }
  812.   else
  813.     {
  814.       errno = e;
  815.       return 0;
  816.     }
  817. }
  818.  
  819. #ifdef  TEST
  820.  
  821. unsigned short _djstat_flags = 0;
  822.  
  823. void
  824. main(int argc, char *argv[])
  825. {
  826.   struct stat stat_buf;
  827.   char *endp;
  828.  
  829.   if (argc < 2)
  830.     {
  831.       fprintf (stderr, "Usage: %s <_djstat_flags> <file...>\n", argv[0]);
  832.       exit(0);
  833.     }
  834.  
  835.   if (stat(*argv, &stat_buf) != 0)
  836.     perror ("stat failed on argv[0]");
  837.   else
  838.     fprintf(stderr, "DOS %d.%d (%s)\n", _osmajor, _osminor, _os_flavor);
  839.   argc--; argv++;
  840.  
  841.   _djstat_flags = (unsigned short)strtoul(*argv, &endp, 0);
  842.   argc--; argv++;
  843.  
  844.   while (argc--)
  845.     {
  846.       if (!stat(*argv, &stat_buf))
  847.         {
  848.           fprintf(stderr, "%s: %d %6u %o %d %d %ld %lu %s", *argv,
  849.                   stat_buf.st_dev,
  850.                   (unsigned)stat_buf.st_ino,
  851.                   stat_buf.st_mode,
  852.                   stat_buf.st_nlink,
  853.                   stat_buf.st_uid,
  854.                   (long)stat_buf.st_size,
  855.                   (unsigned long)stat_buf.st_mtime,
  856.                   ctime(&stat_buf.st_mtime));
  857.           _djstat_describe_lossage(stderr);
  858.         }
  859.       else
  860.         {
  861.           fprintf(stderr, "%s: lossage", *argv);
  862.           perror(" ");
  863.           _djstat_describe_lossage(stderr);
  864.         }
  865.  
  866.       ++argv;
  867.     }
  868.  
  869.     exit (0);
  870. }
  871.  
  872. #endif
  873.  
  874.