xref: /aosp_15_r20/tools/security/fuzzing/orphans/libufdt/mkcorpus.c (revision d9ecfb0f4d734c9ce41cde8ac4d585b094fd4222)
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <arpa/inet.h>
18 #include <stdint.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/stat.h>
23 
get_file_length(const char * filename)24 static uint32_t get_file_length(const char *filename) {
25   struct stat sb;
26 
27   if (stat(filename, &sb) == -1) {
28     fprintf(stderr, "stat(%s) failed: %m\n", filename);
29     exit(EXIT_FAILURE);
30   }
31 
32   return sb.st_size;
33 }
34 
append_file(FILE * out,const char * filename)35 static void append_file(FILE *out, const char *filename) {
36   FILE *f = fopen(filename, "rbe");
37   uint8_t buf[1024 * 8];
38 
39   if (!f) {
40     fprintf(stderr, "fopen(%s) failed: %m\n", filename);
41     exit(EXIT_FAILURE);
42   }
43 
44   while (!feof(f)) {
45     size_t n = fread(buf, 1, sizeof(buf), f);
46 
47     if (fwrite(buf, n, 1, out) != 1) {
48       fprintf(stderr, "fwrite() failed: %m\n");
49       exit(EXIT_FAILURE);
50     }
51   }
52 
53   fclose(f);
54 }
55 
main(int argc,char * argv[])56 int main(int argc, char *argv[]) {
57   FILE *out;
58 
59   if (argc != 4) {
60     fprintf(stderr,
61             "Usage: mkcorpus <dtb> <dto> <output>\n"
62             "\n"
63             "  This concatenates base and overlay file and adds a header to "
64             "create an\n"
65             "  input that can be used for fuzzing.\n");
66     exit(EXIT_FAILURE);
67   }
68 
69   if (strcmp(argv[3], "-") == 0) {
70     out = stdout;
71   } else {
72     out = fopen(argv[3], "wbe");
73     if (!out) {
74       fprintf(stderr, "fopen(%s) failed: %m\n", argv[1]);
75       exit(EXIT_FAILURE);
76     }
77   }
78 
79   uint32_t len = htonl(get_file_length(argv[1]));
80 
81   if (fwrite(&len, sizeof(uint32_t), 1, out) != 1) {
82     fprintf(stderr, "fwrite() failed: %m\n");
83     exit(EXIT_FAILURE);
84   }
85 
86   append_file(out, argv[1]);
87   append_file(out, argv[2]);
88 
89   if (out != stdout) {
90     fclose(out);
91   }
92 
93   return EXIT_SUCCESS;
94 }
95 
96 /* END OF FILE */
97