mkenvimage: Fix getopt() error handling
[oweals/u-boot.git] / tools / mkenvimage.c
1 /*
2  * (C) Copyright 2011 Free Electrons
3  * David Wagner <david.wagner@free-electrons.com>
4  *
5  * Inspired from envcrc.c:
6  * (C) Copyright 2001
7  * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of
15  * the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
25  * MA 02111-1307 USA
26  */
27
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <compiler.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37
38 #include <u-boot/crc.h>
39
40 #define CRC_SIZE sizeof(uint32_t)
41
42 static void usage(const char *exec_name)
43 {
44         fprintf(stderr, "%s [-h] [-r] [-b] [-p <byte>] "
45                "-s <environment partition size> -o <output> <input file>\n"
46                "\n"
47                "This tool takes a key=value input file (same as would a "
48                "`printenv' show) and generates the corresponding environment "
49                "image, ready to be flashed.\n"
50                "\n"
51                "\tThe input file is in format:\n"
52                "\t\tkey1=value1\n"
53                "\t\tkey2=value2\n"
54                "\t\t...\n"
55                "\t-r : the environment has multiple copies in flash\n"
56                "\t-b : the target is big endian (default is little endian)\n"
57                "\t-p <byte> : fill the image with <byte> bytes instead of "
58                "0xff bytes\n"
59                "\n"
60                "If the input file is \"-\", data is read from standard input\n",
61                exec_name);
62 }
63
64 int main(int argc, char **argv)
65 {
66         uint32_t crc, targetendian_crc;
67         const char *txt_filename = NULL, *bin_filename = NULL;
68         int txt_fd, bin_fd;
69         unsigned char *dataptr, *envptr;
70         unsigned char *filebuf = NULL;
71         unsigned int filesize = 0, envsize = 0, datasize = 0;
72         int bigendian = 0;
73         int redundant = 0;
74         unsigned char padbyte = 0xff;
75
76         int option;
77         int ret = EXIT_SUCCESS;
78
79         struct stat txt_file_stat;
80
81         int fp, ep;
82
83         /* Turn off getopt()'s internal error message */
84         opterr = 0;
85
86         /* Parse the cmdline */
87         while ((option = getopt(argc, argv, ":s:o:rbp:h")) != -1) {
88                 switch (option) {
89                 case 's':
90                         datasize = strtol(optarg, NULL, 0);
91                         break;
92                 case 'o':
93                         bin_filename = strdup(optarg);
94                         if (!bin_filename) {
95                                 fprintf(stderr, "Can't strdup() the output "
96                                                 "filename\n");
97                                 return EXIT_FAILURE;
98                         }
99                         break;
100                 case 'r':
101                         redundant = 1;
102                         break;
103                 case 'b':
104                         bigendian = 1;
105                         break;
106                 case 'p':
107                         padbyte = strtol(optarg, NULL, 0);
108                         break;
109                 case 'h':
110                         usage(argv[0]);
111                         return EXIT_SUCCESS;
112                 case ':':
113                         fprintf(stderr, "Missing argument for option -%c\n",
114                                 optopt);
115                         usage(argv[0]);
116                         return EXIT_FAILURE;
117                 default:
118                         fprintf(stderr, "Wrong option -%c\n", optopt);
119                         usage(argv[0]);
120                         return EXIT_FAILURE;
121                 }
122         }
123
124         /* Check datasize and allocate the data */
125         if (datasize == 0) {
126                 fprintf(stderr,
127                         "Please specify the size of the environment "
128                         "partition.\n");
129                 usage(argv[0]);
130                 return EXIT_FAILURE;
131         }
132
133         dataptr = malloc(datasize * sizeof(*dataptr));
134         if (!dataptr) {
135                 fprintf(stderr, "Can't alloc dataptr.\n");
136                 return EXIT_FAILURE;
137         }
138
139         /*
140          * envptr points to the beginning of the actual environment (after the
141          * crc and possible `redundant' bit
142          */
143         envsize = datasize - (CRC_SIZE + redundant);
144         envptr = dataptr + CRC_SIZE + redundant;
145
146         /* Pad the environment with the padding byte */
147         memset(envptr, padbyte, envsize);
148
149         /* Open the input file ... */
150         if (optind >= argc) {
151                 fprintf(stderr, "Please specify an input filename\n");
152                 return EXIT_FAILURE;
153         }
154
155         txt_filename = argv[optind];
156         if (strcmp(txt_filename, "-") == 0) {
157                 int readbytes = 0;
158                 int readlen = sizeof(*envptr) * 2048;
159                 txt_fd = STDIN_FILENO;
160
161                 do {
162                         filebuf = realloc(filebuf, readlen);
163                         readbytes = read(txt_fd, filebuf + filesize, readlen);
164                         filesize += readbytes;
165                 } while (readbytes == readlen);
166
167         } else {
168                 txt_fd = open(txt_filename, O_RDONLY);
169                 if (txt_fd == -1) {
170                         fprintf(stderr, "Can't open \"%s\": %s\n",
171                                         txt_filename, strerror(errno));
172                         return EXIT_FAILURE;
173                 }
174                 /* ... and check it */
175                 ret = fstat(txt_fd, &txt_file_stat);
176                 if (ret == -1) {
177                         fprintf(stderr, "Can't stat() on \"%s\": "
178                                         "%s\n", txt_filename, strerror(errno));
179                         return EXIT_FAILURE;
180                 }
181
182                 filesize = txt_file_stat.st_size;
183                 /* Read the raw input file and transform it */
184                 filebuf = malloc(sizeof(*envptr) * filesize);
185                 ret = read(txt_fd, filebuf, sizeof(*envptr) * filesize);
186                 if (ret != sizeof(*envptr) * filesize) {
187                         fprintf(stderr, "Can't read the whole input file\n");
188                         return EXIT_FAILURE;
189                 }
190                 ret = close(txt_fd);
191         }
192         /*
193          * The right test to do is "=>" (not ">") because of the additional
194          * ending \0. See below.
195          */
196         if (filesize >= envsize) {
197                 fprintf(stderr, "The input file is larger than the "
198                                 "environment partition size\n");
199                 return EXIT_FAILURE;
200         }
201
202         /* Replace newlines separating variables with \0 */
203         for (fp = 0, ep = 0 ; fp < filesize ; fp++) {
204                 if (filebuf[fp] == '\n') {
205                         if (fp == 0) {
206                                 /*
207                                  * Newline at the beginning of the file ?
208                                  * Ignore it.
209                                  */
210                                 continue;
211                         } else if (filebuf[fp-1] == '\\') {
212                                 /*
213                                  * Embedded newline in a variable.
214                                  *
215                                  * The backslash was added to the envptr ;
216                                  * rewind and replace it with a newline
217                                  */
218                                 ep--;
219                                 envptr[ep++] = '\n';
220                         } else {
221                                 /* End of a variable */
222                                 envptr[ep++] = '\0';
223                         }
224                 } else if (filebuf[fp] == '#') {
225                         if (fp != 0 && filebuf[fp-1] == '\n') {
226                                 /* This line is a comment, let's skip it */
227                                 while (fp < txt_file_stat.st_size && fp++ &&
228                                        filebuf[fp] != '\n');
229                         } else {
230                                 envptr[ep++] = filebuf[fp];
231                         }
232                 } else {
233                         envptr[ep++] = filebuf[fp];
234                 }
235         }
236         /*
237          * Make sure there is a final '\0'
238          * And do it again on the next byte to mark the end of the environment.
239          */
240         if (envptr[ep-1] != '\0') {
241                 envptr[ep++] = '\0';
242                 /*
243                  * The text file doesn't have an ending newline.  We need to
244                  * check the env size again to make sure we have room for two \0
245                  */
246                 if (ep >= envsize) {
247                         fprintf(stderr, "The environment file is too large for "
248                                         "the target environment storage\n");
249                         return EXIT_FAILURE;
250                 }
251                 envptr[ep] = '\0';
252         } else {
253                 envptr[ep] = '\0';
254         }
255
256         /* Computes the CRC and put it at the beginning of the data */
257         crc = crc32(0, envptr, envsize);
258         targetendian_crc = bigendian ? cpu_to_be32(crc) : cpu_to_le32(crc);
259
260         memcpy(dataptr, &targetendian_crc, sizeof(uint32_t));
261
262         bin_fd = creat(bin_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
263         if (bin_fd == -1) {
264                 fprintf(stderr, "Can't open output file \"%s\": %s\n",
265                                 bin_filename, strerror(errno));
266                 return EXIT_FAILURE;
267         }
268
269         if (write(bin_fd, dataptr, sizeof(*dataptr) * datasize) !=
270                         sizeof(*dataptr) * datasize) {
271                 fprintf(stderr, "write() failed: %s\n", strerror(errno));
272                 return EXIT_FAILURE;
273         }
274
275         ret = close(bin_fd);
276
277         return ret;
278 }