home *** CD-ROM | disk | FTP | other *** search
/ Doom Fever / Doom_Fever-1995_Maple_Media.iso / dmutil / drivers.zip / EXE2COM.C < prev    next >
C/C++ Source or Header  |  1988-03-08  |  12KB  |  402 lines

  1. /*
  2.     exe2com - exe2bin replacement by Chris Dunford/Cove Software
  3.  
  4.     usage: exe2com [/I] infile [outfile]
  5.  
  6.     usage is the same as exe2bin except:
  7.         1. Output defaults to COM rather than BIN
  8.         2. Binary fixup option not supported
  9.         3. Checksum not verified
  10.         4. Provides more useful error messages and a warning if a
  11.            COM file is being created with initial IP != 0x100
  12.         5. /I switch provides EXE file info instead of converting
  13.  
  14.     Compiler notes:
  15.         This source was written for Microsoft C version 5.0.  It
  16.         should be reasonably portable.  Watch out for fseek();
  17.         what it returns seems to vary widely between compilers.
  18.  
  19.         To compile with MSC, use:
  20.  
  21.             cl exe2com.c  (no switches necessary)
  22.  
  23.         We have checked that the source (as of version 1.04) compiles
  24.         without error under Turbo C 1.5.  It appears to operate correctly,
  25.         but we ran only some quick tests; there may be subtle errors here.
  26.  
  27.     The original version of this program was knocked together in about
  28.     an hour in response to the removal of EXE2BIN from the standard DOS
  29.     distribution disks.  Improvements/corrections are encouraged, but
  30.     please try to coordinate public releases through me.
  31.  
  32.     Program donated to the public domain by the author.
  33.  
  34.     cjd 4/17/87
  35.  
  36.  
  37.     Version history
  38.     ---------------
  39.     Version 1.04 03/02/88 (CJD)
  40.         Cleaned up some ugly code from the original quickie. Added
  41.         /I (info) switch.  In previous versions, we defined an
  42.         error code for nonzero CS but didn't actually check it; now
  43.         we do.  Source will now compile under either Microsoft C or
  44.         Turbo C.
  45.  
  46.     Version 1.03 12/30/87 (CJD)
  47.         C86 version converted to Microsoft C (5.0) by Chris
  48.         Dunford.  Increased size of I/O buffer to 4K to improve
  49.         speed; EXE2COM 1.03 is twice as fast as 1.02 and is now
  50.         slightly faster than EXE2BIN.  The C86 version will no
  51.         longer be distributed.
  52.  
  53.     Version 1.02 11/22/87
  54.     by Chris Blum (CompuServe 76625,1041)
  55.         Fix for even 512-byte boundary file losing last 512 bytes.
  56.         Also corrected signon per request of Chris Dunford (his name
  57.         was lost in the translation to Turbo C).  Version 1.02
  58.         existed in both Turbo C and C86 versions, although only
  59.         the C86 executable was "officially" distributed.
  60.  
  61.     Version 1.01 was a Turbo C conversion.
  62.  
  63.     Version 1.00 04/17/87
  64.         Original C86 version by Chris Dunford
  65.  
  66. */
  67.  
  68. #include <stdio.h>
  69. #include <string.h>
  70. #include <ctype.h>
  71.  
  72. /* Version coding */
  73. #define MAJVER   1
  74. #define MINVER   0
  75. #define REVISION 4
  76.  
  77. /* Conversion error codes */
  78. #define BADREAD  0
  79. #define BADWRITE 1
  80. #define BADSIG   2
  81. #define HASRELO  3
  82. #define HAS_SS   4
  83. #define HAS_CS   5
  84. #define BAD_IP   6
  85. #define TOO_BIG  7
  86. /* This must be the last code */
  87. #define UNKNOWN  8
  88.  
  89. /* Define size of console output buffer */
  90. #define CONBUFSIZ 2048
  91.  
  92. /*
  93. **  Define structure of fixed-format part of EXE file header
  94. */
  95. struct exe_header {
  96.         char exe_sig[2];    /* EXE file signature: "MZ" */
  97.     unsigned excess,        /* Image size mod 512 (valid bytes in last page) */
  98.              pages,         /* # 512-byte pages in image */
  99.              relo_ct,       /* Count of relocation table entries */
  100.              hdr_size,      /* Size of header, in paragraphs */
  101.              min_mem,       /* Min required memory */
  102.              max_mem,       /* Max required memory */
  103.              ss,            /* Stack seg offset in load module */
  104.              sp,            /* Initial value of SP */
  105.              cksum,         /* File checksum */
  106.              ip,            /* Initial value of IP */
  107.              cs,            /* CS offset in load module */
  108.              relo_start,    /* Offset of first relo item */
  109.              ovl_num;       /* Overlay number */
  110. } xh;
  111.  
  112. FILE *fi,                   /* Input file stream */
  113.      *fo;                   /* Output file stream */
  114.  
  115. char fin[129],              /* Input file name */
  116.      fon[129];              /* Output file name */
  117.  
  118. int  info=0;                /* Nonzero if /I found */
  119.  
  120. char buf[CONBUFSIZ];        /* printf I/O buffer */
  121.  
  122. char defext[] = ".com";     /* Default output extension - change if you want */
  123.  
  124. unsigned long code_start,   /* Offset of program image in EXE file */
  125.               code_size;    /* Size of program image, in bytes */
  126.  
  127. /* Function prototypes */
  128. void init (unsigned, char *[]);
  129. void read_hdr (void);
  130. void disp_info (void);
  131. void convert (void);
  132. void err_xit (unsigned);
  133. void usage (void);
  134.  
  135. /*
  136. **  program mainline
  137. */
  138. main(argc, argv)
  139. unsigned argc;
  140. char *argv[];
  141. {
  142.     init (argc, argv);
  143.     read_hdr ();
  144.     if (info)
  145.         disp_info ();
  146.     else
  147.         convert ();
  148. }
  149.  
  150.  
  151. /*
  152. **  Initialize - parse arguments, get filenames, open/create files
  153. */
  154. void init (argc, argv)
  155. unsigned argc;
  156. char **argv;
  157. {
  158. char c, *cp;
  159. int i;
  160.  
  161.     /* Set up buffered output, display logo */
  162.     setvbuf (stdout, buf, _IOFBF, CONBUFSIZ);
  163.     printf ("exe2com %u.%u%u by Chris Dunford/The Cove Software Group\n",
  164.              MAJVER, MINVER, REVISION);
  165.  
  166.     /* Get arguments */
  167.     cp = *(++argv);
  168.     for (i=1; i < argc; i++) {
  169.         while ( (cp = strchr (cp, '/')) != (char *) NULL) {
  170.             *cp++ = '\0';
  171.             c = *cp++;
  172.             switch (toupper (c)) {
  173.                 case 'I':
  174.                     info = 1;
  175.                     break;
  176.                 default:
  177.                     usage ();
  178.             }
  179.         }
  180.  
  181.         if (**argv)
  182.             if (fin[0] == '\0')
  183.                 strcpy (fin, strlwr (*argv));
  184.             else if (fon[0] == '\0')
  185.                 strcpy (fon, strlwr (*argv));
  186.             else
  187.                 usage ();
  188.  
  189.         cp = *(++argv);
  190.     }
  191.  
  192.     /* Check to ensure that an input filename was found *.
  193.     if (fin[0] == '\0') usage ();
  194.  
  195.     /* If the input file has no extension, add .EXE */
  196.     if (strchr (fin, '.') == (char *) NULL)
  197.         strcat (fin, ".exe");
  198.  
  199.     /* Copy input name to output if unspecified */
  200.     if (fon[0] == '\0')
  201.         strcpy (fon, fin);
  202.  
  203.     /* Check output extension--change EXE to COM, or add COM */
  204.     if ((cp = strchr (fon, '.')) == (char *) NULL)
  205.         strcat (fon, defext);
  206.     else if (strcmp (cp, ".exe") == 0)
  207.         strcpy (cp, defext);
  208.  
  209.     /* Try to open input file */
  210.     if ((fi = fopen (fin, "rb")) == (FILE *) NULL) {
  211.         fprintf (stderr, "exe2com: can't find input file %s\n", fin);
  212.         exit (1);
  213.     }
  214.  
  215.     /* Try to create output file, if INFO not requested */
  216.     if (!info)
  217.         if ((fo = fopen (fon, "wb")) == (FILE *) NULL) {
  218.             fprintf (stderr, "exe2com: can't open output file %s\n", fin);
  219.             exit (1);
  220.         }
  221. }
  222.  
  223.  
  224. /*
  225. **  usage display
  226. */
  227. void usage (void)
  228. {
  229.     fprintf (stderr, "usage: exe2com [/I] infile [outfile]\n");
  230.     exit (1);
  231. }
  232.  
  233.  
  234. /*
  235. **  Read and check the EXE file header
  236. */
  237. void read_hdr(void)
  238. {
  239. char *cp;
  240.  
  241.     /* Read the formatted portion of the header */
  242.     if (!fread (&xh, sizeof (struct exe_header), 1, fi))
  243.         err_xit (BADREAD);
  244.  
  245.     /* Check for "MZ" signature */
  246.     if (strncmp (xh.exe_sig, "MZ", 2))
  247.         err_xit (BADSIG);
  248.  
  249.     /* Compute offset of program image in module, and program size.
  250.     **
  251.     ** The program size is computed as follows; it cannot exceed 64K bytes:
  252.     **     512 * (# EXE pages - 1)
  253.     **   + valid bytes in last EXE page
  254.     **   - offset of program image in EXE file
  255.     **
  256.     ** Note that if the IP is nonzero, we will skip the first
  257.     ** IP bytes of the program image, and copy IP bytes fewer
  258.     ** than the actual size.
  259.     */
  260.     code_start = ((unsigned long) xh.hdr_size) << 4;
  261.     code_size = (unsigned long) (xh.pages-1) * 512
  262.         + (xh.excess ? xh.excess : 512)    /* fixed 11/19/87 - CJB */
  263.         - code_start;
  264.  
  265.     /* Don't check anything else if /I requested */
  266.     if (info) return;
  267.  
  268.     /* Check header; to be convertible, must have:
  269.     **      -- no relocatable items
  270.     **      -- no stack segment
  271.     **      -- no code segment
  272.     **      -- IP == 0 or 100
  273.     **      -- code size < 65536
  274.     */
  275.     if (xh.relo_ct)
  276.         err_xit (HASRELO);
  277.     if (xh.ss || xh.sp)
  278.         err_xit (HAS_SS);
  279.     if (xh.cs)
  280.         err_xit (HAS_CS);
  281.     if (xh.ip != 0 && xh.ip != 0x100)
  282.         err_xit (BAD_IP);
  283.     if (code_size > 65536L)
  284.         err_xit (TOO_BIG);
  285.  
  286.     /* Issue a warning if COM file and IP != 0x100 */
  287.     if (!strcmp (strchr (fon, '.'), ".com") && xh.ip != 0x100)
  288.         fprintf (stderr, "exe2com warning: COM file, initial IP not 100H\n");
  289.  
  290. }
  291.  
  292.  
  293. /*
  294. **  /i output: display EXE file info
  295. */
  296. void disp_info (void)
  297. {
  298. char *cp;
  299. unsigned long k;
  300.  
  301.     cp = strrchr (fin, '\\');
  302.     if (!cp) cp = strchr (fin, ':');
  303.     cp = cp ? cp++ : fin;
  304.     printf ("\n%-20s          (hex)      (dec)\n",cp);
  305.  
  306.     k = (unsigned long) (xh.pages-1) * 512 + (xh.excess ? xh.excess : 512);
  307.     printf ("  EXE file size               %5lX    %7lu\n", k, k);
  308.  
  309.     printf ("  EXE header size (para)       %4X    %7u\n", xh.hdr_size, xh.hdr_size);
  310.  
  311.     putchar (code_size > 65536L ? '*' : ' ');
  312.     printf (" Program image size (bytes)  %5lX    %7lu\n", code_size, code_size);
  313.  
  314.     k = (unsigned long) xh.min_mem * 16 + code_size;
  315.     printf ("  Minimum load size (bytes)   %5lX    %7lu\n", k, k);
  316.  
  317.     printf ("  Min allocation (para)        %4X    %7u\n", xh.min_mem, xh.min_mem);
  318.  
  319.     printf ("  Max allocation (para)        %4X    %7u\n", xh.max_mem, xh.max_mem);
  320.  
  321.     putchar (xh.cs || (xh.ip != 0x100) ? '*' : ' ');
  322.     printf (" Initial CS:IP           %04X:%04X\n", xh.cs, xh.ip);
  323.  
  324.     putchar (xh.ss || xh.sp ? '*' : ' ');
  325.     printf (" Initial SS:SP           %04X:%04X    %7u (stack size)\n", xh.ss, xh.sp, xh.sp);
  326.  
  327.     putchar (xh.relo_ct ? '*' : ' ');
  328.     printf (" Relocation count             %4X    %7u\n", xh.relo_ct, xh.relo_ct);
  329.  
  330.     printf ("  Relo table start             %04X    %7u\n", xh.relo_start, xh.relo_start);
  331.  
  332.     printf ("  EXE file checksum            %04X    %7u\n", xh.cksum, xh.cksum);
  333.  
  334.     printf ("  Overlay number               %4X    %7u\n", xh.ovl_num, xh.ovl_num);
  335.  
  336.     printf ("* = this item prevents conversion to BIN/COM\n");
  337. }
  338.  
  339. /*
  340. **  Convert the file.  Nothing to do, really, other than
  341. **  reading the image (which follows the header), and
  342. **  dumping it back out to disk.
  343. */
  344. void convert (void)
  345. {
  346. #define BUFSIZE 16384
  347. static char buffer[BUFSIZE];  /* Forces buffer out of program stack */
  348. unsigned bsize;
  349.  
  350.     /* Seek to start of program image, skipping IP bytes */
  351.     if (fseek (fi, code_start+xh.ip, 0))
  352.         err_xit (BADREAD);
  353.  
  354.     /* Read blocks and copy to output */
  355.     for (code_size -= xh.ip; code_size; code_size -= bsize) {
  356.  
  357.         /* Set count of bytes to read/write */
  358.         bsize = code_size > BUFSIZE ? BUFSIZE : code_size;
  359.  
  360.         /* Read and write block */
  361.         if (!fread (buffer, bsize, 1, fi))
  362.             err_xit (BADREAD);
  363.         if (!fwrite (buffer, bsize, 1, fo))
  364.             err_xit (BADWRITE);
  365.     }
  366.  
  367.     /* All done, close the two files */
  368.     fclose (fi);
  369.     fclose (fo);
  370. }
  371.  
  372.  
  373. /*
  374. **  Display an error message, delete output file, exit.
  375. */
  376. void err_xit (code)
  377. unsigned code;
  378. {
  379. static char *msg[UNKNOWN+1] = {
  380.         "error reading EXE header",
  381.         "error writing output file",
  382.         "invalid EXE file signature",
  383.         "EXE has relocatable items",
  384.         "EXE has stack segment",
  385.         "EXE has nonzero CS",
  386.         "IP not 0 or 100H",
  387.         "program exceeds 64K",
  388.         "unknown internal error"
  389. };
  390.  
  391.     if (code > UNKNOWN) code = UNKNOWN;
  392.     fprintf (stderr, "exe2com: %s, can't convert\n", msg[code]);
  393.  
  394.     /* Close two files and delete partial output */
  395.     fclose (fi);
  396.     fclose (fo);
  397.     unlink (fon);
  398.  
  399.     /* Exit with errorlevel 1 */
  400.     exit (1);
  401. }
  402.