Fixed compile of flash program
[fw/stlink] / flash / main.c
1 /* simple wrapper around the stlink_flash_write function */
2
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/types.h>
8 #include "stlink-common.h"
9
10
11 struct opts
12 {
13   unsigned int do_read;
14   const char* devname;
15   const char* filename;
16   stm32_addr_t addr;
17   size_t size;
18 };
19
20
21 static int get_opts(struct opts* o, int ac, char** av)
22 {
23   /* stlinkv1 command line: ./flash {read|write} /dev/sgX path addr <size> */
24   /* stlinkv2 command line: ./flash {read|write} path addr <size> */
25
26   unsigned int i = 0;
27
28   if (ac < 3) return -1;
29
30   /* stlinkv2 */
31   o->devname = NULL;
32
33   if (strcmp(av[0], "read") == 0)
34   {
35     o->do_read = 1;
36
37     /* stlinkv1 mode */
38     if (ac == 5)
39     {
40       o->devname = av[1];
41       i = 1;
42     }
43
44     o->size = strtoul(av[i + 3], NULL, 10);
45   }
46   else if (strcmp(av[0], "write") == 0)
47   {
48     o->do_read = 0;
49
50     /* stlinkv1 mode */
51     if (ac == 4)
52     {
53       o->devname = av[1];
54       i = 1;
55     }
56   }
57   else
58   {
59     return -1;
60   }
61
62   o->filename = av[i + 1];
63   o->addr = strtoul(av[i + 2], NULL, 16);
64
65   return 0;
66
67
68
69 int main(int ac, char** av)
70 {
71   stlink_t* sl = NULL;
72   struct opts o;
73   int err = -1;
74
75   if (get_opts(&o, ac - 1, av + 1) == -1)
76   {
77     printf("invalid command line\n");
78     goto on_error;
79   }
80
81   if (o.devname != NULL) /* stlinkv1 */
82   {
83     static const int scsi_verbose = 2;
84     sl = stlink_quirk_open(o.devname, scsi_verbose);
85     if (sl == NULL) goto on_error;
86   }
87   else /* stlinkv2 */
88   {
89     sl = stlink_open_usb(10);
90     if (sl == NULL) goto on_error;
91   }
92
93   if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE)
94     stlink_exit_dfu_mode(sl);
95
96   if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE)
97     stlink_enter_swd_mode(sl);
98
99   stlink_reset(sl);
100
101   if (o.do_read == 0) /* write */
102   {
103     err = stlink_fwrite_flash(sl, o.filename, o.addr);
104     if (err == -1)
105     {
106       printf("stlink_fwrite_flash() == -1\n");
107       goto on_error;
108     }
109   }
110   else /* read */
111   {
112     err = stlink_fread(sl, o.filename, o.addr, o.size);
113     if (err == -1)
114     {
115       printf("stlink_fread() == -1\n");
116       goto on_error;
117     }
118   }
119
120   /* success */
121   err = 0;
122
123  on_error:
124   if (sl != NULL) stlink_close(sl);
125
126   return err;
127 }