1 // SPDX-License-Identifier: BSD-3-Clause
2 //
3 // Copyright(c) 2020 Intel Corporation. All rights reserved.
4 //
5 // Author: Karol Trzcinski <karolx.trzcinski@linux.intel.com>
6 
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <string.h>
12 
13 #include "elf.h"
14 #include "ldc.h"
15 #include "smex.h"
16 
usage(char * name)17 static void usage(char *name)
18 {
19 	fprintf(stdout, "%s:\t in_file\n", name);
20 	fprintf(stdout, "\t -l log dictionary outfile\n");
21 	fprintf(stdout, "\t -v enable verbose output\n");
22 	fprintf(stdout, "\t -h this help message\n");
23 	exit(1);
24 }
25 
main(int argc,char * argv[])26 int main(int argc, char *argv[])
27 {
28 	struct image image;
29 	int opt, ret;
30 
31 	memset(&image, 0, sizeof(image));
32 
33 	while ((opt = getopt(argc, argv, "hl:v")) != -1) {
34 		switch (opt) {
35 		case 'l':
36 			image.ldc_out_file = optarg;
37 			break;
38 		case 'v':
39 			image.verbose = true;
40 			break;
41 		case 'h':
42 			usage(argv[0]);
43 			break;
44 		default:
45 			break;
46 		}
47 	}
48 
49 	/* make sure we have an outfile */
50 	if (!image.ldc_out_file)
51 		image.ldc_out_file = "out.ldc";
52 
53 	/* make sure we have an input ELF file */
54 	if (argc - optind != 1) {
55 		usage(argv[0]);
56 		return -EINVAL;
57 	}
58 
59 	/* read source elf file */
60 	ret = elf_read_module(&image.module, argv[optind], image.verbose);
61 	if (ret < 0)
62 		goto out;
63 
64 	/* open outfile for writing */
65 	unlink(image.ldc_out_file);
66 	image.ldc_out_fd = fopen(image.ldc_out_file, "wb");
67 	if (!image.ldc_out_fd) {
68 		fprintf(stderr, "error: unable to open %s for writing %d\n",
69 			image.ldc_out_file, errno);
70 		ret = -EINVAL;
71 		goto out;
72 	}
73 
74 	/* write dictionaries */
75 	ret = write_dictionaries(&image, &image.module);
76 	if (ret) {
77 		fprintf(stderr, "error: unable to write dictionaries, %d\n",
78 			ret);
79 		/* Don't corrupt the build with an empty or incomplete output */
80 		unlink(image.ldc_out_file);
81 		goto out;
82 	}
83 
84 out:
85 	/* close files */
86 	if (image.ldc_out_fd)
87 		fclose(image.ldc_out_fd);
88 
89 	elf_free_module(&image.module);
90 
91 	return ret;
92 }
93