Subversion Repositories QNX 8.QNX8 IFS tool

Rev

Rev 27 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. // dump.c -- information dumping routines for ifstool
  2.  
  3. // standard C includes
  4. #include <stdint.h>
  5. #include <stdbool.h>
  6. #include <stdlib.h>
  7. #include <stdarg.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <errno.h>
  11. #include <sys/stat.h>
  12. #include <ctype.h>
  13. #include <time.h>
  14.  
  15. // platform-specific includes
  16. #ifdef _MSC_VER
  17. #include <direct.h>
  18. #include <sys/utime.h>
  19. #else // !_MSC_VER
  20. #include <sys/param.h>
  21. #include <unistd.h>
  22. #include <utime.h>
  23. #endif // _MSC_VER
  24.  
  25. // own includes
  26. #include "buffer.h"
  27. #include "sha512.h"
  28. #include "ifsfile.h"
  29. #include "elffile.h"
  30. #include "utility.h"
  31.  
  32.  
  33. // imported global variables
  34. extern int verbose_level; // from ifstool.c
  35.  
  36.  
  37. // exported function prototypes
  38. int dump_ifs_info (const char *ifs_pathname, bool want_everything); // dumps detailed info about a particular IFS file on the standard output, returns 0 on success and >0 on error
  39. int dump_ifs_contents (const char *ifs_pathname, const char *outdir); // dumps the IFS filesystem contents in outdir, returns 0 on success and >0 on error
  40. int dump_file_hex (const char *pathname); // hexdump the content of pathname, returns 0 on success and != 0 on error
  41.  
  42.  
  43. // prototypes of local functions
  44. static int create_intermediate_dirs (const char *file_pathname); // creates all intermediate directories from root (or cwd) up to file_path, returns 0 on success and != 0 on error
  45. static void hex_fprintf (FILE *fp, const uint8_t *data, size_t data_size, int howmany_columns, const char *fmt, ...); // hexdump-style formatted output to a file stream (which may be stdout/stderr)
  46. static char *binary (const uint8_t x, char char_for_zero, char char_for_one); // returns the binary representation of x as a string
  47. static char *describe_uint8 (const uint8_t x, const char *bitwise_stringdescs[8]); // returns the ORed description of byte 'x' according to the description strings for each bit
  48.  
  49.  
  50. // imported function prototypes
  51. extern int32_t update_checksum (const void *data, const size_t data_len, const bool is_foreign_endianness); // from ifstool.c
  52.  
  53.  
  54. static int create_intermediate_dirs (const char *file_pathname)
  55. {
  56.    // creates all intermediate directories from root (or cwd) up to file_path
  57.  
  58.    char *temp_pathname;
  59.    char *separator;
  60.    char *ctx;
  61.    size_t string_index;
  62.    size_t length;
  63.  
  64.    temp_pathname = strdup (file_pathname); // have a working copy of file_pathname
  65.    if (temp_pathname == NULL)
  66.       return (-1); // on strdup() failure, return an error value (errno is set)
  67.    length = strlen (temp_pathname);
  68.    for (string_index = length - 1; string_index != SIZE_MAX; string_index--) // i.e. loop until it overflows
  69.       if ((temp_pathname[string_index] == '/') || (temp_pathname[string_index] == '\\'))
  70.          break; // look for the last directory separator and stop as soon as we find it
  71.    if (string_index != SIZE_MAX)
  72.    {
  73.       for (; string_index < length; string_index++)
  74.          temp_pathname[string_index] = 0; // if we found one, break there so as to have just the path and clear the rest of the string
  75.       separator = strtok_r (&temp_pathname[1], "/\\", &ctx); // for each separator in the remaining string past the first one...
  76.       while (separator != NULL)
  77.       {
  78.          (void) mkdir (temp_pathname, 0755); // create directories recursively
  79.          temp_pathname[strlen (temp_pathname)] = '/'; // put the separator back
  80.          separator = strtok_r (NULL, "/\\", &ctx); // and look for the next one
  81.       }
  82.    }
  83.  
  84.    free (temp_pathname); // release our working copy of file_pathname
  85.    return (0);
  86. }
  87.  
  88.  
  89. static void hex_fprintf (FILE *fp, const uint8_t *data, size_t data_size, int howmany_columns, const char *fmt, ...)
  90. {
  91.    // this function logs hexadecimal data to an opened file pointer (or to stdout/stderr)
  92.  
  93.    va_list argptr;
  94.    size_t index;
  95.    int i;
  96.  
  97.    // concatenate all the arguments in one string and write it to the file
  98.    va_start (argptr, fmt);
  99.    vfprintf (fp, fmt, argptr);
  100.    va_end (argptr);
  101.  
  102.    // for each row of howmany_columns bytes of data...
  103.    for (index = 0; index < data_size; index += howmany_columns)
  104.    {
  105.       fprintf (fp, "    %05zu  ", index); // print array address of row
  106.       for (i = 0; i < howmany_columns; i++)
  107.          if (index + i < data_size)
  108.             fprintf (fp, " %02X", data[index + i]); // if row contains data, print data as hex bytes
  109.          else
  110.             fprintf (fp, "   "); // else fill the space with blanks
  111.       fprintf (fp, "   ");
  112.       for (i = 0; i < howmany_columns; i++)
  113.          if (index + i < data_size)
  114.             fputc ((data[index + i] >= 32) && (data[index + i] < 127) ? data[index + i] : '.', fp); // now if row contains data, print data as ASCII
  115.          else
  116.             fputc (' ', fp); // else fill the space with blanks
  117.       fputc ('\n', fp);
  118.    }
  119.  
  120.    return; // and return
  121. }
  122.  
  123.  
  124. static char *binary (const uint8_t x, char char_for_zero, char char_for_one)
  125. {
  126.    // returns the binary representation of x as a string
  127.  
  128.    static thread_local char outstr[9] = "00000000";
  129.    for (int i = 0; i < 8; i++)
  130.       outstr[i] = (x & (0x80 >> i) ? char_for_one : char_for_zero);
  131.    return (outstr);
  132. }
  133.  
  134.  
  135. static char *describe_uint8 (const uint8_t x, const char *bitwise_stringdescs[8])
  136. {
  137.    // returns the ORed description of byte 'x' according to the description strings for each bit
  138.  
  139.    static char *default_bitstrings[8] = { "bit0", "bit1", "bit2", "bit3", "bit4", "bit5", "bit6", "bit7" };
  140.    static thread_local char outstr[8 * 64] = "";
  141.  
  142.    outstr[0] = 0;
  143.    for (int i = 0; i < 8; i++)
  144.       if (x & (1 << i))
  145.       {
  146.          if (outstr[0] != 0)
  147.             strcat_s (outstr, sizeof (outstr), "|");
  148.          strcat_s (outstr, sizeof (outstr), ((bitwise_stringdescs != NULL) && (*bitwise_stringdescs[i] != 0) ? bitwise_stringdescs[i] : default_bitstrings[i]));
  149.       }
  150.    return (outstr);
  151. }
  152.  
  153.  
  154. int dump_ifs_info (const char *ifs_pathname, bool want_everything)
  155. {
  156.    #define hex_printf(buf,size,...) do { \
  157.       if (want_everything || ((size) <= 16 * 1024)) /* only print when it's not too big (up to 16 kb) */\
  158.          hex_fprintf (stdout, (buf), (size), 16, __VA_ARGS__); /* use 16 columns in hex output to stdout */ \
  159.       else { \
  160.          printf (__VA_ARGS__); \
  161.          hex_fprintf (stdout, (buf), 1024, 16, "   first kilobyte:\n"); \
  162.       } \
  163.    } while (0)
  164.    #define BINARY(x) binary ((x), '-', 'x')
  165.  
  166.    static const char *startupheader_flags1_strings[8] = {
  167.       "VIRTUAL", // bit 0
  168.       "BIGENDIAN", // bit 1
  169.       "COMPRESS_BIT1", // bit 2
  170.       "COMPRESS_BIT2", // bit 3
  171.       "COMPRESS_BIT3", // bit 4
  172.       "TRAILER_V2", // bit 5
  173.       "", // bit 6
  174.       "", // bit 7
  175.    };
  176.    static const char *imageheader_flags_strings[8] = {
  177.       "BIGENDIAN", // bit 0
  178.       "READONLY", // bit 1
  179.       "INO_BITS", // bit 2
  180.       "SORTED", // bit 3
  181.       "TRAILER_V2", // bit 4
  182.       "", // bit 5
  183.       "", // bit 6
  184.       "", // bit 7
  185.    };
  186.  
  187.    startup_header_t *startup_header = NULL;
  188.    size_t startupheader_offset = 0;
  189.    startup_trailer_v1_t *startup_trailer_v1 = NULL;
  190.    startup_trailer_v2_t *startup_trailer_v2 = NULL;
  191.    size_t startuptrailer_offset = 0;
  192.    image_header_t *image_header = NULL;
  193.    size_t imageheader_offset = 0;
  194.    image_trailer_v1_t *image_trailer_v1 = NULL;
  195.    image_trailer_v2_t *image_trailer_v2 = NULL;
  196.    size_t imagetrailer_offset = 0;
  197.    fsentry_t **fsentries = NULL; // mallocated
  198.    size_t fsentry_count = 0;
  199.    fsentry_t *current_fsentry = NULL;
  200.    char recorded_sha512[2 * SHA512_DIGEST_LENGTH + 1] = "";
  201.    char computed_sha512[2 * SHA512_DIGEST_LENGTH + 1] = "";
  202.    size_t startupfile_blobsize = 0;
  203.    void *reallocated_ptr;
  204.    bool is_foreign_endianness;
  205.    size_t bootfile_blobsize = 0;
  206.    size_t current_offset;
  207.    size_t fsentry_index;
  208.    size_t nearest_distance;
  209.    size_t nearest_index;
  210.    size_t byte_index;
  211.    uint32_t recorded_checksum;
  212.    uint32_t computed_checksum;
  213.    buffer_t file;
  214.    time_t mtime;
  215.  
  216.    // open and read IFS file
  217.    if (!Buffer_ReadFromFile (&file, ifs_pathname))
  218.       DIE_WITH_EXITCODE (1, "can't open \"%s\" for reading: %s", ifs_pathname, strerror (errno));
  219.  
  220.    printf ("QNX In-kernel Filesystem analysis produced by ifstool version " VERSION_FMT_YYYYMMDD "\n", VERSION_ARG_YYYYMMDD);
  221.    printf ("IFS file \"%s\" - size 0x%zx (%zd) bytes\n", ifs_pathname, file.size, file.size);
  222.  
  223.    // parse file from start to end
  224.    current_offset = 0;
  225.    for (;;)
  226.    {
  227.       // does a startup header start here ?
  228.       if ((current_offset + sizeof (startup_header_t) < file.size) && (memcmp (&file.bytes[current_offset], "\xeb\x7e\xff\x00", 4) == 0))
  229.       {
  230.          startupheader_offset = current_offset;
  231.          startup_header = (startup_header_t *) &file.bytes[startupheader_offset];
  232.  
  233.          // layout:
  234.          // [STARTUP HEADER]
  235.          // (startup file blob)
  236.          // [STARTUP TRAILER v1 or v2]
  237.  
  238.          printf ("\n");
  239.          printf ("Startup header at offset 0x%zx (%zd):\n", current_offset, current_offset);
  240.          printf ("   signature     = %02x %02x %02x %02x - good\n", startup_header->signature[0], startup_header->signature[1], startup_header->signature[2], startup_header->signature[3]);
  241.          printf ("   version       = 0x%04x (%d) - %s\n", startup_header->version, startup_header->version, (startup_header->version == 1 ? "looks good" : "???"));
  242.          printf ("   flags1        = 0x%02x (%s)\n", startup_header->flags1, describe_uint8 (startup_header->flags1, startupheader_flags1_strings));
  243.          printf ("   flags2        = 0x%02x (%s) - %s\n", startup_header->flags2, BINARY (startup_header->flags2), (startup_header->flags2 == 0 ? "looks good" : "???"));
  244.          printf ("   header_size   = 0x%04x (%d) - %s\n", startup_header->header_size, startup_header->header_size, (startup_header->header_size == sizeof (startup_header_t) ? "looks good" : "BAD"));
  245.          printf ("   machine       = 0x%04x (%d) - %s\n", startup_header->machine, startup_header->machine, (startup_header->machine == ELF_MACHINE_X86_64 ? "x86_64" : (startup_header->machine == ELF_MACHINE_AARCH64 ? "aarch64" : "unknown")));
  246.          printf ("   startup_vaddr = 0x%08x (%d) - virtual address to transfer to after IPL is done\n", startup_header->startup_vaddr, startup_header->startup_vaddr);
  247.          printf ("   paddr_bias    = 0x%08x (%d) - value to add to physical addresses to get an indirectable pointer value\n", startup_header->paddr_bias, startup_header->paddr_bias);
  248.          printf ("   image_paddr   = 0x%08x (%d) - physical address of image\n", startup_header->image_paddr, startup_header->image_paddr);
  249.          printf ("   ram_paddr     = 0x%08x (%d) - physical address of RAM to copy image to (startup_size bytes copied)\n", startup_header->ram_paddr, startup_header->ram_paddr);
  250.          printf ("   ram_size      = 0x%08x (%d) - amount of RAM used by the startup program and executables in the fs\n", startup_header->ram_size, startup_header->ram_size);
  251.          printf ("   startup_size  = 0x%08x (%d) - size of startup (never compressed) - %s\n", startup_header->startup_size, startup_header->startup_size, (current_offset + sizeof (image_header_t) + startup_header->startup_size + (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2 ? sizeof (image_trailer_v2_t) : sizeof (image_trailer_v1_t)) < file.size ? "looks good" : "BAD (IFS file too short)"));
  252.          printf ("   stored_size   = 0x%08x (%d) - size of entire image - %s\n", startup_header->stored_size, startup_header->stored_size, (startup_header->stored_size == startup_header->ram_size ? "looks good" : "???"));
  253.          printf ("   imagefs_paddr = 0x%08x (%d) - set by IPL when startup runs - %s\n", startup_header->imagefs_paddr, startup_header->imagefs_paddr, (startup_header->imagefs_paddr == 0 ? "looks good" : "??? should be zero"));
  254.          printf ("   imagefs_size  = 0x%08x (%d) - size of uncompressed imagefs\n", startup_header->imagefs_size, startup_header->imagefs_size);
  255.          printf ("   preboot_size  = 0x%04x (%d) - size of loaded before header - %s\n", startup_header->preboot_size, startup_header->preboot_size, (startup_header->preboot_size == current_offset ? "looks good" : "???"));
  256.          printf ("   zero0         = 0x%04x (%d) - zeros - %s\n", startup_header->zero0, startup_header->zero0, (startup_header->zero0 == 0 ? "looks good" : "??? should be zero"));
  257.          printf ("   zero[0]       = 0x%08x (%d) - zeros - %s\n", startup_header->zero[0], startup_header->zero[0], (startup_header->zero[0] == 0 ? "looks good" : "??? should be zero"));
  258.          printf ("   addr_off      = 0x%016llx (%lld) - offset for startup_vaddr and [image|ram|imagefs]_paddr - %s\n", (unsigned long long) startup_header->addr_off, (unsigned long long) startup_header->addr_off, (startup_header->addr_off == 0 ? "looks good" : "??? should be zero"));
  259.          hex_printf ((uint8_t *) &startup_header->info[0], sizeof (startup_header->info), "   info[48] =\n");
  260.  
  261.          // validate that the file can contain up to the startup trailer
  262.          if (current_offset + startup_header->startup_size > file.size)
  263.          {
  264.             LOG_WARNING ("this IFS file is corrupted (startup trailer extends past end of file)");
  265.             goto endofdata;
  266.          }
  267.  
  268.          // check if this endianness is ours
  269.          if (   ( (startup_header->flags1 & STARTUP_HDR_FLAGS1_BIGENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
  270.              || (!(startup_header->flags1 & STARTUP_HDR_FLAGS1_BIGENDIAN) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)))
  271.             is_foreign_endianness = true; // if the header is big endian and we're on a little endian machine, or the other way around, it's a foreign endianness
  272.          else
  273.             is_foreign_endianness = false; // else this header is for the same endianness as us
  274.  
  275.          // locate the right startup trailer at the right offset
  276.          if (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2)
  277.          {
  278.             startuptrailer_offset = current_offset + startup_header->startup_size - sizeof (startup_trailer_v2_t);
  279.             startup_trailer_v2 = (startup_trailer_v2_t *) &file.bytes[startuptrailer_offset];
  280.             startupfile_blobsize = startup_header->startup_size - sizeof (startup_header_t) - sizeof (startup_trailer_v2_t);
  281.          }
  282.          else // old V1 trailer
  283.          {
  284.             startuptrailer_offset = current_offset + startup_header->startup_size - sizeof (startup_trailer_v1_t);
  285.             startup_trailer_v1 = (startup_trailer_v1_t *) &file.bytes[startuptrailer_offset];
  286.             startupfile_blobsize = startup_header->startup_size - sizeof (startup_header_t) - sizeof (startup_trailer_v1_t);
  287.          }
  288.  
  289.          current_offset += sizeof (startup_header_t); // jump over the startup header and reach the startup blob
  290.          printf ("\n");
  291.          printf ("Startup blob at offset 0x%zx (%zd):\n", current_offset, current_offset);
  292.          printf ("   size 0x%zx (%zd) bytes\n", startupfile_blobsize, startupfile_blobsize);
  293.          printf ("   checksum 0x%08x\n", update_checksum (&file.bytes[current_offset], startupfile_blobsize, is_foreign_endianness));
  294.  
  295.          current_offset += startupfile_blobsize; // jump over the startup blob and reach the startup trailer
  296.          printf ("\n");
  297.          printf ("Startup trailer at offset 0x%zx (%zd) - version %d:\n", current_offset, current_offset, (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2 ? 2 : 1));
  298.          if (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2)
  299.          {
  300.             for (byte_index = 0; byte_index < SHA512_DIGEST_LENGTH; byte_index++)
  301.                sprintf_s (&recorded_sha512[2 * byte_index], 3, "%02x", startup_trailer_v2->sha512[byte_index]);
  302.             strcpy_s (computed_sha512, sizeof (computed_sha512), SHA512 (startup_header, startuptrailer_offset - startupheader_offset, NULL));
  303.             recorded_checksum = startup_trailer_v2->cksum;
  304.             computed_checksum = update_checksum (startup_header, startuptrailer_offset + SHA512_DIGEST_LENGTH - startupheader_offset, is_foreign_endianness);
  305.             printf ("    sha512([0x%zx-0x%zx[) = %s - %s\n", startupheader_offset, startuptrailer_offset, recorded_sha512, (strcasecmp (computed_sha512, recorded_sha512) == 0 ? "GOOD" : "BAD"));
  306.             printf ("    cksum([0x%zx-0x%zx[) = 0x%08x - %s\n", startupheader_offset, startuptrailer_offset + SHA512_DIGEST_LENGTH, recorded_checksum, (computed_checksum == recorded_checksum ? "GOOD" : "BAD"));
  307.             if (strcasecmp (computed_sha512, recorded_sha512) != 0)
  308.                printf ("Computed SHA-512: %s\n", computed_sha512);
  309.             if (computed_checksum != recorded_checksum)
  310.                printf ("Computed cksum: 0x%08x\n", computed_checksum);
  311.          }
  312.          else // old v1 trailer
  313.          {
  314.             recorded_checksum = startup_trailer_v1->cksum;
  315.             computed_checksum = update_checksum (startup_header, sizeof (startup_header) + startupfile_blobsize, is_foreign_endianness);
  316.             printf ("    cksum([0x%zx-0x%zx[) = 0x%08x - %s\n", startupheader_offset, startuptrailer_offset, recorded_checksum, (computed_checksum == recorded_checksum ? "GOOD" : "BAD"));
  317.             if (computed_checksum != recorded_checksum)
  318.                printf ("Computed cksum: 0x%08x\n", computed_checksum);
  319.          }
  320.  
  321.          current_offset += (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2 ? sizeof (startup_trailer_v2_t) : sizeof (startup_trailer_v1_t)); // now reach the next segment
  322.       }
  323.  
  324.       // else does an image header start here ?
  325.       else if ((current_offset + sizeof (image_header_t) < file.size) && (memcmp (&file.bytes[current_offset], "imagefs", 7) == 0))
  326.       {
  327.          imageheader_offset = current_offset;
  328.          image_header = (image_header_t *) &file.bytes[imageheader_offset];
  329.  
  330.          // layout:
  331.          // [IMAGE HEADER]
  332.          // [image directory entries]
  333.          // [smallest file blobs up to KERNEL]
  334.          // [padding]
  335.          // [KERNEL]
  336.          // [rest of file blobs]
  337.          // [IMAGE FOOTER]
  338.  
  339.          printf ("\n");
  340.          printf ("Image header at offset %zx (%zd):\n", current_offset, current_offset);
  341.          printf ("   signature    = %02x %02x %02x %02x %02x %02x %02x (\"%.7s\") - good\n", image_header->signature[0], image_header->signature[1], image_header->signature[2], image_header->signature[3], image_header->signature[4], image_header->signature[5], image_header->signature[6], image_header->signature);
  342.          printf ("   flags        = 0x%02x (%s)\n", image_header->flags, describe_uint8 (image_header->flags, imageheader_flags_strings));
  343.          printf ("   image_size   = 0x%08x (%d) - size from header to end of trailer - %s\n", image_header->image_size, image_header->image_size, (current_offset + image_header->image_size <= file.size ? "looks good" : "BAD (IFS file too short)"));
  344.          printf ("   hdr_dir_size = 0x%08x (%d) - size from header to last dirent - %s\n", image_header->hdr_dir_size, image_header->hdr_dir_size, (current_offset + image_header->hdr_dir_size < file.size ? "looks good" : "BAD (IFS file too short)"));
  345.          printf ("   dir_offset   = 0x%08x (%d) - offset from header to first dirent - %s\n", image_header->dir_offset, image_header->dir_offset, (current_offset + image_header->dir_offset >= file.size ? "BAD (IFS file too short)" : (image_header->dir_offset > image_header->hdr_dir_size ? "BAD" : "looks good")));
  346.          printf ("   boot_ino[4]  = { 0x%08x, 0x%08x, 0x%08x, 0x%08x }\n", image_header->boot_ino[0], image_header->boot_ino[1], image_header->boot_ino[2], image_header->boot_ino[3]);
  347.          printf ("   script_ino   = 0x%08x (%d) - inode of compiled bootscript\n", image_header->script_ino, image_header->script_ino);
  348.          printf ("   chain_paddr  = 0x%08x (%d) - offset to next fs signature\n", image_header->chain_paddr, image_header->chain_paddr);
  349.          hex_printf ((uint8_t *) &image_header->spare[0], sizeof (image_header->spare), "   spare[10] =\n");
  350.          printf ("   mountflags   = 0x%08x (%s %s %s %s)\n", image_header->mountflags, BINARY (((uint8_t *) &image_header->mountflags)[0]), BINARY (((uint8_t *) &image_header->mountflags)[1]), BINARY (((uint8_t *) &image_header->mountflags)[2]), BINARY (((uint8_t *) &image_header->mountflags)[3]));
  351.          printf ("   mountpoint   = \"%s\"\n", image_header->mountpoint);
  352.  
  353.          // validate that the file can contain up to the image trailer
  354.          if (current_offset + image_header->image_size > file.size)
  355.          {
  356.             LOG_WARNING ("this IFS file is corrupted (image trailer extends past end of file)");
  357.             goto endofdata;
  358.          }
  359.  
  360.          // check if this endianness is ours
  361.          if (   ( (image_header->flags & IMAGE_FLAGS_BIGENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
  362.              || (!(image_header->flags & IMAGE_FLAGS_BIGENDIAN) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)))
  363.             is_foreign_endianness = true; // if the header is big endian and we're on a little endian machine, or the other way around, it's a foreign endianness
  364.          else
  365.             is_foreign_endianness = false; // else this header is for the same endianness as us
  366.  
  367.          // locate the image trailer at the right offset
  368.          if (image_header->flags & IMAGE_FLAGS_TRAILER_V2)
  369.          {
  370.             imagetrailer_offset = current_offset + image_header->image_size - sizeof (image_trailer_v2_t);
  371.             image_trailer_v2 = (image_trailer_v2_t *) &file.bytes[imagetrailer_offset];
  372.          }
  373.          else // old V1 trailer
  374.          {
  375.             imagetrailer_offset = current_offset + image_header->image_size - sizeof (image_trailer_v1_t);
  376.             image_trailer_v1 = (image_trailer_v1_t *) &file.bytes[imagetrailer_offset];
  377.          }
  378.  
  379.          current_offset += sizeof (image_header_t); // jump over the image header and reach the first directory entry
  380.  
  381.          // there may be padding before the first directory entry
  382.          if (image_header->dir_offset - sizeof (image_header_t) > 0)
  383.             hex_printf (&file.bytes[current_offset], image_header->dir_offset - sizeof (image_header_t), "\n" "%zd padding bytes at offset 0x%zd (%zd):\n", image_header->dir_offset - sizeof (image_header_t), current_offset, current_offset);
  384.          current_offset += image_header->dir_offset - sizeof (image_header_t); // padding was processed, jump over it
  385.  
  386.          // dump all directory entries until the last one included
  387.          fsentries = NULL;
  388.          fsentry_count = 0;
  389.          while (current_offset < imageheader_offset + image_header->hdr_dir_size)
  390.          {
  391.             current_fsentry = (fsentry_t *) &file.bytes[current_offset];
  392.  
  393.             if (imageheader_offset + image_header->hdr_dir_size - current_offset < sizeof (current_fsentry->header))
  394.                break; // end padding reached
  395.  
  396.             // stack up the filesystem entry pointers in an array while we read them
  397.             reallocated_ptr = realloc (fsentries, (fsentry_count + 1) * sizeof (fsentry_t *));
  398.             ASSERT_WITH_ERRNO (reallocated_ptr);
  399.             fsentries = reallocated_ptr;
  400.             fsentries[fsentry_count] = current_fsentry;
  401.             fsentry_count++;
  402.  
  403.             printf ("\n");
  404.             printf ("Filesystem entry at offset 0x%zx (%zd) - last one at 0x%zx (%zd):\n", current_offset, current_offset, imageheader_offset + image_header->hdr_dir_size, imageheader_offset + image_header->hdr_dir_size);
  405.             printf ("   size           = 0x%04x (%d) - size of dirent - %s\n", current_fsentry->header.size, current_fsentry->header.size, ((current_fsentry->header.size > 0) && (current_offset + current_fsentry->header.size < file.size) ? "looks good" : "BAD"));
  406.             printf ("   extattr_offset = 0x%04x (%d) - %s\n", current_fsentry->header.extattr_offset, current_fsentry->header.extattr_offset, (current_fsentry->header.extattr_offset == 0 ? "no extattr" : "has extattr"));
  407.             printf ("   ino            = 0x%08x (%d) - inode number (%s%s%s%s)\n", current_fsentry->header.ino, current_fsentry->header.ino, (current_fsentry->header.ino & 0xE0000000 ? "is" : "nothing special"), (current_fsentry->header.ino & IFS_INO_PROCESSED_ELF ? " PROCESSED_ELF" : ""), (current_fsentry->header.ino & IFS_INO_RUNONCE_ELF ? " RUNONCE_ELF" : ""), (current_fsentry->header.ino & IFS_INO_BOOTSTRAP_EXE ? " BOOTSTRAP_EXE" : ""));
  408.             printf ("   mode           = 0x%08x (%d) - %s (0%o), POSIX permissions 0%o\n", current_fsentry->header.mode, current_fsentry->header.mode, (S_ISDIR (current_fsentry->header.mode) ? "directory" : (S_ISREG (current_fsentry->header.mode) ? "file" : (S_ISLNK (current_fsentry->header.mode) ? "symlink" : "device"))), (current_fsentry->header.mode & 0xF000) >> 12, current_fsentry->header.mode & 0xFFF);
  409.             printf ("   gid            = 0x%08x (%d) - owner group ID%s\n", current_fsentry->header.gid, current_fsentry->header.gid, (current_fsentry->header.gid == 0 ? " (root)" : ""));
  410.             printf ("   uid            = 0x%08x (%d) - owner user ID%s\n", current_fsentry->header.uid, current_fsentry->header.uid, (current_fsentry->header.uid == 0 ? " (root)" : ""));
  411.             mtime = (time_t) current_fsentry->header.mtime;
  412.             printf ("   mtime          = 0x%08x (%d) - POSIX timestamp: %s", current_fsentry->header.mtime, current_fsentry->header.mtime, asctime (localtime (&mtime))); // NOTE: asctime() provides the newline
  413.             if (S_ISDIR (current_fsentry->header.mode))
  414.                printf ("   [DIRECTORY] path = \"%s\"\n", (char *) &current_fsentry->u.dir.path); // convert from pointer to char array
  415.             else if (S_ISREG (current_fsentry->header.mode))
  416.             {
  417.                printf ("   [FILE] offset = 0x%08x (%d) - %s\n", current_fsentry->u.file.offset, current_fsentry->u.file.offset, (imageheader_offset + current_fsentry->u.file.offset < file.size ? "looks good" : "BAD (IFS file too short)"));
  418.                printf ("   [FILE] size   = 0x%08x (%d) - %s\n", current_fsentry->u.file.size, current_fsentry->u.file.size, (imageheader_offset + current_fsentry->u.file.offset + current_fsentry->u.file.size < file.size ? "looks good" : "BAD (IFS file too short)"));
  419.                printf ("   [FILE] path   = \"%s\"\n", (char *) &current_fsentry->u.file.path); // convert from pointer to char array
  420.             }
  421.             else if (S_ISLNK (current_fsentry->header.mode))
  422.             {
  423.                printf ("   [SYMLINK] sym_offset = 0x%04x (%d) - %s\n", current_fsentry->u.symlink.sym_offset, current_fsentry->u.symlink.sym_offset, (sizeof (current_fsentry->header) + 2 * sizeof (uint16_t) + current_fsentry->u.symlink.sym_offset <= current_fsentry->header.size ? "looks good" : "BAD (dirent too short)"));
  424.                printf ("   [SYMLINK] sym_size   = 0x%04x (%d) - %s\n", current_fsentry->u.symlink.sym_size, current_fsentry->u.symlink.sym_size, (sizeof (current_fsentry->header) + 2 * sizeof (uint16_t) + current_fsentry->u.symlink.sym_offset + current_fsentry->u.symlink.sym_size <= current_fsentry->header.size ? "looks good" : "BAD (dirent too short)"));
  425.                printf ("   [SYMLINK] path       = \"%s\"\n", (char *) &current_fsentry->u.symlink.path); // convert from pointer to char array
  426.                printf ("   [SYMLINK] contents   = \"%s\"\n", ((char *) &current_fsentry->u.symlink.path) + current_fsentry->u.symlink.sym_offset); // convert from pointer to char array
  427.             }
  428.             else // can only be a device
  429.             {
  430.                printf ("   [DEVICE] dev  = 0x%08x (%d)\n", current_fsentry->u.device.dev, current_fsentry->u.device.dev);
  431.                printf ("   [DEVICE] rdev = 0x%08x (%d)\n", current_fsentry->u.device.rdev, current_fsentry->u.device.rdev);
  432.                printf ("   [DEVICE] path = \"%s\"\n", (char *) &current_fsentry->u.device.path); // convert from pointer to char array
  433.             }
  434.  
  435.             if ((current_fsentry->header.size == 0) || (current_offset + current_fsentry->header.size >= file.size))
  436.             {
  437.                LOG_WARNING ("this IFS file is corrupted (the size of this directory entry is invalid)");
  438.                goto endofdata;
  439.             }
  440.  
  441.             current_offset += current_fsentry->header.size;
  442.          }
  443.          if (imageheader_offset + image_header->hdr_dir_size < current_offset + sizeof (current_fsentry->header))
  444.             hex_printf (&file.bytes[current_offset], imageheader_offset + image_header->hdr_dir_size - current_offset, "\n" "%zd padding bytes at offset 0x%zx (%zd):\n", imageheader_offset + image_header->hdr_dir_size - current_offset, current_offset, current_offset);
  445.          current_offset += imageheader_offset + image_header->hdr_dir_size - current_offset; // padding was processed, jump over it
  446.  
  447.          // at this point we are past the directory entries; what is stored now, up to and until the image trailer, is the files' data
  448.          if (fsentry_count > 0)
  449.          {
  450.             while (current_offset < imagetrailer_offset) // and parse data up to the trailer
  451.             {
  452.                nearest_distance = SIZE_MAX;
  453.                nearest_index = SIZE_MAX;
  454.                for (fsentry_index = 0; fsentry_index < fsentry_count; fsentry_index++)
  455.                   if (S_ISREG (fsentries[fsentry_index]->header.mode) // if this directory entry a file (i.e. it has a data blob)...
  456.                       && (imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset >= current_offset) // ... AND its data blob is still ahead of our current pointer ...
  457.                       && (imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset - current_offset < nearest_distance)) // ... AND it's the closest to us we've found so far
  458.                   {
  459.                      nearest_distance = imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset - current_offset; // then remember it
  460.                      nearest_index = fsentry_index;
  461.                   }
  462.                if (nearest_index == SIZE_MAX)
  463.                   break; // found no file ahead, which means we've parsed the whole file data area, so stop the loop so as to proceed to the image trailer
  464.  
  465.                fsentry_index = nearest_index;
  466.                current_fsentry = fsentries[fsentry_index]; // quick access to closest fsentry
  467.  
  468.                // there may be padding before the file data
  469.                if (imageheader_offset + (size_t) current_fsentry->u.file.offset - current_offset > 0)
  470.                   hex_printf (&file.bytes[current_offset], imageheader_offset + (size_t) current_fsentry->u.file.offset - current_offset, "\n" "%zd padding bytes at offset 0x%zx (%zd):\n", imageheader_offset + (size_t) current_fsentry->u.file.offset - current_offset, current_offset, current_offset);
  471.                current_offset += imageheader_offset + (size_t) current_fsentry->u.file.offset - current_offset; // padding was processed, jump over it
  472.  
  473.                printf ("\n");
  474.                printf ("File data blob at offset 0x%zx (%zd):\n", current_offset, current_offset);
  475.                printf ("   corresponding dirent index: %zd/%zd\n", fsentry_index, fsentry_count);
  476.                printf ("   corresponding inode 0x%08x (%d) -%s%s%s%s\n", current_fsentry->header.ino, current_fsentry->header.ino, (current_fsentry->header.ino & 0xE0000000 ? "" : " nothing special"), (current_fsentry->header.ino & IFS_INO_PROCESSED_ELF ? " PROCESSED_ELF" : ""), (current_fsentry->header.ino & IFS_INO_RUNONCE_ELF ? " RUNONCE_ELF" : ""), (current_fsentry->header.ino & IFS_INO_BOOTSTRAP_EXE ? " BOOTSTRAP_EXE" : ""));
  477.                printf ("   corresponding path: \"%s\"\n", (char *) &current_fsentry->u.file.path); // convert from pointer to char array
  478.                printf ("   size 0x%zx (%zd) bytes\n", (size_t) current_fsentry->u.file.size, (size_t) current_fsentry->u.file.size);
  479.                if (current_offset + 4 < file.size)
  480.                   hex_printf (&file.bytes[current_offset], current_fsentry->u.file.size, "   data:\n");
  481.                if (current_offset + current_fsentry->u.file.size < file.size)
  482.                   printf ("   checksum %d\n", update_checksum (&file.bytes[current_offset], current_fsentry->u.file.size, is_foreign_endianness));
  483.                else
  484.                {
  485.                   LOG_WARNING ("this IFS file is corrupted (the size of this file data extends past the IFS size)");
  486.                   goto endofdata;
  487.                }
  488.  
  489.                current_offset += current_fsentry->u.file.size; // now jump over this file's data
  490.             }
  491.          }
  492.  
  493.          // ad this point we're past the last file data, there may be padding before the image trailer
  494.          if (imagetrailer_offset - current_offset > 0)
  495.             hex_printf (&file.bytes[current_offset], imagetrailer_offset - current_offset, "\n" "%zd padding bytes at offset %zx (%zd):\n", imagetrailer_offset - current_offset, current_offset, current_offset);
  496.          current_offset += imagetrailer_offset - current_offset; // padding was processed, jump over it
  497.  
  498.          printf ("\n");
  499.          printf ("Image trailer at offset 0x%zx (%zd) - version %d:\n", current_offset, current_offset, (image_header->flags & IMAGE_FLAGS_TRAILER_V2 ? 2 : 1));
  500.          if (image_header->flags & IMAGE_FLAGS_TRAILER_V2)
  501.          {
  502.             for (byte_index = 0; byte_index < SHA512_DIGEST_LENGTH; byte_index++)
  503.                sprintf_s (&recorded_sha512[2 * byte_index], 3, "%02x", image_trailer_v2->sha512[byte_index]);
  504.             strcpy_s (computed_sha512, sizeof (computed_sha512), SHA512 (image_header, imagetrailer_offset - imageheader_offset, NULL));
  505.             recorded_checksum = image_trailer_v2->cksum;
  506.             computed_checksum = update_checksum (image_header, imagetrailer_offset + SHA512_DIGEST_LENGTH - imageheader_offset, is_foreign_endianness);
  507.             printf ("    sha512([0x%zx-0x%zx[) = %s - %s\n", imageheader_offset, imagetrailer_offset, recorded_sha512, (strcasecmp (computed_sha512, recorded_sha512) == 0 ? "GOOD" : "BAD"));
  508.             printf ("    cksum([0x%zx-0x%zx[) = 0x%08x - %s\n", imageheader_offset, imagetrailer_offset + SHA512_DIGEST_LENGTH, recorded_checksum, (computed_checksum == recorded_checksum ? "GOOD" : "BAD"));
  509.             if (strcasecmp (computed_sha512, recorded_sha512) != 0)
  510.                printf ("Computed SHA-512: %s\n", computed_sha512);
  511.             if (computed_checksum != recorded_checksum)
  512.                printf ("Computed cksum: 0x%08x\n", computed_checksum);
  513.          }
  514.          else // old v1 trailer
  515.          {
  516.             recorded_checksum = image_trailer_v1->cksum;
  517.             computed_checksum = update_checksum (image_header, image_header->image_size - sizeof (image_trailer_v1_t), is_foreign_endianness);
  518.             printf ("    cksum([0x%zx-0x%zx[) = 0x%08x - %s\n", imageheader_offset, imagetrailer_offset, recorded_checksum, (computed_checksum == recorded_checksum ? "GOOD" : "BAD"));
  519.             if (computed_checksum != recorded_checksum)
  520.                printf ("Computed cksum: 0x%08x\n", computed_checksum);
  521.          }
  522.  
  523.          current_offset += (image_header->flags & IMAGE_FLAGS_TRAILER_V2 ? sizeof (image_trailer_v2_t) : sizeof (image_trailer_v1_t)); // now reach the next segment (typically end of file)
  524.       }
  525.  
  526.       // else it has to be a boot blob, of which we don't know the size, except that it has to fit in 0xffff bytes and be immediately followed by a startup header
  527.       else
  528.       {
  529.          // so scan for the first startup header magic and version (which makes us 6 bytes to scan for, i.e. "\xeb\x7e\xff\x00" for the magic and "\x01\x00" (LSB) for the version 1)
  530.          for (byte_index = current_offset; byte_index < file.size - 6; byte_index++)
  531.             if (memcmp (&file.bytes[byte_index], "\xeb\x7e\xff\x00" "\x01\x00", 4 + 2) == 0)
  532.                break; // stop as soon as we find it
  533.  
  534.          if (byte_index >= file.size - 6)
  535.             break; // if not found, stop scanning
  536.  
  537.          bootfile_blobsize = byte_index - current_offset;
  538.          printf ("Boot blob at offset 0x%zx (%zd):\n", current_offset, current_offset);
  539.          printf ("   size 0x%zx (%zd) bytes\n", bootfile_blobsize, bootfile_blobsize);
  540.          printf ("   checksum 0x%08x\n", update_checksum (&file.bytes[current_offset], bootfile_blobsize, false)); // NOTE: endianness is not known yet -- assume same
  541.  
  542.          current_offset = byte_index; // now reach the next segment
  543.       }
  544.    }
  545.  
  546. endofdata:
  547.    // at this point there's nothing left we're able to parse
  548.    if (current_offset < file.size)
  549.    {
  550.       printf ("End of identifiable data reached.\n");
  551.       hex_printf (&file.bytes[current_offset], file.size - current_offset, "\n" "%zd extra bytes at offset %zx (%zd):\n", file.size - current_offset, current_offset, current_offset);
  552.    }
  553.  
  554.    printf ("End of file reached at offset 0x%zx (%zd)\n", file.size, file.size);
  555.    printf ("IFS dissecation complete.\n");
  556.    return (0);
  557. }
  558.  
  559.  
  560. int dump_ifs_contents (const char *ifs_pathname, const char *outdir)
  561. {
  562.    static char outfile_pathname[MAXPATHLEN] = "";
  563.  
  564.    startup_header_t *startup_header = NULL;
  565.    size_t startupheader_offset = 0;
  566.    image_header_t *image_header = NULL;
  567.    size_t imageheader_offset = 0;
  568.    size_t imagetrailer_offset = 0;
  569.    fsentry_t **fsentries = NULL; // mallocated
  570.    size_t fsentry_count = 0;
  571.    fsentry_t *current_fsentry = NULL;
  572.    size_t startupfile_blobsize = 0;
  573.    struct utimbuf file_times = { 0, 0 };
  574.    void *reallocated_ptr;
  575.    size_t bootfile_blobsize = 0;
  576.    size_t current_offset;
  577.    size_t fsentry_index;
  578.    size_t nearest_distance;
  579.    size_t nearest_index;
  580.    size_t byte_index;
  581.    buffer_t file;
  582.    FILE *fp;
  583.  
  584.    // open and read IFS file
  585.    if (!Buffer_ReadFromFile (&file, ifs_pathname))
  586.       DIE_WITH_EXITCODE (1, "can't open \"%s\" for reading: %s\n", ifs_pathname, strerror (errno));
  587.  
  588.    // create the output directory
  589.    create_intermediate_dirs (outdir);
  590.    (void) mkdir (outdir, 0755);
  591.  
  592.    // parse file from start to end
  593.    current_offset = 0;
  594.    for (;;)
  595.    {
  596.       // does a startup header start here ?
  597.       if ((current_offset + sizeof (startup_header_t) < file.size) && (memcmp (&file.bytes[current_offset], "\xeb\x7e\xff\x00", 4) == 0))
  598.       {
  599.          startupheader_offset = current_offset;
  600.          startup_header = (startup_header_t *) &file.bytes[startupheader_offset];
  601.  
  602.          // layout:
  603.          // [STARTUP HEADER]
  604.          // (startup file blob)
  605.          // [STARTUP TRAILER v1 or v2]
  606.  
  607.          // validate that the file can contain up to the startup trailer
  608.          if (current_offset + startup_header->startup_size > file.size)
  609.          {
  610.             LOG_WARNING ("this IFS file is corrupted (startup trailer extends past end of file)");
  611.             goto endofdata;
  612.          }
  613.  
  614.          // locate the right startup trailer at the right offset
  615.          if (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2)
  616.             startupfile_blobsize = startup_header->startup_size - sizeof (startup_header_t) - sizeof (startup_trailer_v2_t);
  617.          else // old V1 trailer
  618.             startupfile_blobsize = startup_header->startup_size - sizeof (startup_header_t) - sizeof (startup_trailer_v1_t);
  619.  
  620.          current_offset += sizeof (startup_header_t); // jump over the startup header and reach the startup blob
  621.  
  622.          // write startup blob
  623.          sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/startup.bin", outdir);
  624.          fopen_s (&fp, outfile_pathname, "wb");
  625.          ASSERT (fp, "failed to open '%s': %s", outfile_pathname, strerror (errno));
  626.          fwrite (&file.bytes[current_offset], 1, startupfile_blobsize, fp);
  627.          fclose (fp);
  628.  
  629.          current_offset += startupfile_blobsize; // jump over the startup blob and reach the startup trailer
  630.          current_offset += (startup_header->flags1 & STARTUP_HDR_FLAGS1_TRAILER_V2 ? sizeof (startup_trailer_v2_t) : sizeof (startup_trailer_v1_t)); // jump over the startup trailer and reach the next segment
  631.       }
  632.  
  633.       // else does an image header start here ?
  634.       else if ((current_offset + sizeof (image_header_t) < file.size) && (memcmp (&file.bytes[current_offset], "imagefs", 7) == 0))
  635.       {
  636.          imageheader_offset = current_offset;
  637.          image_header = (image_header_t *) &file.bytes[imageheader_offset];
  638.  
  639.          // layout:
  640.          // [IMAGE HEADER]
  641.          // [image directory entries]
  642.          // [smallest file blobs up to KERNEL]
  643.          // [padding]
  644.          // [KERNEL]
  645.          // [rest of file blobs]
  646.          // [IMAGE FOOTER]
  647.  
  648.          // validate that the file can contain up to the image trailer
  649.          if (current_offset + image_header->image_size > file.size)
  650.          {
  651.             LOG_WARNING ("this IFS file is corrupted (image trailer extends past end of file)");
  652.             goto endofdata;
  653.          }
  654.  
  655.          // locate the image trailer at the right offset
  656.          if (image_header->flags & IMAGE_FLAGS_TRAILER_V2)
  657.             imagetrailer_offset = current_offset + image_header->image_size - sizeof (image_trailer_v2_t);
  658.          else // old V1 trailer
  659.             imagetrailer_offset = current_offset + image_header->image_size - sizeof (image_trailer_v1_t);
  660.  
  661.          current_offset += sizeof (image_header_t); // jump over the image header
  662.          current_offset += image_header->dir_offset - sizeof (image_header_t); // jump over possible padding
  663.  
  664.          // dump all directory entries until the last one included
  665.          fsentries = NULL;
  666.          fsentry_count = 0;
  667.          while (current_offset < imageheader_offset + image_header->hdr_dir_size)
  668.          {
  669.             current_fsentry = (fsentry_t *) &file.bytes[current_offset];
  670.  
  671.             if (imageheader_offset + image_header->hdr_dir_size - current_offset < sizeof (current_fsentry->header))
  672.                break; // end padding reached
  673.  
  674.             // stack up the filesystem entry pointers in an array while we read them
  675.             reallocated_ptr = realloc (fsentries, (fsentry_count + 1) * sizeof (fsentry_t *));
  676.             ASSERT_WITH_ERRNO (reallocated_ptr);
  677.             fsentries = reallocated_ptr;
  678.             fsentries[fsentry_count] = current_fsentry;
  679.             fsentry_count++;
  680.  
  681.             if ((current_fsentry->header.size == 0) || (current_offset + current_fsentry->header.size >= file.size))
  682.             {
  683.                LOG_WARNING ("this IFS file is corrupted (the size of this directory entry is invalid)");
  684.                goto endofdata;
  685.             }
  686.  
  687.             current_offset += current_fsentry->header.size;
  688.          }
  689.          current_offset += imageheader_offset + image_header->hdr_dir_size - current_offset; // jump over possible padding
  690.  
  691.          // at this point we are past the directory entries; what is stored now, up to and until the image trailer, is the files' data
  692.          if (fsentry_count > 0)
  693.          {
  694.             while (current_offset < imagetrailer_offset) // and parse data up to the trailer
  695.             {
  696.                nearest_distance = SIZE_MAX;
  697.                nearest_index = SIZE_MAX;
  698.                for (fsentry_index = 0; fsentry_index < fsentry_count; fsentry_index++)
  699.                   if (S_ISREG (fsentries[fsentry_index]->header.mode) // if this directory entry a file (i.e. it has a data blob)...
  700.                       && (imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset >= current_offset) // ... AND its data blob is still ahead of our current pointer ...
  701.                       && (imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset - current_offset < nearest_distance)) // ... AND it's the closest to us we've found so far
  702.                   {
  703.                      nearest_distance = imageheader_offset + (size_t) fsentries[fsentry_index]->u.file.offset - current_offset; // then remember it
  704.                      nearest_index = fsentry_index;
  705.                   }
  706.                if (nearest_index == SIZE_MAX)
  707.                   break; // found no file ahead, which means we've parsed the whole file data area, so stop the loop so as to proceed to the image trailer
  708.  
  709.                fsentry_index = nearest_index;
  710.                current_fsentry = fsentries[fsentry_index]; // quick access to closest fsentry
  711.  
  712.                current_offset += imageheader_offset + (size_t) current_fsentry->u.file.offset - current_offset; // jump over possible padding
  713.  
  714.                if (current_offset + current_fsentry->u.file.size >= file.size)
  715.                {
  716.                   LOG_WARNING ("this IFS file is corrupted (the size of this file data extends past the IFS size)");
  717.                   goto endofdata;
  718.                }
  719.  
  720.                // write filesystem data entry
  721.                if (S_ISDIR (current_fsentry->header.mode))
  722.                {
  723.                   sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/%s", outdir, (char *) &current_fsentry->u.dir.path); // convert from pointer to char array
  724.                   create_intermediate_dirs (outfile_pathname);
  725.                   (void) mkdir (outfile_pathname, current_fsentry->header.mode & 0777);
  726.                }
  727.                else if (S_ISLNK (current_fsentry->header.mode))
  728.                {
  729.                   sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/%s", outdir, (char *) &current_fsentry->u.symlink.path); // convert from pointer to char array
  730.                   create_intermediate_dirs (outfile_pathname);
  731. #ifdef _WIN32
  732.                   fopen_s (&fp, outfile_pathname, "wb"); // on Windows create symlinks as plain files
  733.                   ASSERT (fp, "failed to open '%s': %s", outfile_pathname, strerror (errno));
  734.                   fwrite ((char *) &current_fsentry->u.symlink.path + current_fsentry->u.symlink.sym_offset, 1, current_fsentry->u.symlink.sym_size, fp); // convert from pointer to char array
  735.                   fclose (fp);
  736. #else // !_WIN32, thus POSIX
  737.                   symlink (current_fsentry->u.symlink.contents, outfile_pathname); // on UNIX systems, just create the symlink for real
  738. #endif // _WIN32
  739.                }
  740.                else if (S_ISREG (current_fsentry->header.mode))
  741.                {
  742.                   sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/%s", outdir, (char *) &current_fsentry->u.file.path); // convert from pointer to char array
  743.                   create_intermediate_dirs (outfile_pathname);
  744.                   fopen_s (&fp, outfile_pathname, "wb"); // on Windows create symlinks as plain files
  745.                   ASSERT (fp, "failed to open '%s': %s", outfile_pathname, strerror (errno));
  746.                   fwrite (&file.bytes[current_offset], 1, current_fsentry->u.file.size, fp);
  747.                   fclose (fp);
  748.                }
  749.                else // must be a device node. Since we might not be the super-user and/or on Win32, create plain file with "X:Y" as data
  750.                {
  751.                   sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/%s", outdir, (char *) &current_fsentry->u.device.path); // convert from pointer to char array
  752.                   create_intermediate_dirs (outfile_pathname);
  753.                   fopen_s (&fp, outfile_pathname, "wb"); // on Windows create symlinks as plain files
  754.                   ASSERT (fp, "failed to open '%s': %s", outfile_pathname, strerror (errno));
  755.                   fprintf (fp, "%u:%u", current_fsentry->u.device.dev, current_fsentry->u.device.rdev);
  756.                   fclose (fp);
  757.                }
  758.  
  759.                // set created file mtime
  760.                file_times.actime = current_fsentry->header.mtime;
  761.                file_times.modtime = current_fsentry->header.mtime;
  762.                utime (outfile_pathname, &file_times);
  763.  
  764.                // set created file mode
  765. #ifndef _WIN32
  766.                (void) chmod (outfile_pathname, current_fsentry->header.mode & 0777); // only on POSIX systems
  767. #endif // !_WIN32
  768.  
  769.                current_offset += current_fsentry->u.file.size; // now jump over this file's data
  770.             }
  771.          }
  772.  
  773.          // ad this point we're past the last file data, there may be padding before the image trailer
  774.          current_offset += imagetrailer_offset - current_offset; // jump over possible padding and reach the image trailer
  775.          current_offset += (image_header->flags & IMAGE_FLAGS_TRAILER_V2 ? sizeof (image_trailer_v2_t) : sizeof (image_trailer_v1_t)); // now jump over the image trailer and reach the next segment (typically end of file)
  776.       }
  777.  
  778.       // else it has to be a boot blob, of which we don't know the size, except that it has to fit in 0xffff bytes and be immediately followed by a startup header
  779.       else
  780.       {
  781.          // so scan for the first startup header magic and version (which makes us 6 bytes to scan for, i.e. "\xeb\x7e\xff\x00" for the magic and "\x01\x00" (LSB) for the version 1)
  782.          for (byte_index = current_offset; byte_index < file.size - 6; byte_index++)
  783.             if (memcmp (&file.bytes[byte_index], "\xeb\x7e\xff\x00" "\x01\x00", 4 + 2) == 0)
  784.                break; // stop as soon as we find it
  785.  
  786.          if (byte_index >= file.size - 6)
  787.             break; // if not found, stop scanning
  788.  
  789.          bootfile_blobsize = byte_index - current_offset;
  790.  
  791.          // write boot blob
  792.          sprintf_s (outfile_pathname, sizeof (outfile_pathname), "%s/boot.bin", outdir);
  793.          fopen_s (&fp, outfile_pathname, "wb");
  794.          ASSERT (fp, "failed to open '%s': %s", outfile_pathname, strerror (errno));
  795.          fwrite (&file.bytes[current_offset], 1, bootfile_blobsize, fp);
  796.          fclose (fp);
  797.  
  798.          current_offset = byte_index; // now reach the next segment
  799.       }
  800.    }
  801.  
  802. endofdata:
  803.    return (0);
  804. }
  805.  
  806.  
  807. int dump_file_hex (const char *pathname)
  808. {
  809.    buffer_t file;
  810.  
  811.    ASSERT_WITH_ERRNO (Buffer_ReadFromFile (&file, pathname));
  812.    hex_fprintf (stdout, file.bytes, file.size, 16, "%s (%zd bytes):\n", pathname, file.size);
  813.    return (0);
  814. }
  815.