4 stlinkv2.py - a tool to control ST-Link/V2
6 Copyright (C) 2012, 2013 Free Software Initiative of Japan
7 Author: NIIBE Yutaka <gniibe@fsij.org>
9 This file is a part of Gnuk, a GnuPG USB Token implementation.
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.
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.
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/>.
28 from colorama import init as colorama_init, Fore, Back, Style
32 # Assumes only single ST-Link/V2 device is attached to computer.
37 OPTION_BYTES_ADDR=0x1ffff800
38 RDP_KEY=0x00a5 # Unlock readprotection
39 FLASH_BASE_ADDR=0x40022000
41 FLASH_KEYR= FLASH_BASE_ADDR+0x04
42 FLASH_OPTKEYR= FLASH_BASE_ADDR+0x08
43 FLASH_SR= FLASH_BASE_ADDR+0x0c
44 FLASH_CR= FLASH_BASE_ADDR+0x10
45 FLASH_AR= FLASH_BASE_ADDR+0x14
46 FLASH_OBR= FLASH_BASE_ADDR+0x1c
52 FLASH_SR_PGERR= 0x0004
53 FLASH_SR_WRPRTERR= 0x0010
59 FLASH_CR_OPTPG= 0x0010
60 FLASH_CR_OPTER= 0x0020
63 FLASH_CR_OPTWRE= 0x0200
69 return v[0] + (v[1]<<8) + (v[2]<<16) + (v[3]<<24)
71 ## HERE comes: "movw r2,#SIZE" instruction
72 prog_flash_write_body = "\x0A\x48" + "\x0B\x49" + \
73 "\x08\x4C" + "\x01\x25" + "\x14\x26" + "\x00\x27" + "\x25\x61" + \
74 "\xC3\x5B" + "\xCB\x53" + "\xE3\x68" + "\x2B\x42" + "\xFC\xD1" + \
75 "\x33\x42" + "\x02\xD1" + "\x02\x37" + "\x97\x42" + "\xF5\xD1" + \
76 "\x00\x27" + "\x27\x61" + "\x00\xBE" + "\x00\x20\x02\x40" + \
78 # .SRC_ADDR: 0x20000038
79 ## HERE comes: target_addr in 4-byte
82 def gen_prog_flash_write(addr,size):
83 return pack("<BBBB", (0x40 | (size&0xf000)>>12), (0xf2 | (size&0x0800)>>9),
84 (size & 0x00ff), (0x02 | ((size&0x0700) >> 4))) + \
85 prog_flash_write_body + pack("<I", addr)
88 ## HERE comes: "movw r0,#VAL" instruction
89 prog_option_bytes_write_body = "\x06\x49" + "\x05\x4A" + "\x10\x23" + \
90 "\x01\x24" + "\x13\x61" + "\x08\x80" + "\xD0\x68" + "\x20\x42" + \
91 "\xFC\xD1" + "\x00\x20" + "\x10\x61" + "\x00\xBE" + "\x00\x20\x02\x40"
92 ## HERE comes: target_addr in 4-byte
95 def gen_prog_option_bytes_write(addr,val):
96 return pack("<BBBB", (0x40 | (val&0xf000)>>12), (0xf2 | (val&0x0800)>>9),
97 (val & 0x00ff), (0x00 | ((val&0x0700) >> 4))) + \
98 prog_option_bytes_write_body + pack("<I", addr)
100 prog_blank_check_body = "\x04\x49" + "\x05\x4A" + "\x08\x68" + "\x01\x30" + \
101 "\x02\xD1" + "\x04\x31" + "\x91\x42" + "\xF9\xD1" + "\x00\xBE" + \
102 "\x00\xBF" + "\x00\x00\x00\x08"
103 ## HERE comes: end_addr in 4-byte
106 def gen_prog_blank_check(size):
107 return prog_blank_check_body + pack("<I", 0x08000000 + size)
110 SRAM_ADDRESS=0x20000000
111 BLOCK_SIZE=16384 # Should be less than (20KiB - 0x0038)
112 BLOCK_WRITE_TIMEOUT=80 # Increase this when you increase BLOCK_SIZE
115 class TimeOutError(Exception):
116 def __init__(self, msg):
119 return repr(self.msg)
121 return "TimeoutError(" + self.msg + ")"
123 class OperationFailure(Exception):
124 def __init__(self, msg):
127 return repr(self.msg)
129 return "OperationFailure(" + self.msg + ")"
132 class stlinkv2(object):
133 def __init__(self, dev):
137 self.__timeout = 1000 # 1 second
138 conf = dev.configurations[0]
139 intf_alt = conf.interfaces[0]
141 if intf.interfaceClass != 0xff: # Vendor specific
142 raise ValueError("Wrong interface class.", intf.interfaceClass)
143 self.__devhandle = dev.open()
145 self.__devhandle.setConfiguration(conf)
148 self.__devhandle.claimInterface(intf)
149 # self.__devhandle.setAltInterface(intf) # This is not good for libusb-win32
152 self.__devhandle.releaseInterface()
154 def execute_get(self, cmd, res_len):
155 self.__devhandle.bulkWrite(self.__bulkout, cmd, self.__timeout)
156 res = self.__devhandle.bulkRead(self.__bulkin, res_len, self.__timeout)
159 def execute_put(self, cmd, data=None):
160 self.__devhandle.bulkWrite(self.__bulkout, cmd, self.__timeout)
162 self.__devhandle.bulkWrite(self.__bulkout, data, self.__timeout)
165 v = self.execute_get("\xf5\x00", 2)
166 return (v[1] * 256 + v[0])
168 def exit_from_debug_swd(self):
169 self.execute_put("\xf2\x21\x00")
172 def exit_from_dfu(self):
173 self.execute_put("\xf3\x07\x00")
176 def exit_from_debug_swim(self):
177 self.execute_put("\xf4\x01\x00")
181 self.execute_put("\xf2\x20\xa3")
184 def get_status(self):
185 v = self.execute_get("\xf2\x01\x00", 2)
186 return (v[1] << 8) + v[0]
189 def enter_debug(self):
190 v = self.execute_get("\xf2\x02\x00", 2)
191 return (v[1] << 8) + v[0]
193 def exit_debug(self):
194 self.execute_put("\xf2\x21\x00")
197 v = self.execute_get("\xf2\x03\x00", 2)
198 return (v[1] << 8) + v[0]
200 def read_memory(self, addr, length):
201 return self.execute_get("\xf2\x07" + pack('<IH', addr, length), length)
203 def read_memory_u32(self, addr):
204 return uint32(self.execute_get("\xf2\x07" + pack('<IH', addr, 4), 4))
206 def write_memory(self, addr, data):
207 return self.execute_put("\xf2\x08" + pack('<IH', addr, len(data)), data)
209 def write_memory_u32(self, addr, data):
210 return self.execute_put("\xf2\x08" + pack('<IH', addr, 4),
213 def read_reg(self, regno):
214 return uint32(self.execute_get("\xf2\x05" + pack('<B', regno), 4))
216 def write_reg(self, regno, value):
217 return self.execute_get("\xf2\x06" + pack('<BI', regno, value), 2)
219 def write_debug_reg(self, addr, value):
220 return self.execute_get("\xf2\x35" + pack('<II', addr, value), 2)
223 v = self.execute_get("\xf2\x09\x00", 2)
224 return (v[1] << 8) + v[0]
227 v = self.execute_get("\xf2\x22\x00", 4)
228 return v[0] + (v[1]<<8) + (v[2]<<16) + (v[3]<<24)
231 v = self.execute_get("\xf1", 6)
232 val = (v[0] << 8) + v[1]
233 return ((val >> 12) & 0x0f, (val >> 6) & 0x3f, val & 0x3f)
235 # For FST-01-00 and FST-01: LED on, USB connect
236 def setup_gpio(self):
237 apb2enr = self.read_memory_u32(0x40021018)
238 apb2enr = apb2enr | 4 | 8 | 0x1000 # Enable port A, port B, and SPI1
239 self.write_memory_u32(0x40021018, apb2enr) # RCC->APB2ENR
240 self.write_memory_u32(0x4002100c, 4|8|0x1000) # RCC->APB2RSTR
241 self.write_memory_u32(0x4002100c, 0)
242 self.write_memory_u32(GPIOA+0x0c, 0xffffffff) # ODR
243 self.write_memory_u32(GPIOA+0x04, 0x88888383) # CRH
244 self.write_memory_u32(GPIOA+0x00, 0xBBB38888) # CRL
245 self.write_memory_u32(GPIOB+0x0c, 0xffffffff) # ODR
246 self.write_memory_u32(GPIOB+0x04, 0x88888888) # CRH
247 self.write_memory_u32(GPIOB+0x00, 0x88888883) # CRL
249 # For FST-01-00 and FST-01: LED on, USB disconnect
250 def usb_disconnect(self):
251 self.write_memory_u32(GPIOA+0x0c, 0xfffffbff) # ODR
253 # For FST-01-00 and FST-01: LED off, USB connect
254 def finish_gpio(self):
255 self.write_memory_u32(GPIOA+0x0c, 0xfffffeff) # ODR
256 self.write_memory_u32(GPIOB+0x0c, 0xfffffffe) # ODR
257 apb2enr = self.read_memory_u32(0x40021018)
258 apb2enr = apb2enr & ~(4 | 8 | 0x1000)
259 self.write_memory_u32(0x40021018, apb2enr) # RCC->APB2ENR
261 def spi_flash_init(self):
262 self.write_memory_u32(SPI1+0x00, 0x0004); # CR1 <= MSTR
263 i2scfgr = self.read_memory_u32(SPI1+0x1c) # I2SCFGR
264 i2scfgr = i2scfgr & 0xf7ff #
265 self.write_memory_u32(SPI1+0x1c, i2scfgr); # I2SCFGR <= SPI mode
266 self.write_memory_u32(SPI1+0x10, 7); # CRCPR <= 7
267 self.write_memory_u32(SPI1+0x04, 0x04); # CR2 <= SSOE
268 self.write_memory_u32(SPI1+0x00, 0x0044); # CR1 <= MSTR | SPE
270 def spi_flash_select(self, enable):
272 self.write_memory_u32(GPIOA+0x0c, 0xffffffef) # ODR
274 self.write_memory_u32(GPIOA+0x0c, 0xffffffff) # ODR
276 def spi_flash_sendbyte(self, v):
279 status = self.read_memory_u32(SPI1+0x08) # SR
280 if status & 0x02 != 0: # TXE (Data Empty)
285 raise TimeOutError('spi_flash_sendbyte')
286 self.write_memory_u32(SPI1+0x0c, v) # DR
289 status = self.read_memory_u32(SPI1+0x08) # SR
290 if status & 0x01 != 0: # RXNE (Data Not Empty)
295 raise TimeOutError('spi_flash_sendbyte')
296 v = self.read_memory_u32(SPI1+0x0c) # DR
299 def spi_flash_read_id(self):
300 self.spi_flash_select(True)
301 self.spi_flash_sendbyte(0x9f)
302 t0 = self.spi_flash_sendbyte(0xa5)
303 t1 = self.spi_flash_sendbyte(0xa5)
304 t2 = self.spi_flash_sendbyte(0xa5)
305 self.spi_flash_select(False)
306 return (t0 << 16) | (t1 << 8) | t2
308 def protection(self):
309 return (self.read_memory_u32(FLASH_OBR) & 0x0002) != 0
311 def blank_check(self):
312 prog = gen_prog_blank_check(0x20000) # 128KiB XXX: table lookup???
313 self.write_memory(SRAM_ADDRESS, prog)
314 self.write_reg(15, SRAM_ADDRESS)
317 while self.get_status() == 0x80:
321 raise TimeOutError("blank check")
323 r0_value = self.read_reg(0)
326 def option_bytes_read(self):
327 return self.read_memory_u32(OPTION_BYTES_ADDR)
329 def option_bytes_write(self,addr,val):
330 self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
331 self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
332 self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
334 self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY1)
335 self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY2)
337 prog = gen_prog_option_bytes_write(addr,val)
338 self.write_memory(SRAM_ADDRESS, prog)
339 self.write_reg(15, SRAM_ADDRESS)
342 while self.get_status() == 0x80:
346 raise TimeOutError("option bytes write")
348 status = self.read_memory_u32(FLASH_SR)
349 self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
350 if (status & FLASH_SR_EOP) == 0:
351 raise OperationFailure("option bytes write")
353 def option_bytes_erase(self):
354 self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
355 self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
356 self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
358 self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY1)
359 self.write_memory_u32(FLASH_OPTKEYR, FLASH_KEY2)
361 self.write_memory_u32(FLASH_CR, FLASH_CR_OPTER)
362 self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_OPTER)
366 status = self.read_memory_u32(FLASH_SR)
367 if (status & FLASH_SR_BSY) == 0:
373 self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
374 if (status & FLASH_SR_EOP) == 0:
375 raise OperationFailure("option bytes erase")
377 def flash_write_internal(self, addr, data, off, size):
378 prog = gen_prog_flash_write(addr,size)
379 self.write_memory(SRAM_ADDRESS, prog+data[off:off+size])
380 self.write_reg(15, SRAM_ADDRESS)
383 while self.get_status() == 0x80:
386 if i >= BLOCK_WRITE_TIMEOUT:
387 raise TimeOutError("flash write")
388 status = self.read_memory_u32(FLASH_SR)
389 if (status & FLASH_SR_PGERR) != 0:
390 raise OperationFailure("flash write: write to not erased part")
391 if (status & FLASH_SR_WRPRTERR) != 0:
392 raise OperationFailure("flash write: write to protected part")
394 def flash_write(self, addr, data):
395 self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
396 self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
397 self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
401 if len(data[off:]) > BLOCK_SIZE:
403 self.flash_write_internal(addr, data, off, size)
407 size = len(data[off:])
408 self.flash_write_internal(addr, data, off, size)
411 self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
413 def flash_erase_all(self):
414 self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
415 self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
416 self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
418 self.write_memory_u32(FLASH_CR, FLASH_CR_MER)
419 self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_MER)
423 status = self.read_memory_u32(FLASH_SR)
424 if (status & FLASH_SR_BSY) == 0:
431 self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
433 if (status & FLASH_SR_EOP) == 0:
434 raise OperationFailure("flash erase all")
436 def flash_erase_page(self, addr):
437 self.write_memory_u32(FLASH_KEYR, FLASH_KEY1)
438 self.write_memory_u32(FLASH_KEYR, FLASH_KEY2)
440 self.write_memory_u32(FLASH_SR, FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGERR)
442 self.write_memory_u32(FLASH_CR, FLASH_CR_PER)
443 self.write_memory_u32(FLASH_AR, addr)
444 self.write_memory_u32(FLASH_CR, FLASH_CR_STRT | FLASH_CR_PER)
448 status = self.read_memory_u32(FLASH_SR)
449 if (status & FLASH_SR_BSY) == 0:
455 self.write_memory_u32(FLASH_CR, FLASH_CR_LOCK)
457 if (status & FLASH_SR_EOP) == 0:
458 raise OperationFailure("flash page erase")
461 mode = self.stl_mode()
463 self.exit_from_debug_swd()
465 self.exit_from_debug_swim()
466 elif mode != 1 and mode != 4:
468 new_mode = self.stl_mode()
469 print "Change ST-Link/V2 mode %04x -> %04x" % (mode, new_mode)
471 s = self.get_status()
473 print "Status is %04x" % s
475 s = self.get_status()
478 self.write_debug_reg(0xE000EDF0, 0xA05F0000)
479 s = self.get_status()
481 raise ValueError("Status of core is not running.", s)
482 mode = self.stl_mode()
484 raise ValueError("Failed to switch debug mode.", mode)
487 USB_VENDOR_ST=0x0483 # 0x0483 SGS Thomson Microelectronics
488 USB_VENDOR_STLINKV2=0x3748 # 0x3748 ST-LINK/V2
490 def stlinkv2_devices():
491 busses = usb.busses()
493 devices = bus.devices
495 if dev.idVendor != USB_VENDOR_ST:
497 if dev.idProduct != USB_VENDOR_STLINKV2:
501 def compare(data_original, data_in_device):
503 for d in data_original:
504 if ord(d) != data_in_device[i]:
505 raise ValueError("Verify failed at:", i)
509 for d in stlinkv2_devices():
518 print "stlinkv2.py [-h]: Show this help message"
519 print "stlinkv2.py [-e]: Erase flash ROM"
520 print "stlinkv2.py [-u]: Unlock flash ROM"
521 print "stlinkv2.py [-s]: Show status"
522 print "stlinkv2.py [-b] [-n] [-r] [-i] FILE: Write content of FILE to flash ROM"
523 print " -b: Blank check before write (auto erase when not blank)"
524 print " -n: Don't enable read protection after write"
525 print " -r: Don't reset after write"
526 print " -i: Don't test SPI flash"
529 def main(show_help, erase_only, no_protect, spi_flash_check,
530 reset_after_successful_write,
531 skip_blank_check, status_only, unlock, data):
532 if show_help or len(sys.argv) != 1:
536 stl = open_stlinkv2()
538 raise ValueError("No ST-Link/V2 device found.", None)
540 print "ST-Link/V2 version info: %d %d %d" % stl.version()
542 core_id = stl.core_id()
543 chip_id = stl.read_memory_u32(0xE0042000)
545 # FST-01 chip id: 0x20036410
546 print "CORE: %08x, CHIP_ID: %08x" % (core_id, chip_id)
547 print "Flash ROM read protection:",
548 protection = stl.protection()
554 option_bytes = stl.option_bytes_read()
555 print "Option bytes: %08x" % option_bytes
556 if (option_bytes & 0xff) == RDP_KEY:
557 ob_protection_enable = False
559 ob_protection_enable = True
562 status = stl.get_status()
564 print "Core does not halt, try API V2 halt."
565 # DCB_DHCSR DBGKEY|C_HALT|C_DEBUGEN
566 stl.write_debug_reg(0xE000EDF0, 0xA05F0003)
567 status = stl.get_status()
569 raise ValueError("Status of core is not halt.", status)
573 print "The MCU is now stopped."
576 raise OperationFailure("Flash ROM is protected")
578 if not skip_blank_check:
580 blank = stl.blank_check()
581 print "Flash ROM blank check: %s" % blank
589 elif unlock and not ob_protection_enable:
590 print "No need to unlock. Protection is not enabled."
595 print "No need to erase"
601 if option_bytes != 0xff:
603 stl.option_bytes_erase()
605 stl.option_bytes_write(OPTION_BYTES_ADDR,RDP_KEY)
609 print "Flash ROM read protection disabled. Reset the board, now."
614 id = stl.spi_flash_read_id()
615 print "SPI Flash ROM ID: %06x" % id
617 raise ValueError("bad spi flash ROM ID")
622 stl.flash_erase_all()
633 stl.flash_write(0x08000000, data)
644 data_received = data_received + stl.read_memory(0x08000000+off, 1024)
645 size = size - blk_size
647 compare(data, data_received)
651 stl.option_bytes_erase()
652 print "Flash ROM read protection enabled. Reset the board to enable protection."
654 if reset_after_successful_write:
665 if __name__ == '__main__':
669 reset_after_successful_write = True
670 skip_blank_check=True
674 spi_flash_check = True
676 while len(sys.argv) > 1:
677 if sys.argv[1] == '-h':
681 elif sys.argv[1] == '-e':
684 skip_blank_check=False
686 elif sys.argv[1] == '-u':
690 elif sys.argv[1] == '-s':
693 skip_blank_check=False
695 elif sys.argv[1] == '-b':
696 skip_blank_check=False
697 elif sys.argv[1] == '-n':
699 elif sys.argv[1] == '-r':
700 reset_after_successful_write = False
701 elif sys.argv[1] == '-i':
702 spi_flash_check = False
704 filename = sys.argv[1]
705 f = open(filename,'rb')
713 r = main(show_help, erase_only, no_protect, spi_flash_check,
714 reset_after_successful_write,
715 skip_blank_check, status_only, unlock, data)
717 print Fore.WHITE + Back.BLUE + Style.BRIGHT + "SUCCESS" + Style.RESET_ALL
719 except Exception as e:
720 print Back.RED + Style.BRIGHT + repr(e) + Style.RESET_ALL