[fix] flash tool. not working for stm32l, ok with stm32vl
[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     if (stlink_current_mode(sl) == STLINK_DEV_DFU_MODE)
88       stlink_exit_dfu_mode(sl);
89   }
90   else /* stlinkv2 */
91   {
92     sl = stlink_open_usb(NULL, 10);
93     if (sl == NULL) goto on_error;
94   }
95
96   stlink_enter_swd_mode(sl);
97   stlink_reset(sl);
98
99   if (o.do_read == 0) /* write */
100   {
101     err = stlink_fwrite_flash(sl, o.filename, o.addr);
102     if (err == -1)
103     {
104       printf("stlink_fwrite_flash() == -1\n");
105       goto on_error;
106     }
107   }
108   else /* read */
109   {
110     err = stlink_fread(sl, o.filename, o.addr, o.size);
111     if (err == -1)
112     {
113       printf("stlink_fread() == -1\n");
114       goto on_error;
115     }
116   }
117
118   /* success */
119   err = 0;
120
121  on_error:
122   if (sl != NULL) stlink_close(sl);
123
124   return err;
125 }