ao-tools: Fix warnings in ao-tools
[fw/altos] / ao-tools / ao-usbload / ao-usbload.c
1 /*
2  * Copyright © 2012 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 #include <err.h>
20 #include <fcntl.h>
21 #include <gelf.h>
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <sysexits.h>
26 #include <unistd.h>
27 #include <getopt.h>
28 #include <string.h>
29 #include <stdbool.h>
30 #include "ao-elf.h"
31 #include "ccdbg.h"
32 #include "cc-usb.h"
33 #include "cc.h"
34 #include "ao-usbload.h"
35 #include "ao-selfload.h"
36 #include "ao-verbose.h"
37 #include "ao-editaltos.h"
38
39 static uint16_t
40 get_uint16(struct cc_usb *cc, uint32_t addr)
41 {
42         uint16_t        result;
43         result = ao_self_get_uint16(cc, addr);
44         return result;
45 }
46
47 /*
48  * Read a 32-bit value from the target device with arbitrary
49  * alignment
50  */
51 static uint32_t
52 get_uint32(struct cc_usb *cc, uint32_t addr)
53 {
54         uint32_t        result;
55
56         result = ao_self_get_uint32(cc, addr);
57         return result;
58 }
59
60 /*
61  * Check to see if the target device has been
62  * flashed with a similar firmware image before
63  *
64  * This is done by looking for the same romconfig version,
65  * which should be at the same location as the linker script
66  * places this at 0x100 from the start of the rom section
67  */
68 static int
69 check_flashed(struct cc_usb *cc)
70 {
71         uint16_t        romconfig_version = get_uint16(cc, AO_ROMCONFIG_VERSION);
72         uint16_t        romconfig_check = get_uint16(cc, AO_ROMCONFIG_CHECK);
73
74         if (romconfig_version != (uint16_t) ~romconfig_check) {
75                 fprintf (stderr, "Device has not been flashed before\n");
76                 return 0;
77         }
78         return 1;
79 }
80
81 static const struct option options[] = {
82         { .name = "tty", .has_arg = 1, .val = 'T' },
83         { .name = "device", .has_arg = 1, .val = 'D' },
84         { .name = "raw", .has_arg = 0, .val = 'r' },
85         { .name = "cal", .has_arg = 1, .val = 'c' },
86         { .name = "serial", .has_arg = 1, .val = 's' },
87         { .name = "verbose", .has_arg = 1, .val = 'v' },
88         { .name = "wait", .has_arg = 0, .val = 'w' },
89         { .name = "force", .has_arg = 0, .val = 'f' },
90         { 0, 0, 0, 0},
91 };
92
93 static void usage(char *program)
94 {
95         fprintf(stderr, "usage: %s [--raw] [--verbose=<verbose>] [--device=<device>] [-tty=<tty>] [--cal=<radio-cal>] [--serial=<serial>] [--wait] [--force] file.{elf,ihx}\n", program);
96         exit(1);
97 }
98
99 static void
100 done(struct cc_usb *cc, int code)
101 {
102 /*      cc_usb_printf(cc, "a\n"); */
103         cc_usb_close(cc);
104         exit (code);
105 }
106
107 static int
108 ends_with(char *whole, char *suffix)
109 {
110         int whole_len = strlen(whole);
111         int suffix_len = strlen(suffix);
112
113         if (suffix_len > whole_len)
114                 return 0;
115         return strcmp(whole + whole_len - suffix_len, suffix) == 0;
116 }
117
118 static int
119 ucs2len(uint16_t *ucs2)
120 {
121         int     len = 0;
122         while (*ucs2++)
123                 len++;
124         return len;
125 }
126
127 static int
128 putucs4(uint32_t c, FILE *file)
129 {
130         char d;
131         int     bits;
132
133              if (c <       0x80) { d = c;                         bits= -6; }
134         else if (c <      0x800) { d= ((c >>  6) & 0x1F) | 0xC0;  bits=  0; }
135         else if (c <    0x10000) { d= ((c >> 12) & 0x0F) | 0xE0;  bits=  6; }
136         else if (c <   0x200000) { d= ((c >> 18) & 0x07) | 0xF0;  bits= 12; }
137         else if (c <  0x4000000) { d= ((c >> 24) & 0x03) | 0xF8;  bits= 18; }
138         else if (c < 0x80000000) { d= ((c >> 30) & 0x01) | 0xFC;  bits= 24; }
139         else return EOF;
140
141         if (putc (d, file) < 0)
142                 return EOF;
143
144         for ( ; bits >= 0; bits-= 6)
145                 if (putc (((c >> bits) & 0x3F) | 0x80, file) < 0)
146                         return EOF;
147
148         return 0;
149 }
150
151 static void
152 putucs2str(uint16_t *ucs2str, FILE *file)
153 {
154         uint16_t        ucs2;
155
156         while ((ucs2 = *ucs2str++) != 0)
157                 putucs4(ucs2, file);
158 }
159
160 int
161 main (int argc, char **argv)
162 {
163         char                    *device = NULL;
164         char                    *filename;
165         int                     raw = 0;
166         char                    *serial_end;
167         unsigned int            serial = 0;
168         uint32_t                cal = 0;
169         char                    *cal_end;
170         int                     c;
171         int                     was_flashed = 0;
172         struct ao_hex_image     *load;
173         struct cc_usb           *cc = NULL;
174         char                    *tty = NULL;
175         int                     success;
176         int                     verbose = 0;
177         struct ao_sym           *file_symbols;
178         int                     num_file_symbols;
179         uint32_t                flash_base, flash_bound;
180         int                     has_flash_size = 0;
181         int                     force = 0;
182
183         while ((c = getopt_long(argc, argv, "wrfT:D:c:s:v:", options, NULL)) != -1) {
184                 switch (c) {
185                 case 'T':
186                         tty = optarg;
187                         break;
188                 case 'D':
189                         device = optarg;
190                         break;
191                 case 'r':
192                         raw = 1;
193                         break;
194                 case 'w':
195                         cc_default_timeout = -1;
196                         break;
197                 case 'c':
198                         cal = strtoul(optarg, &cal_end, 10);
199                         if (cal_end == optarg || *cal_end != '\0')
200                                 usage(argv[0]);
201                         break;
202                 case 's':
203                         serial = strtoul(optarg, &serial_end, 10);
204                         if (serial_end == optarg || *serial_end != '\0')
205                                 usage(argv[0]);
206                         break;
207                 case 'v':
208                         verbose++;
209                         break;
210                 case 'f':
211                         force = 1;
212                         break;
213                 default:
214                         usage(argv[0]);
215                         break;
216                 }
217         }
218
219         ao_verbose = verbose;
220
221         if (verbose > 1)
222                 ccdbg_add_debug(CC_DEBUG_BITBANG);
223
224         filename = argv[optind];
225         if (filename == NULL)
226                 usage(argv[0]);
227
228         if (ends_with (filename, ".elf")) {
229                 load = ao_load_elf(filename, &file_symbols, &num_file_symbols);
230         } else if (ends_with (filename, ".ihx")) {
231                 load = ao_hex_load(filename, &file_symbols, &num_file_symbols);
232         } else
233                 usage(argv[0]);
234
235         if (!raw) {
236                 if (!ao_editaltos_find_symbols(file_symbols, num_file_symbols, ao_symbols, ao_num_symbols)) {
237                         fprintf(stderr, "Cannot find required symbols\n");
238                         usage(argv[0]);
239                 }
240         }
241
242         {
243                 int     is_loader;
244                 int     tries;
245
246                 for (tries = 0; tries < 3; tries++) {
247                         char    *this_tty = tty;
248                         if (!this_tty)
249                                 this_tty = cc_usbdevs_find_by_arg(device, "AltosFlash");
250                         if (!this_tty)
251                                 this_tty = cc_usbdevs_find_by_arg(device, "TeleMega");
252                         if (!this_tty)
253                                 this_tty = cc_usbdevs_find_by_arg(device, "TeleMetrum");
254                         if (!this_tty)
255                                 this_tty = cc_usbdevs_find_by_arg(device, "TeleGPS");
256                         if (!this_tty)
257                                 this_tty = getenv("ALTOS_TTY");
258                         if (!this_tty)
259                                 this_tty="/dev/ttyACM0";
260
261                         cc = cc_usb_open(this_tty);
262
263                         if (!cc)
264                                 exit(1);
265                         cc_usb_printf(cc, "v\n");
266                         is_loader = 0;
267                         for (;;) {
268                                 char    line[256];
269                                 cc_usb_getline(cc, line, sizeof(line));
270                                 if (!strncmp(line, "altos-loader", 12))
271                                         is_loader = 1;
272                                 if (!strncmp(line, "flash-range", 11)) {
273                                         int i;
274                                         for (i = 11; i < strlen(line); i++)
275                                                 if (line[i] != ' ')
276                                                         break;
277                                         if (sscanf(line + i, "%x %x", &flash_base, &flash_bound) == 2)
278                                                 has_flash_size = 1;
279                                 }
280                                 if (!strncmp(line, "software-version", 16))
281                                         break;
282                         }
283                         if (is_loader)
284                                 break;
285                         printf ("rebooting to loader\n");
286                         cc_usb_printf(cc, "X\n");
287                         cc_usb_close(cc);
288                         sleep(1);
289                         cc = NULL;
290                 }
291                 if (!is_loader) {
292                         fprintf(stderr, "Cannot switch to boot loader\n");
293                         exit(1);
294                 }
295 #if 0
296                 {
297                         uint8_t check[256];
298                         int     i = 0;
299
300                         ao_self_block_read(cc, AO_BOOT_APPLICATION_BASE, check);
301                         for (;;) {
302                                 uint8_t block[256];
303                                 putchar ('.');
304                                 if (++i == 40) {
305                                         putchar('\n');
306                                         i = 0;
307                                 }
308                                 fflush(stdout);
309                                 ao_self_block_write(cc, AO_BOOT_APPLICATION_BASE, block);
310                                 ao_self_block_read(cc, AO_BOOT_APPLICATION_BASE, block);
311                                 if (memcmp(block, check, 256) != 0) {
312                                         fprintf (stderr, "read differed\n");
313                                         exit(1);
314                                 }
315                         }
316                 }
317 #endif
318         }
319
320         /* If the device can tell us the size of flash, make sure
321          * the image fits in that
322          */
323         if (has_flash_size) {
324                 if (load->address < flash_base ||
325                     load->address + load->length > flash_bound)
326                 {
327                         fprintf(stderr, "Image does not fit on device.\n");
328                         fprintf(stderr, "  Image base:  %08x bounds %08x\n",
329                                 load->address, load->address + load->length);
330                         fprintf(stderr, "  Device base: %08x bounds %08x\n",
331                                 flash_base, flash_bound);
332                         done(cc, 1);
333                 }
334         }
335
336         if (!raw) {
337                 /* Go fetch existing config values
338                  * if available
339                  */
340                 was_flashed = check_flashed(cc);
341
342                 if (!serial) {
343                         if (!was_flashed) {
344                                 fprintf (stderr, "Must provide serial number\n");
345                                 done(cc, 1);
346                         }
347                         serial = get_uint16(cc, AO_SERIAL_NUMBER);
348                         if (!serial || serial == 0xffff) {
349                                 fprintf (stderr, "Invalid existing serial %d\n", serial);
350                                 done(cc, 1);
351                         }
352                 }
353
354                 if (!cal && AO_RADIO_CAL && was_flashed) {
355                         cal = get_uint32(cc, AO_RADIO_CAL);
356                         if (!cal || cal == 0xffffffff) {
357                                 fprintf (stderr, "Invalid existing rf cal %d\n", cal);
358                                 done(cc, 1);
359                         }
360                 }
361
362                 if (!force && was_flashed) {
363                         struct ao_usb_id        new_id, old_id;
364                         uint16_t                *new_product, *old_product;
365                         int                     new_len, old_len;
366
367                         if (!ao_heximage_usb_id(load, &new_id)) {
368                                 fprintf(stderr, "Can't get new USB id\n");
369                                 done(cc, 1);
370                         }
371
372                         if (!ao_self_get_usb_id(cc, &old_id)) {
373                                 fprintf(stderr, "Can't get old USB id\n");
374                                 done(cc, 1);
375                         }
376                         if (new_id.vid != old_id.vid || new_id.pid != old_id.pid) {
377                                 fprintf(stderr, "USB ID mismatch (device is %04x/%04x image is %04x/%04x)\n",
378                                         old_id.vid, old_id.pid, new_id.vid, new_id.pid);
379                                 done(cc, 1);
380                         }
381
382                         new_product = ao_heximage_usb_product(load);
383                         if (!new_product) {
384                                 fprintf(stderr, "Can't get new USB product name\n");
385                                 done(cc, 1);
386                         }
387                         old_product = ao_self_get_usb_product(cc);
388                         if (!old_product) {
389                                 fprintf(stderr, "Can't get existing USB product name\n");
390                                 done(cc, 1);
391                         }
392                         new_len = ucs2len(new_product);
393                         old_len = ucs2len(old_product);
394                         if (new_len != old_len || memcmp(new_product, old_product, new_len * 2) != 0) {
395                                 fprintf(stderr, "USB product mismatch (device is ");
396                                 putucs2str(old_product, stderr);
397                                 fprintf(stderr, ", image is ");
398                                 putucs2str(new_product, stderr);
399                                 fprintf(stderr, ")\n");
400                                 done(cc, 1);
401                         }
402                 }
403
404                 if (!ao_editaltos(load, serial, cal))
405                         done(cc, 1);
406         }
407
408         /* And flash the resulting image to the device
409          */
410         success = ao_self_write(cc, load);
411
412         if (!success) {
413                 fprintf (stderr, "\"%s\": Write failed\n", filename);
414                 done(cc, 1);
415         }
416
417         done(cc, 0);
418 }