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