scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | README | LICENSE

strip.c (1403B)


      1 #include <errno.h>
      2 #include <stdarg.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <string.h>
      6 
      7 #include <scc/arg.h>
      8 #include <scc/mach.h>
      9 
     10 static int status;
     11 static char *filename;
     12 char *argv0;
     13 
     14 static void
     15 error(char *fmt, ...)
     16 {
     17 	va_list va;
     18 
     19 	va_start(va, fmt);
     20 	fprintf(stderr, "strip: %s: ", filename);
     21 	vfprintf(stderr, fmt, va);
     22 	putc('\n', stderr);
     23 	va_end(va);
     24 
     25 	status = EXIT_FAILURE;
     26 }
     27 
     28 static void
     29 strip(char *fname)
     30 {
     31 	int type;
     32 	FILE *fp;
     33 	Obj *obj;
     34 
     35 	errno = 0;
     36 	filename = fname;
     37 
     38 	if ((fp = fopen(fname, "rb")) == NULL)
     39 		goto err1;
     40 
     41 	if ((type = objtype(fp, NULL)) < 0) {
     42 		error("file format not recognized");
     43 		goto err2;
     44 	}
     45 	if ((obj = objnew(type)) == NULL) {
     46 		error("out of memory");
     47 		goto err3;
     48 	}
     49 	if (objread(obj, fp) < 0) {
     50 		error("file corrupted");
     51 		goto err3;
     52 	}
     53 	fclose(fp);
     54 	fp = NULL;
     55 
     56 	objstrip(obj);
     57 
     58 	if ((fp = fopen(fname, "wb")) == NULL)
     59 		goto err1;
     60 
     61 	if (objwrite(obj, fp) < 0) {
     62 		error("error writing output");
     63 		goto err3;
     64 	}
     65 
     66 	fclose(fp);
     67 	objdel(obj);
     68 
     69 	return;
     70 
     71 err3:
     72 	objdel(obj);
     73 err2:
     74 	if (fp)
     75 		fclose(fp);
     76 err1:
     77 	if (errno)
     78 		error(strerror(errno));
     79 
     80 	return;
     81 }
     82 
     83 static void
     84 usage(void)
     85 {
     86 	fputs("usage: strip [file...]\n", stderr);
     87 	exit(EXIT_FAILURE);
     88 }
     89 
     90 int
     91 main(int argc, char *argv[])
     92 {
     93 	ARGBEGIN {
     94 	default:
     95 		usage();
     96 	} ARGEND
     97 
     98 	if (argc == 0) {
     99 		strip("a.out");
    100 	} else {
    101 		for (; *argv; ++argv)
    102 			strip(*argv);
    103 	}
    104 
    105 	return status;
    106 }