00001
00002
00003
00004
00005
00006
00007
00008
00009 #include <stdlib.h>
00010 #include <stdio.h>
00011 #include <errno.h>
00012 #include <a.out.h>
00013 #include <sys/types.h>
00014 #include <fcntl.h>
00015 #include <sys/stat.h>
00016 #include <string.h>
00017 #include <unistd.h>
00018
00019 #define INPUT_FILE 1
00020 #define OUTPUT_FILE 2
00021
00022
00023 void report(char *problem, char *message)
00024 {
00025 fprintf(stderr, "%s:\n", problem);
00026 fprintf(stderr, " %s\n\n", message);
00027 }
00028
00029
00030 int copy_data(int srcfd, int dstfd)
00031 {
00032 char buf[8192];
00033 ssize_t n;
00034 int total=0;
00035
00036
00037 while ((n= read(srcfd, buf, sizeof(buf))) > 0) {
00038 char *bp = buf;
00039 ssize_t r;
00040
00041 while (n > 0 && (r= write(dstfd, bp, n)) > 0) {
00042 bp += r;
00043 n -= r;
00044 total += r;
00045 }
00046 if (r <= 0) {
00047 if (r == 0) {
00048 fprintf(stderr, "Warning: EOF writing to output file.\n");
00049 return(-1);
00050 }
00051 }
00052 }
00053 return(total);
00054 }
00055
00056
00057
00058 int main(int argc, char **argv)
00059 {
00060 struct exec aout;
00061 struct stat stin;
00062 int fdin, fdout;
00063 char * bp;
00064 int n,r;
00065 int total_size=0;
00066 int result;
00067
00068
00069 if (argc!=3) {
00070 printf("Invalid arguments. Usage:\n");
00071 printf(" %s <input_file> <output_file>\n",argv[0]);
00072 return(1);
00073 }
00074
00075
00076 if (stat(argv[INPUT_FILE], &stin) != 0) {
00077 report("Couldn't get status of input file", strerror(errno));
00078 return(1);
00079 }
00080 if ((fdin = open(argv[INPUT_FILE], O_RDONLY)) < 0) {
00081 report("Couldn't open input file", strerror(errno));
00082 return(1);
00083 }
00084 if ((fdout = open(argv[OUTPUT_FILE], O_WRONLY|O_CREAT|O_TRUNC,
00085 stin.st_mode & 0777)) < 0) {
00086 report("Couldn't open output file", strerror(errno));
00087 return(1);
00088 }
00089
00090
00091
00092 lseek(fdout, sizeof(aout), SEEK_SET);
00093 total_size = copy_data(fdin, fdout);
00094 if (total_size < 0) {
00095 report("Aborted", "Output file may be truncated.");
00096 return(1);
00097 } else if (total_size == 0) {
00098 report("Aborted without prepending header", "No data in input file.");
00099 return(1);
00100 }
00101
00102
00103
00104 memset(&aout, 0, sizeof(struct exec));
00105 aout.a_magic[0] = A_MAGIC0;
00106 aout.a_magic[1] = A_MAGIC1;
00107 aout.a_flags |= A_IMG;
00108 aout.a_hdrlen = sizeof(aout);
00109 aout.a_text = 0;
00110 aout.a_data = total_size;
00111 aout.a_bss = 0;
00112 aout.a_total = aout.a_hdrlen + aout.a_data;
00113
00114 bp = (char *) &aout;
00115 n = sizeof(aout);
00116 lseek(fdout, 0, SEEK_SET);
00117 while (n > 0 && (r= write(fdout, bp, n)) > 0) {
00118 bp += r;
00119 n -= r;
00120 }
00121
00122 printf("Prepended data file (%u bytes) with a.out header (%u bytes).\n",
00123 total_size, sizeof(aout));
00124 printf("Done.\n");
00125
00126 return(0);
00127 }
00128