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