940a0c623ed52723f1bd4c3ed8315c786836fd2d
[gnuk/gnuk.git] / tool / stlinkv2.py
1 #! /usr/bin/python
2
3 """
4 stlinkv2.py - a tool to control ST-Link/V2
5
6 Copyright (C) 2012, 2013, 2015 Free Software Initiative of Japan
7 Author: NIIBE Yutaka <gniibe@fsij.org>
8
9 This file is a part of Gnuk, a GnuPG USB Token implementation.
10
11 Gnuk is free software: you can redistribute it and/or modify it
12 under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or
14 (at your option) any later version.
15
16 Gnuk is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19 License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 """
24
25 from struct import *
26 import sys, time
27 import usb
28 from colorama import init as colorama_init, Fore, Back, Style
29 from array import array
30
31 # INPUT: binary file
32
33 # Assumes only single ST-Link/V2 device is attached to computer.
34
35 CORE_ID_CORTEX_M3=0x1ba01477
36 CORE_ID_CORTEX_M0=0x0bb11477
37
38 CHIP_ID_STM32F103xB=0x20036410
39 CHIP_ID_STM32F103xE=0x10016414
40 # CHIP_ID_STM32F0   0x20006440
41 # CHIP_ID_STM32F030??  0x10006444; FSM-55
42
43 GPIOA=0x40010800
44 GPIOB=0x40010C00
45 OPTION_BYTES_ADDR=0x1ffff800
46 RDP_KEY_F1=0x00a5                  # Unlock readprotection
47 RDP_KEY_F0=0x00aa                  # Unlock readprotection
48 FLASH_BASE_ADDR=0x40022000
49
50 FLASH_KEYR=    FLASH_BASE_ADDR+0x04
51 FLASH_OPTKEYR= FLASH_BASE_ADDR+0x08
52 FLASH_SR=      FLASH_BASE_ADDR+0x0c
53 FLASH_CR=      FLASH_BASE_ADDR+0x10
54 FLASH_AR=      FLASH_BASE_ADDR+0x14
55 FLASH_OBR=     FLASH_BASE_ADDR+0x1c
56
57 FLASH_KEY1=0x45670123
58 FLASH_KEY2=0xcdef89ab
59
60 FLASH_SR_BSY=      0x0001
61 FLASH_SR_PGERR=    0x0004
62 FLASH_SR_WRPRTERR= 0x0010
63 FLASH_SR_EOP=      0x0020
64
65 FLASH_CR_PG=     0x0001
66 FLASH_CR_PER=    0x0002
67 FLASH_CR_MER=    0x0004
68 FLASH_CR_OPTPG=  0x0010
69 FLASH_CR_OPTER=  0x0020
70 FLASH_CR_STRT=   0x0040
71 FLASH_CR_LOCK=   0x0080
72 FLASH_CR_OPTWRE= 0x0200
73
74 SPI1= 0x40013000
75
76 def uint32(v):
77     return v[0] + (v[1]<<8) + (v[2]<<16) + (v[3]<<24)
78
79 prog_flash_write_body = b"\x0D\x4A\x0B\x48\x0B\x49\x09\x4C\x01\x25\x14\x26\x00\x27\x25\x61" + \
80     b"\xC3\x5B\xCB\x53\xE3\x68\x2B\x42\xFC\xD1\x33\x42\x02\xD1\x02\x37\x97\x42\xF5\xD1" + \
81     b"\x00\x27\x27\x61\x00\xBE\xC0\x46\x00\x20\x02\x40\x3C\x00\x00\x20"
82 #   .SRC_ADDR: 0x2000003C
83 ## HERE comes: target_addr in 4-byte
84 #   .TARGET_ADDR
85 ## HERE comes: size in 4-byte
86 #   .SIZE
87
88 def gen_prog_flash_write(addr,size):
89     return prog_flash_write_body + pack("<I", addr) + pack("<I", size)
90
91 prog_option_bytes_write_body = b"\x0B\x48\x0A\x49\x08\x4A\x10\x23\x01\x24\x13\x61\x08\x80\xD0\x68" + \
92      b"\x20\x42\xFC\xD1\x02\x31\xFF\x20\x08\x80\xD0\x68\x20\x42\xFC\xD1\x00\x20\x10\x61" + \
93      b"\x00\xBE\xC0\x46\x00\x20\x02\x40"
94 ## HERE comes: target_addr in 4-byte
95 #   .TARGET_ADDR
96 ## HERE comes: option_bytes in 4-byte
97 #   .OPTION_BYTES
98
99 def gen_prog_option_bytes_write(addr,val):
100     return prog_option_bytes_write_body + pack("<I", addr) + pack("<I", val)
101
102 prog_blank_check_body = b"\x04\x49\x05\x4A\x08\x68\x01\x30\x02\xD1\x04\x31\x91\x42\xF9\xD1\x00\xBE\xC0\x46" + \
103                         b"\x00\x00\x00\x08"
104 ## HERE comes: end_addr in 4-byte
105 # .END_ADDR
106
107 def gen_prog_blank_check(size):
108     return prog_blank_check_body + pack("<I", 0x08000000 + size)
109
110
111 SRAM_ADDRESS=0x20000000
112 FLASH_BLOCK_SIZE_F1=16384       # Should be less than (20KiB - 0x0038)
113 FLASH_BLOCK_SIZE_F0=2048        # Should be less than (4KiB - 0x0038)
114 BLOCK_WRITE_TIMEOUT=80          # Increase this when you increase BLOCK_SIZE
115
116
117 class TimeOutError(Exception):
118     def __init__(self, msg):
119         self.msg = msg
120     def __str__(self):
121         return repr(self.msg)
122     def __repr__(self):
123         return "TimeoutError(" + self.msg + ")"
124
125 class OperationFailure(Exception):
126     def __init__(self, msg):
127         self.msg = msg
128     def __str__(self):
129         return repr(self.msg)
130     def __repr__(self):
131         return "OperationFailure(" + self.msg + ")"
132
133
134 class stlinkv2(object):
135     def __init__(self, dev):
136         self.__bulkout = 2
137         self.__bulkin  = 0x81
138
139         self.__timeout = 1000   # 1 second
140         conf = dev.configurations[0]
141         intf_alt = conf.interfaces[0]
142         intf = intf_alt[0]
143         if intf.interfaceClass != 0xff: # Vendor specific
144             raise ValueError("Wrong interface class.", intf.interfaceClass)
145         self.__devhandle = dev.open()
146         self.__devhandle.setConfiguration(conf.value)
147         self.__devhandle.claimInterface(intf.interfaceNumber)
148         # self.__devhandle.setAltInterface(0)  # This was not good for libusb-win32 with wrong arg intf, new correct value 0 would be OK
149
150     def shutdown(self):
151         self.__devhandle.releaseInterface()
152
153     def execute_get(self, cmd, res_len):
154         self.__devhandle.bulkWrite(self.__bulkout, cmd, self.__timeout)
155         res = self.__devhandle.bulkRead(self.__bulkin, res_len, self.__timeout)
156         return res
157
158     def execute_put(self, cmd, data=None):
159         self.__devhandle.bulkWrite(self.__bulkout, cmd, self.__timeout)
160         if (data):
161             self.__devhandle.bulkWrite(self.__bulkout, data, self.__timeout)
162
163     def stl_mode(self):
164         v = self.execute_get(b"\xf5\x00", 2)
165         return (v[1] * 256 + v[0])
166
167     def exit_from_debug_swd(self):
168         self.execute_put(b"\xf2\x21\x00")
169         time.sleep(1)
170
171     def exit_from_dfu(self):
172         self.execute_put(b"\xf3\x07\x00")
173         time.sleep(1)
174
175     def exit_from_debug_swim(self):
176         self.execute_put(b"\xf4\x01\x00")
177         time.sleep(1)
178
179     def enter_swd(self):
180         self.execute_put(b"\xf2\x20\xa3")
181         time.sleep(1)
182
183     def get_status(self):
184         v = self.execute_get(b"\xf2\x01\x00", 2)
185         return (v[1] << 8) + v[0]
186     # RUN:128, HALT:129
187
188     def enter_debug(self):
189         v = self.execute_get(b"\xf2\x02\x00", 2)
190         return (v[1] << 8) + v[0]
191
192     def exit_debug(self):
193         self.execute_put(b"\xf2\x21\x00")
194
195     def reset_sys(self):
196         v = self.execute_get(b"\xf2\x03\x00", 2)
197         return (v[1] << 8) + v[0]
198
199     def read_memory(self, addr, length):
200         return self.execute_get(b"\xf2\x07" + pack('<IH', addr, length), length)
201
202     def read_memory_u32(self, addr):
203         return uint32(self.execute_get(b"\xf2\x07" + pack('<IH', addr, 4), 4))
204
205     def write_memory(self, addr, data):
206         return self.execute_put(b"\xf2\x08" + pack('<IH', addr, len(data)), data)
207
208     def write_memory_u32(self, addr, data):
209         return self.execute_put(b"\xf2\x08" + pack('<IH', addr, 4),
210                                 pack('<I', data))
211
212     def read_reg(self, regno):
213         return uint32(self.execute_get(b"\xf2\x05" + pack('<B', regno), 4))
214
215     def write_reg(self, regno, value):
216         return self.execute_get(b"\xf2\x06" + pack('<BI', regno, value), 2)
217
218     def write_debug_reg(self, addr, value):
219         return self.execute_get(b"\xf2\x35" + pack('<II', addr, value), 2)
220
221     def control_nrst(self, value):
222         return self.execute_get(b"\xf2\x3c" + pack('<B', value), 2)
223
224     def run(self):
225         v = self.execute_get(b"\xf2\x09\x00", 2)
226         return (v[1] << 8) + v[0]
227
228     def get_core_id(self):
229         v = self.execute_get(b"\xf2\x22\x00", 4)
230         return v[0] + (v[1]<<8) + (v[2]<<16) + (v[3]<<24)
231
232     def version(self):
233         v = self.execute_get(b"\xf1", 6)
234         val = (v[0] << 8) + v[1]
235         return ((val >> 12) & 0x0f, (val >> 6) & 0x3f, val & 0x3f)
236
237     # For FST-01-00 and FST-01: LED on, USB connect
238     def setup_gpio(self):
239         apb2enr = self.read_memory_u32(0x40021018)
240         apb2enr = apb2enr | 4 | 8 | 0x1000 # Enable port A, port B, and SPI1
241         self.write_memory_u32(0x40021018, apb2enr)    # RCC->APB2ENR
242         self.write_memory_u32(0x4002100c, 4|8|0x1000) # RCC->APB2RSTR
243         self.write_memory_u32(0x4002100c, 0)
244         self.write_memory_u32(GPIOA+0x0c, 0xffffffff) # ODR
245         self.write_memory_u32(GPIOA+0x04, 0x88888383) # CRH
246         self.write_memory_u32(GPIOA+0x00, 0xBBB38888) # CRL
247         self.write_memory_u32(GPIOB+0x0c, 0xffffffff) # ODR
248         self.write_memory_u32(GPIOB+0x04, 0x88888888) # CRH
249         self.write_memory_u32(GPIOB+0x00, 0x88888883) # CRL
250
251     # For FST-01-00 and FST-01: LED on, USB disconnect
252     def usb_disconnect(self):
253         self.write_memory_u32(GPIOA+0x0c, 0xfffffbff) # ODR
254
255     # For FST-01-00 and FST-01: LED off, USB connect
256     def finish_gpio(self):
257         self.write_memory_u32(GPIOA+0x0c, 0xfffffeff) # ODR
258         self.write_memory_u32(GPIOB+0x0c, 0xfffffffe) # ODR
259         apb2enr = self.read_memory_u32(0x40021018)
260         apb2enr = apb2enr &  ~(4 | 8 | 0x1000)
261         self.write_memory_u32(0x40021018, apb2enr)    # RCC->APB2ENR
262
263     def spi_flash_init(self):
264         self.write_memory_u32(SPI1+0x00, 0x0004); # CR1 <= MSTR
265         i2scfgr = self.read_memory_u32(SPI1+0x1c) # I2SCFGR
266         i2scfgr = i2scfgr & 0xf7ff                # 
267         self.write_memory_u32(SPI1+0x1c, i2scfgr); # I2SCFGR <= SPI mode
268         self.write_memory_u32(SPI1+0x10, 7);       # CRCPR <= 7
269         self.write_memory_u32(SPI1+0x04, 0x04);    # CR2 <= SSOE
270         self.write_memory_u32(SPI1+0x00, 0x0044);  # CR1 <= MSTR | SPE
271
272     def spi_flash_select(self, enable):
273         if enable:
274             self.write_memory_u32(GPIOA+0x0c, 0xffffffef) # ODR
275         else:
276             self.write_memory_u32(GPIOA+0x0c, 0xffffffff) # ODR
277
278     def spi_flash_sendbyte(self, v):
279         i = 0
280         while True:
281             status = self.read_memory_u32(SPI1+0x08) # SR
282             if status & 0x02 != 0:                   # TXE (Data Empty)
283                 break
284             time.sleep(0.01)
285             i = i + 1
286             if i > 10:
287                 raise TimeOutError('spi_flash_sendbyte')
288         self.write_memory_u32(SPI1+0x0c, v) # DR
289         i = 0
290         while True:
291             status = self.read_memory_u32(SPI1+0x08) # SR
292             if status & 0x01 != 0:                   # RXNE (Data Not Empty)
293                 break
294             time.sleep(0.01)
295             i = i + 1
296             if i > 10:
297                 raise TimeOutError('spi_flash_sendbyte')
298         v = self.read_memory_u32(SPI1+0x0c) # DR
299         return v
300
301     def spi_flash_read_id(self):
302         self.spi_flash_select(True)
303         self.spi_flash_sendbyte(0x9f)
304         t0 = self.spi_flash_sendbyte(0xa5)
305         t1 = self.spi_flash_sendbyte(0xa5)
306         t2 = self.spi_flash_sendbyte(0xa5)
307         self.spi_flash_select(False)
308         return (t0 << 16) | (t1 << 8) | t2
309
310     def protection(self):
311         return (self.read_memory_u32(FLASH_OBR) & 0x0002) != 0
312
313     def blank_check(self):
314         prog = gen_prog_blank_check(self.flash_size)
315         self.write_memory(SRAM_ADDRESS, prog)
316         self.write_reg(15, SRAM_ADDRESS)
317         self.run()
318         i = 0
319         while self.get_status() == 0x80:
320             time.sleep(0.050)
321             i = i + 1
322             if i >= 10:
323                 raise TimeOutError("blank check")
324
325         r0_value = self.read_reg(0)
326         return r0_value == 0
327
328     def option_bytes_read(self):
329         return self.read_memory_u32(OPTION_BYTES_ADDR)
330
331     def option_bytes_write(self,addr,val):
332         self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
333         self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
334         self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
335
336         self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY1)
337         self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY2)
338
339         prog = gen_prog_option_bytes_write(addr,val)
340         self.write_memory(SRAM_ADDRESS, prog)
341         self.write_reg(15, SRAM_ADDRESS)
342         self.run()
343         i = 0
344         while self.get_status() == 0x80:
345             time.sleep(0.050)
346             i = i + 1
347             if i >= 10:
348                 raise TimeOutError("option bytes write")
349
350         status = self.read_memory_u32(FLASH_SR)
351         self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
352         if (status & FLASH_SR_EOP) == 0:
353             raise OperationFailure("option bytes write")
354
355     def option_bytes_erase(self):
356         self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
357         self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
358         self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
359
360         self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY1)
361         self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY2)
362
363         self.write_memory_u32(FLASH_CR, FLASH_CR_OPTER)
364         self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_OPTER)
365
366         i = 0
367         while True:
368             status = self.read_memory_u32(FLASH_SR)
369             if (status & FLASH_SR_BSY) == 0:
370                 break
371             i = i + 1
372             if i >= 1000:
373                 break
374
375         self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
376         if (status & FLASH_SR_EOP) == 0:
377             raise OperationFailure("option bytes erase")
378
379     def flash_write_internal(self, addr, data, off, size):
380         prog = gen_prog_flash_write(addr,size)
381         self.write_memory(SRAM_ADDRESS, prog+data[off:off+size])
382         self.write_reg(15, SRAM_ADDRESS)
383         self.run()
384         i = 0
385         while self.get_status() == 0x80:
386             time.sleep(0.050)
387             i = i + 1
388             if i >= BLOCK_WRITE_TIMEOUT:
389                 raise TimeOutError("flash write")
390         status = self.read_memory_u32(FLASH_SR)
391         if (status & FLASH_SR_PGERR) != 0:
392             raise OperationFailure("flash write: write to not erased part")
393         if (status & FLASH_SR_WRPRTERR) != 0:
394             raise OperationFailure("flash write: write to protected part")
395
396     def flash_write(self, addr, data):
397         self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
398         self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
399         self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
400
401         off = 0
402         while True:
403             if len(data[off:]) > self.flash_block_size:
404                 size = self.flash_block_size
405                 self.flash_write_internal(addr, data, off, size)
406                 off = off + size
407                 addr = addr + size
408             else:
409                 size = len(data[off:])
410                 self.flash_write_internal(addr, data, off, size)
411                 break
412
413         self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
414
415     def flash_erase_all(self):
416         self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
417         self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
418         self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
419
420         self.write_memory_u32(FLASH_CR, FLASH_CR_MER)
421         self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_MER)
422
423         i = 0
424         while True:
425             status = self.read_memory_u32(FLASH_SR)
426             if (status & FLASH_SR_BSY) == 0:
427                 break
428             i = i + 1
429             time.sleep(0.050)
430             if i >= 100:
431                 break
432
433         self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
434
435         if (status & FLASH_SR_EOP) == 0:
436             raise OperationFailure("flash erase all")
437
438     def flash_erase_page(self, addr):
439         self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
440         self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
441
442         self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
443
444         self.write_memory_u32(FLASH_CR, FLASH_CR_PER)
445         self.write_memory_u32(FLASH_AR, addr)
446         self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_PER)
447
448         i = 0
449         while True:
450             status = self.read_memory_u32(FLASH_SR)
451             if (status & FLASH_SR_BSY) == 0:
452                 break
453             i = i + 1
454             if i >= 1000:
455                 break
456
457         self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
458
459         if (status & FLASH_SR_EOP) == 0:
460             raise OperationFailure("flash page erase")
461
462     def start(self):
463         mode = self.stl_mode()
464         if mode == 2:
465             self.exit_from_debug_swd()
466         elif mode == 5:
467             self.exit_from_debug_swim()
468         elif mode != 1 and mode != 4:
469             self.exit_from_dfu()
470         new_mode = self.stl_mode()
471         print("Change ST-Link/V2 mode %04x -> %04x" % (mode, new_mode))
472         self.control_nrst(2)
473         self.enter_swd()
474         s = self.get_status()
475         if s != 0x0080:
476             print("Status is %04x" % s)
477             self.run()
478             s = self.get_status()
479             if s != 0x0080:
480                 #                   DCB_DHCSR    DBGKEY
481                 self.write_debug_reg(0xE000EDF0, 0xA05F0000)
482                 s = self.get_status()
483                 if s != 0x0080:
484                     raise ValueError("Status of core is not running.", s)
485         mode = self.stl_mode()
486         if mode != 2:
487             raise ValueError("Failed to switch debug mode.", mode)
488
489         self.core_id = self.get_core_id()
490         if self.core_id == CORE_ID_CORTEX_M3:
491             self.chip_stm32 = True
492         elif self.core_id == CORE_ID_CORTEX_M0:
493             self.chip_stm32 = False
494         else:
495             raise ValueError("Unknown core ID", self.core_id)
496         if self.chip_stm32:
497             self.rdp_key = RDP_KEY_F1
498             self.flash_block_size = FLASH_BLOCK_SIZE_F1
499             self.require_nrst = False
500             self.external_spi_flash = True
501             self.protection_feature = True
502         else:
503             self.rdp_key = RDP_KEY_F0
504             self.flash_block_size = FLASH_BLOCK_SIZE_F0
505             self.require_nrst = True
506             self.external_spi_flash = False
507             self.protection_feature = False
508         return self.core_id
509
510     def get_chip_id(self):
511         if self.chip_stm32:
512             self.chip_id = self.read_memory_u32(0xE0042000)
513             self.flash_size = (self.read_memory_u32(0x1ffff7e0) & 0xffff)*1024
514             if self.chip_id == CHIP_ID_STM32F103xB:
515                 pass
516             elif self.chip_id == CHIP_ID_STM32F103xE:
517                 pass
518             else:
519                 raise ValueError("Unknown chip ID", self.chip_id)
520         else:
521             self.chip_id = self.read_memory_u32(0x40015800)
522             self.flash_size = (self.read_memory_u32(0x1ffff7cc) & 0xffff)*1024
523         print("Flash size: %dKiB" % (self.flash_size/1024))
524         return self.chip_id
525
526     def get_rdp_key(self):
527         return self.rdp_key
528
529     def has_spi_flash(self):
530         return self.external_spi_flash
531
532     def has_protection(self):
533         return self.protection_feature
534
535
536 USB_VENDOR_ST=0x0483            # 0x0483 SGS Thomson Microelectronics
537 USB_VENDOR_STLINKV2=0x3748      # 0x3748 ST-LINK/V2
538
539 def stlinkv2_devices():
540     busses = usb.busses()
541     for bus in busses:
542         devices = bus.devices
543         for dev in devices:
544             if dev.idVendor != USB_VENDOR_ST:
545                 continue
546             if dev.idProduct != USB_VENDOR_STLINKV2:
547                 continue
548             yield dev
549
550 def compare(data_original, data_in_device):
551     i = 0 
552     for d in data_original:
553         if d != data_in_device[i]:
554             raise ValueError("Verify failed at:", i)
555         i += 1
556
557 def open_stlinkv2():
558     for d in stlinkv2_devices():
559         try:
560             stl = stlinkv2(d)
561             return stl
562         except:
563             pass
564     return None
565
566 def help():
567     print("stlinkv2.py [-h]: Show this help message")
568     print("stlinkv2.py [-e]: Erase flash ROM")
569     print("stlinkv2.py [-u]: Unlock flash ROM")
570     print("stlinkv2.py [-s]: Show status")
571     print("stlinkv2.py [-b] [-n] [-r] [-i] FILE: Write content of FILE to flash ROM")
572     print("    -b: Blank check before write (auto erase when not blank)")
573     print("    -n: Don't enable read protection after write")
574     print("    -r: Don't reset after write")
575     print("    -i: Don't test SPI flash")
576
577
578 def main(show_help, erase_only, no_protect, spi_flash_check,
579          reset_after_successful_write,
580          skip_blank_check, status_only, unlock, data):
581     if show_help or len(sys.argv) != 1:
582         help()
583         return 1
584
585     stl = open_stlinkv2()
586     if not stl:
587         raise ValueError("No ST-Link/V2 device found.", None)
588
589     print("ST-Link/V2 version info: %d %d %d" % stl.version())
590     core_id = stl.start()
591
592     stl.control_nrst(2)
593     stl.enter_debug()
594     status = stl.get_status()
595     if status != 0x0081:
596         print("Core does not halt, try API V2 halt.")
597         #                   DCB_DHCSR    DBGKEY|C_HALT|C_DEBUGEN
598         stl.write_debug_reg(0xE000EDF0, 0xA05F0003)
599         status = stl.get_status()
600         stl.write_debug_reg(0xE000EDF0, 0xA05F0003)
601         status = stl.get_status()
602         if status != 0x0081:
603             raise ValueError("Status of core is not halt.", status)
604
605     chip_id = stl.get_chip_id()
606
607     # FST-01 chip id: 0x20036410
608     print("CORE: %08x, CHIP_ID: %08x" % (core_id, chip_id))
609     protection = stl.protection()
610     print("Flash ROM read protection: " + ("ON" if protection else "off"))
611     option_bytes = stl.option_bytes_read()
612     print("Option bytes: %08x" % option_bytes)
613     rdp_key = stl.get_rdp_key()
614     if (option_bytes & 0xff) == rdp_key:
615         ob_protection_enable = False
616     else:
617         ob_protection_enable = True
618
619     if protection:
620         if status_only:
621             print("The MCU is now stopped.")
622             return 0
623         elif not unlock:
624             raise OperationFailure("Flash ROM is protected")
625     else:
626         if not skip_blank_check:
627             stl.reset_sys()
628             blank = stl.blank_check()
629             print("Flash ROM blank check: %s" % blank)
630         else:
631             blank = True
632         if status_only:
633             stl.reset_sys()
634             stl.run()
635             stl.exit_debug()
636             return 0
637         elif unlock and not ob_protection_enable:
638             print("No need to unlock.  Protection is not enabled.")
639             return 1
640
641     if erase_only:
642         if blank:
643             print("No need to erase")
644             return 0
645
646     stl.setup_gpio()
647
648     if unlock:
649         if option_bytes != 0xff:
650             stl.reset_sys()
651             stl.option_bytes_erase()
652         stl.reset_sys()
653         stl.option_bytes_write(OPTION_BYTES_ADDR,rdp_key)
654         stl.usb_disconnect()
655         time.sleep(0.100)
656         stl.finish_gpio()
657         print("Flash ROM read protection disabled.  Reset the board, now.")
658         return 0
659
660     if spi_flash_check and stl.has_spi_flash():
661         stl.spi_flash_init()
662         id = stl.spi_flash_read_id()
663         print("SPI Flash ROM ID: %06x" % id)
664         if id != 0xbf254a:
665             raise ValueError("bad spi flash ROM ID")
666
667     if not blank:
668         print("ERASE ALL")
669         stl.reset_sys()
670         stl.flash_erase_all()
671
672     if erase_only:
673         stl.usb_disconnect()
674         time.sleep(0.100)
675         stl.finish_gpio()
676         return 0
677
678     time.sleep(0.100)
679
680     print("WRITE")
681     stl.flash_write(0x08000000, data)
682
683     print("VERIFY")
684     data_received = array('B')
685     size = len(data)
686     off = 0
687     while size > 0:
688         if size > 1024:
689             blk_size = 1024
690         else:
691             blk_size = size
692         data_received = data_received + array('B', stl.read_memory(0x08000000+off, blk_size))
693         size = size - blk_size
694         off = off + blk_size
695     compare(array('B', data), data_received)
696
697     if not no_protect and stl.has_protection():
698         print("PROTECT")
699         stl.option_bytes_erase()
700         print("Flash ROM read protection enabled.  Reset the board to enable protection.")
701
702     if reset_after_successful_write:
703         stl.control_nrst(2)
704         stl.usb_disconnect()
705         stl.reset_sys()
706         stl.run()
707         stl.exit_debug()
708     else:
709         stl.finish_gpio()
710
711     stl.shutdown()
712     return 0
713
714 if __name__ == '__main__':
715     show_help = False
716     erase_only = False
717     no_protect = False
718     reset_after_successful_write = True
719     skip_blank_check=True
720     status_only = False
721     unlock = False
722     data = None
723     spi_flash_check = True
724
725     while len(sys.argv) > 1:
726         if sys.argv[1] == '-h':
727             sys.argv.pop(1)
728             show_help = True
729             break
730         elif sys.argv[1] == '-e':
731             sys.argv.pop(1)
732             erase_only = True
733             skip_blank_check=False
734             break
735         elif sys.argv[1] == '-u':
736             sys.argv.pop(1)
737             unlock = True
738             break
739         elif sys.argv[1] == '-s':
740             sys.argv.pop(1)
741             status_only = True
742             skip_blank_check=False
743             break
744         elif sys.argv[1] == '-b':
745             skip_blank_check=False
746         elif sys.argv[1] == '-n':
747             no_protect = True
748         elif sys.argv[1] == '-r':
749             reset_after_successful_write = False
750         elif sys.argv[1] == '-i':
751             spi_flash_check = False
752         else:
753             filename = sys.argv[1]
754             f = open(filename,'rb')
755             data = f.read()
756             f.close()
757             if len(data) % 1:
758                 raise ValueError("The size of file should be even")
759         sys.argv.pop(1)
760
761     colorama_init()
762
763     try:
764         r = main(show_help, erase_only, no_protect, spi_flash_check,
765                  reset_after_successful_write,
766                  skip_blank_check, status_only, unlock, data)
767         if r == 0:
768             print(Fore.WHITE + Back.BLUE + Style.BRIGHT + "SUCCESS" + Style.RESET_ALL)
769         sys.exit(r)
770     except Exception as e:
771         print(Back.RED + Style.BRIGHT + repr(e) + Style.RESET_ALL)