46a8ce1711e295651cf2c16e1bfae3c08bc6dd09
[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 static void usage(void)
21 {
22     puts("stlinkv1 command line: ./flash {read|write} /dev/sgX path addr <size>");
23     puts("stlinkv2 command line: ./flash {read|write} path addr <size>");
24 }
25
26 static int get_opts(struct opts* o, int ac, char** av)
27 {
28   /* stlinkv1 command line: ./flash {read|write} /dev/sgX path addr <size> */
29   /* stlinkv2 command line: ./flash {read|write} path addr <size> */
30
31   unsigned int i = 0;
32
33   if (ac < 3) return -1;
34
35   /* stlinkv2 */
36   o->devname = NULL;
37
38   if (strcmp(av[0], "read") == 0)
39   {
40     o->do_read = 1;
41
42     /* stlinkv1 mode */
43     if (ac == 5)
44     {
45       o->devname = av[1];
46       i = 1;
47     }
48
49     o->size = strtoul(av[i + 3], NULL, 10);
50   }
51   else if (strcmp(av[0], "write") == 0)
52   {
53     o->do_read = 0;
54
55     /* stlinkv1 mode */
56     if (ac == 4)
57     {
58       o->devname = av[1];
59       i = 1;
60     }
61   }
62   else
63   {
64     return -1;
65   }
66
67   o->filename = av[i + 1];
68   o->addr = strtoul(av[i + 2], NULL, 16);
69
70   return 0;
71
72
73
74 int main(int ac, char** av)
75 {
76   stlink_t* sl = NULL;
77   struct opts o;
78   int err = -1;
79
80   if (get_opts(&o, ac - 1, av + 1) == -1)
81   {
82     printf("invalid command line\n");
83     usage();
84     goto on_error;
85   }
86
87   if (o.devname != NULL) /* stlinkv1 */
88   {
89 #if CONFIG_USE_LIBSG
90     static const int scsi_verbose = 2;
91     sl = stlink_quirk_open(o.devname, scsi_verbose);
92     if (sl == NULL) goto on_error;
93 #else
94     printf("not compiled for use with STLink/V1");
95     goto on_error;
96 #endif
97   }
98   else /* stlinkv2 */
99   {
100     sl = stlink_open_usb(1);
101     if (sl == NULL) goto on_error;
102   }
103
104   if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE)
105     stlink_exit_dfu_mode(sl);
106
107   if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE)
108     stlink_enter_swd_mode(sl);
109
110   stlink_reset(sl);
111
112   if (o.do_read == 0) /* write */
113   {
114     err = stlink_fwrite_flash(sl, o.filename, o.addr);
115     if (err == -1)
116     {
117       printf("stlink_fwrite_flash() == -1\n");
118       goto on_error;
119     }
120   }
121   else /* read */
122   {
123     err = stlink_fread(sl, o.filename, o.addr, o.size);
124     if (err == -1)
125     {
126       printf("stlink_fread() == -1\n");
127       goto on_error;
128     }
129   }
130
131   /* success */
132   err = 0;
133
134  on_error:
135   if (sl != NULL) stlink_close(sl);
136
137   return err;
138 }