-
Notifications
You must be signed in to change notification settings - Fork 3
/
esptoolpy.py
1236 lines (1046 loc) · 51.1 KB
/
esptoolpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# NB: Before sending a PR to change the above line to '#!/usr/bin/env python2', please read https://github.com/themadinventor/esptool/issues/21
#
# ESP8266 ROM Bootloader Utility
# https://github.com/themadinventor/esptool
#
# Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, other contributors as noted.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse
import hashlib
import inspect
import json
import os
import serial
import struct
import subprocess
import sys
import tempfile
import time
__version__ = "1.2-dev"
class ESPROM(object):
# These are the currently known commands supported by the ROM
ESP_FLASH_BEGIN = 0x02
ESP_FLASH_DATA = 0x03
ESP_FLASH_END = 0x04
ESP_MEM_BEGIN = 0x05
ESP_MEM_END = 0x06
ESP_MEM_DATA = 0x07
ESP_SYNC = 0x08
ESP_WRITE_REG = 0x09
ESP_READ_REG = 0x0a
# Maximum block sized for RAM and Flash writes, respectively.
ESP_RAM_BLOCK = 0x1800
ESP_FLASH_BLOCK = 0x400
# Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
ESP_ROM_BAUD = 115200
# First byte of the application image
ESP_IMAGE_MAGIC = 0xe9
# Initial state for the checksum routine
ESP_CHECKSUM_MAGIC = 0xef
# OTP ROM addresses
ESP_OTP_MAC0 = 0x3ff00050
ESP_OTP_MAC1 = 0x3ff00054
ESP_OTP_MAC3 = 0x3ff0005c
# Flash sector size, minimum unit of erase.
ESP_FLASH_SECTOR = 0x1000
def __init__(self, port=0, baud=ESP_ROM_BAUD):
self._port = serial.Serial(port)
self._slip_reader = slip_reader(self._port)
# setting baud rate in a separate step is a workaround for
# CH341 driver on some Linux versions (this opens at 9600 then
# sets), shouldn't matter for other platforms/drivers. See
# https://github.com/themadinventor/esptool/issues/44#issuecomment-107094446
self._port.baudrate = baud
""" Read a SLIP packet from the serial port """
def read(self):
return self._slip_reader.next()
""" Write bytes to the serial port while performing SLIP escaping """
def write(self, packet):
buf = '\xc0' \
+ (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \
+ '\xc0'
self._port.write(buf)
""" Calculate checksum of a blob, as it is defined by the ROM """
@staticmethod
def checksum(data, state=ESP_CHECKSUM_MAGIC):
for b in data:
state ^= ord(b)
return state
""" Send a request and read the response """
def command(self, op=None, data=None, chk=0):
if op is not None:
pkt = struct.pack('<BBHI', 0x00, op, len(data), chk) + data
self.write(pkt)
# tries to get a response until that response has the
# same operation as the request or a retries limit has
# exceeded. This is needed for some esp8266s that
# reply with more sync responses than expected.
for retry in xrange(100):
p = self.read()
if len(p) < 8:
continue
(resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
if resp != 1:
continue
body = p[8:]
if op is None or op_ret == op:
return val, body # valid response received
raise FatalError("Response doesn't match request")
""" Perform a connection test """
def sync(self):
self.command(ESPROM.ESP_SYNC, '\x07\x07\x12\x20' + 32 * '\x55')
for i in xrange(7):
self.command()
""" Try connecting repeatedly until successful, or giving up """
def connect(self):
print 'Connecting...'
for _ in xrange(4):
# issue reset-to-bootloader:
# RTS = either CH_PD or nRESET (both active low = chip in reset)
# DTR = GPIO0 (active low = boot to flasher)
self._port.setDTR(False)
self._port.setRTS(True)
time.sleep(0.05)
self._port.setDTR(True)
self._port.setRTS(False)
time.sleep(0.05)
self._port.setDTR(False)
# worst-case latency timer should be 255ms (probably <20ms)
self._port.timeout = 0.3
for _ in xrange(4):
try:
self._port.flushInput()
self._slip_reader = slip_reader(self._port)
self._port.flushOutput()
self.sync()
self._port.timeout = 5
return
except:
time.sleep(0.05)
raise FatalError('Failed to connect to ESP8266')
""" Read memory address in target """
def read_reg(self, addr):
res = self.command(ESPROM.ESP_READ_REG, struct.pack('<I', addr))
if res[1] != "\0\0":
raise FatalError('Failed to read target memory')
return res[0]
""" Write to memory address in target """
def write_reg(self, addr, value, mask, delay_us=0):
if self.command(ESPROM.ESP_WRITE_REG,
struct.pack('<IIII', addr, value, mask, delay_us))[1] != "\0\0":
raise FatalError('Failed to write target memory')
""" Start downloading an application image to RAM """
def mem_begin(self, size, blocks, blocksize, offset):
if self.command(ESPROM.ESP_MEM_BEGIN,
struct.pack('<IIII', size, blocks, blocksize, offset))[1] != "\0\0":
raise FatalError('Failed to enter RAM download mode')
""" Send a block of an image to RAM """
def mem_block(self, data, seq):
if self.command(ESPROM.ESP_MEM_DATA,
struct.pack('<IIII', len(data), seq, 0, 0) + data,
ESPROM.checksum(data))[1] != "\0\0":
raise FatalError('Failed to write to target RAM')
""" Leave download mode and run the application """
def mem_finish(self, entrypoint=0):
if self.command(ESPROM.ESP_MEM_END,
struct.pack('<II', int(entrypoint == 0), entrypoint))[1] != "\0\0":
raise FatalError('Failed to leave RAM download mode')
""" Start downloading to Flash (performs an erase) """
def flash_begin(self, size, offset):
old_tmo = self._port.timeout
num_blocks = (size + ESPROM.ESP_FLASH_BLOCK - 1) / ESPROM.ESP_FLASH_BLOCK
sectors_per_block = 16
sector_size = self.ESP_FLASH_SECTOR
num_sectors = (size + sector_size - 1) / sector_size
start_sector = offset / sector_size
head_sectors = sectors_per_block - (start_sector % sectors_per_block)
if num_sectors < head_sectors:
head_sectors = num_sectors
if num_sectors < 2 * head_sectors:
erase_size = (num_sectors + 1) / 2 * sector_size
else:
erase_size = (num_sectors - head_sectors) * sector_size
self._port.timeout = 20
t = time.time()
result = self.command(ESPROM.ESP_FLASH_BEGIN,
struct.pack('<IIII', erase_size, num_blocks, ESPROM.ESP_FLASH_BLOCK, offset))[1]
if size != 0:
print "Took %.2fs to erase flash block" % (time.time() - t)
if result != "\0\0":
raise FatalError.WithResult('Failed to enter Flash download mode (result "%s")', result)
self._port.timeout = old_tmo
""" Write block to flash """
def flash_block(self, data, seq):
result = self.command(ESPROM.ESP_FLASH_DATA,
struct.pack('<IIII', len(data), seq, 0, 0) + data,
ESPROM.checksum(data))[1]
if result != "\0\0":
raise FatalError.WithResult('Failed to write to target Flash after seq %d (got result %%s)' % seq, result)
""" Leave flash mode and run/reboot """
def flash_finish(self, reboot=False):
pkt = struct.pack('<I', int(not reboot))
if self.command(ESPROM.ESP_FLASH_END, pkt)[1] != "\0\0":
raise FatalError('Failed to leave Flash mode')
""" Run application code in flash """
def run(self, reboot=False):
# Fake flash begin immediately followed by flash end
self.flash_begin(0, 0)
self.flash_finish(reboot)
""" Read MAC from OTP ROM """
def read_mac(self):
mac0 = self.read_reg(self.ESP_OTP_MAC0)
mac1 = self.read_reg(self.ESP_OTP_MAC1)
mac3 = self.read_reg(self.ESP_OTP_MAC3)
if (mac3 != 0):
oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
elif ((mac1 >> 16) & 0xff) == 0:
oui = (0x18, 0xfe, 0x34)
elif ((mac1 >> 16) & 0xff) == 1:
oui = (0xac, 0xd0, 0x74)
else:
raise FatalError("Unknown OUI")
return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
""" Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """
def chip_id(self):
id0 = self.read_reg(self.ESP_OTP_MAC0)
id1 = self.read_reg(self.ESP_OTP_MAC1)
return (id0 >> 24) | ((id1 & 0xffffff) << 8)
""" Read SPI flash manufacturer and device id """
def flash_id(self):
self.flash_begin(0, 0)
self.write_reg(0x60000240, 0x0, 0xffffffff)
self.write_reg(0x60000200, 0x10000000, 0xffffffff)
flash_id = self.read_reg(0x60000240)
self.flash_finish(False)
return flash_id
""" Abuse the loader protocol to force flash to be left in write mode """
def flash_unlock_dio(self):
# Enable flash write mode
self.flash_begin(0, 0)
# Reset the chip rather than call flash_finish(), which would have
# write protected the chip again (why oh why does it do that?!)
self.mem_begin(0,0,0,0x40100000)
self.mem_finish(0x40000080)
""" Perform a chip erase of SPI flash """
def flash_erase(self):
# Trick ROM to initialize SFlash
self.flash_begin(0, 0)
# This is hacky: we don't have a custom stub, instead we trick
# the bootloader to jump to the SPIEraseChip() routine and then halt/crash
# when it tries to boot an unconfigured system.
self.mem_begin(0,0,0,0x40100000)
self.mem_finish(0x40004984)
# Yup - there's no good way to detect if we succeeded.
# It it on the other hand unlikely to fail.
def run_stub(self, stub, params, read_output=True):
stub = dict(stub)
stub['code'] = unhexify(stub['code'])
if 'data' in stub:
stub['data'] = unhexify(stub['data'])
if stub['num_params'] != len(params):
raise FatalError('Stub requires %d params, %d provided'
% (stub['num_params'], len(params)))
params = struct.pack('<' + ('I' * stub['num_params']), *params)
pc = params + stub['code']
# Upload
self.mem_begin(len(pc), 1, len(pc), stub['params_start'])
self.mem_block(pc, 0)
if 'data' in stub:
self.mem_begin(len(stub['data']), 1, len(stub['data']), stub['data_start'])
self.mem_block(stub['data'], 0)
self.mem_finish(stub['entry'])
if read_output:
print 'Stub executed, reading response:'
while True:
p = self.read()
print hexify(p)
if p == '':
return
class ESPBOOTLOADER(object):
""" These are constants related to software ESP bootloader, working with 'v2' image files """
# First byte of the "v2" application image
IMAGE_V2_MAGIC = 0xea
# First 'segment' value in a "v2" application image, appears to be a constant version value?
IMAGE_V2_SEGMENT = 4
def LoadFirmwareImage(filename):
""" Load a firmware image, without knowing what kind of file (v1 or v2) it is.
Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2).
"""
with open(filename, 'rb') as f:
magic = ord(f.read(1))
f.seek(0)
if magic == ESPROM.ESP_IMAGE_MAGIC:
return ESPFirmwareImage(f)
elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
return OTAFirmwareImage(f)
else:
raise FatalError("Invalid image magic number: %d" % magic)
class BaseFirmwareImage(object):
""" Base class with common firmware image functions """
def __init__(self):
self.segments = []
self.entrypoint = 0
def add_segment(self, addr, data, pad_to=4):
""" Add a segment to the image, with specified address & data
(padded to a boundary of pad_to size) """
# Data should be aligned on word boundary
l = len(data)
if l % pad_to:
data += b"\x00" * (pad_to - l % pad_to)
if l > 0:
self.segments.append((addr, len(data), data))
def load_segment(self, f, is_irom_segment=False):
""" Load the next segment from the image file """
(offset, size) = struct.unpack('<II', f.read(8))
if not is_irom_segment:
if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
raise FatalError('Suspicious segment 0x%x, length %d' % (offset, size))
segment_data = f.read(size)
if len(segment_data) < size:
raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
segment = (offset, size, segment_data)
self.segments.append(segment)
return segment
def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
(offset, size, data) = segment
f.write(struct.pack('<II', offset, size))
f.write(data)
if checksum is not None:
return ESPROM.checksum(data, checksum)
def read_checksum(self, f):
""" Return ESPROM checksum from end of just-read image """
# Skip the padding. The checksum is stored in the last byte so that the
# file is a multiple of 16 bytes.
align_file_position(f, 16)
return ord(f.read(1))
def append_checksum(self, f, checksum):
""" Append ESPROM checksum to the just-written image """
align_file_position(f, 16)
f.write(struct.pack('B', checksum))
def write_v1_header(self, f, segments):
f.write(struct.pack('<BBBBI', ESPROM.ESP_IMAGE_MAGIC, len(segments),
self.flash_mode, self.flash_size_freq, self.entrypoint))
class ESPFirmwareImage(BaseFirmwareImage):
""" 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
def __init__(self, load_file=None):
super(ESPFirmwareImage, self).__init__()
self.flash_mode = 0
self.flash_size_freq = 0
self.version = 1
if load_file is not None:
(magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
# some sanity check
if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
for i in xrange(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
def save(self, filename):
with open(filename, 'wb') as f:
self.write_v1_header(f, self.segments)
checksum = ESPROM.ESP_CHECKSUM_MAGIC
for segment in self.segments:
checksum = self.save_segment(f, segment, checksum)
self.append_checksum(f, checksum)
class OTAFirmwareImage(BaseFirmwareImage):
""" 'Version 2' firmware image, segments loaded by software bootloader stub
(ie Espressif bootloader or rboot)
"""
def __init__(self, load_file=None):
super(OTAFirmwareImage, self).__init__()
self.version = 2
if load_file is not None:
(magic, segments, first_flash_mode, first_flash_size_freq, first_entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
# some sanity check
if magic != ESPBOOTLOADER.IMAGE_V2_MAGIC:
raise FatalError('Invalid V2 image magic=%d' % (magic))
if segments != 4:
# segment count is not really segment count here, but we expect to see '4'
print 'Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments
# irom segment comes before the second header
self.load_segment(load_file, True)
(magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
if first_flash_mode != self.flash_mode:
print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
% (first_flash_mode, self.flash_mode))
if first_flash_size_freq != self.flash_size_freq:
print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
% (first_flash_size_freq, self.flash_size_freq))
if first_entrypoint != self.entrypoint:
print('WARNING: Enterypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
% (first_entrypoint, self.entrypoint))
if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
raise FatalError('Invalid V2 second header magic=%d segments=%d' % (magic, segments))
# load all the usual segments
for _ in xrange(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
def save(self, filename):
with open(filename, 'wb') as f:
# Save first header for irom0 segment
f.write(struct.pack('<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
self.flash_mode, self.flash_size_freq, self.entrypoint))
# irom0 segment identified by load address zero
irom_segments = [segment for segment in self.segments if segment[0] == 0]
if len(irom_segments) != 1:
raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
# save irom0 segment
irom_segment = irom_segments[0]
self.save_segment(f, irom_segment)
# second header, matches V1 header and contains loadable segments
normal_segments = [s for s in self.segments if s != irom_segment]
self.write_v1_header(f, normal_segments)
checksum = ESPROM.ESP_CHECKSUM_MAGIC
for segment in normal_segments:
checksum = self.save_segment(f, segment, checksum)
self.append_checksum(f, checksum)
class ELFFile(object):
def __init__(self, name):
self.name = binutils_safe_path(name)
self.symbols = None
def _fetch_symbols(self):
if self.symbols is not None:
return
self.symbols = {}
try:
tool_nm = "xtensa-lx106-elf-nm"
if os.getenv('XTENSA_CORE') == 'lx106':
tool_nm = "xt-nm"
proc = subprocess.Popen([tool_nm, self.name], stdout=subprocess.PIPE)
except OSError:
print "Error calling %s, do you have Xtensa toolchain in PATH?" % tool_nm
sys.exit(1)
for l in proc.stdout:
fields = l.strip().split()
try:
if fields[0] == "U":
print "Warning: ELF binary has undefined symbol %s" % fields[1]
continue
if fields[0] == "w":
continue # can skip weak symbols
self.symbols[fields[2]] = int(fields[0], 16)
except ValueError:
raise FatalError("Failed to strip symbol output from nm: %s" % fields)
def get_symbol_addr(self, sym):
self._fetch_symbols()
return self.symbols[sym]
def get_entry_point(self):
tool_readelf = "xtensa-lx106-elf-readelf"
if os.getenv('XTENSA_CORE') == 'lx106':
tool_readelf = "xt-readelf"
try:
proc = subprocess.Popen([tool_readelf, "-h", self.name], stdout=subprocess.PIPE)
except OSError:
print "Error calling %s, do you have Xtensa toolchain in PATH?" % tool_readelf
sys.exit(1)
for l in proc.stdout:
fields = l.strip().split()
if fields[0] == "Entry":
return int(fields[3], 0)
def load_section(self, section):
tool_objcopy = "xtensa-lx106-elf-objcopy"
if os.getenv('XTENSA_CORE') == 'lx106':
tool_objcopy = "xt-objcopy"
tmpsection = binutils_safe_path(tempfile.mktemp(suffix=".section"))
try:
subprocess.check_call([tool_objcopy, "--only-section", section, "-Obinary", self.name, tmpsection])
with open(tmpsection, "rb") as f:
data = f.read()
finally:
os.remove(tmpsection)
return data
class CesantaFlasher(object):
# From stub_flasher.h
CMD_FLASH_WRITE = 1
CMD_FLASH_READ = 2
CMD_FLASH_DIGEST = 3
CMD_BOOT_FW = 6
def __init__(self, esp, baud_rate=0):
print 'Running Cesanta flasher stub...'
if baud_rate <= ESPROM.ESP_ROM_BAUD: # don't change baud rates if we already synced at that rate
baud_rate = 0
self._esp = esp
esp.run_stub(json.loads(_CESANTA_FLASHER_STUB), [baud_rate], read_output=False)
if baud_rate > 0:
esp._port.baudrate = baud_rate
# Read the greeting.
p = esp.read()
if p != 'OHAI':
raise FatalError('Failed to connect to the flasher (got %s)' % hexify(p))
def flash_write(self, addr, data, show_progress=False):
assert addr % self._esp.ESP_FLASH_SECTOR == 0, 'Address must be sector-aligned'
assert len(data) % self._esp.ESP_FLASH_SECTOR == 0, 'Length must be sector-aligned'
sys.stdout.write('Writing %d @ 0x%x... ' % (len(data), addr))
sys.stdout.flush()
self._esp.write(struct.pack('<B', self.CMD_FLASH_WRITE))
self._esp.write(struct.pack('<III', addr, len(data), 1))
num_sent, num_written = 0, 0
while num_written < len(data):
p = self._esp.read()
if len(p) == 4:
num_written = struct.unpack('<I', p)[0]
elif len(p) == 1:
status_code = struct.unpack('<B', p)[0]
raise FatalError('Write failure, status: %x' % status_code)
else:
raise FatalError('Unexpected packet while writing: %s' % hexify(p))
if show_progress:
progress = '%d (%d %%)' % (num_written, num_written * 100.0 / len(data))
sys.stdout.write(progress + '\b' * len(progress))
sys.stdout.flush()
while num_sent - num_written < 5120:
self._esp._port.write(data[num_sent:num_sent + 1024])
num_sent += 1024
p = self._esp.read()
if len(p) != 16:
raise FatalError('Expected digest, got: %s' % hexify(p))
digest = hexify(p).upper()
expected_digest = hashlib.md5(data).hexdigest().upper()
print
if digest != expected_digest:
raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
p = self._esp.read()
if len(p) != 1:
raise FatalError('Expected status, got: %s' % hexify(p))
status_code = struct.unpack('<B', p)[0]
if status_code != 0:
raise FatalError('Write failure, status: %x' % status_code)
def flash_read(self, addr, length, show_progress=False):
sys.stdout.write('Reading %d @ 0x%x... ' % (length, addr))
sys.stdout.flush()
self._esp.write(struct.pack('<B', self.CMD_FLASH_READ))
# USB may not be able to keep up with the read rate, especially at
# higher speeds. Since we don't have flow control, this will result in
# data loss. Hence, we use small packet size and only allow small
# number of bytes in flight, which we can reasonably expect to fit in
# the on-chip FIFO. max_in_flight = 64 works for CH340G, other chips may
# have longer FIFOs and could benefit from increasing max_in_flight.
self._esp.write(struct.pack('<IIII', addr, length, 32, 64))
data = ''
while True:
p = self._esp.read()
data += p
self._esp.write(struct.pack('<I', len(data)))
if show_progress and (len(data) % 1024 == 0 or len(data) == length):
progress = '%d (%d %%)' % (len(data), len(data) * 100.0 / length)
sys.stdout.write(progress + '\b' * len(progress))
sys.stdout.flush()
if len(data) == length:
break
if len(data) > length:
raise FatalError('Read more than expected')
p = self._esp.read()
if len(p) != 16:
raise FatalError('Expected digest, got: %s' % hexify(p))
expected_digest = hexify(p).upper()
digest = hashlib.md5(data).hexdigest().upper()
print
if digest != expected_digest:
raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
p = self._esp.read()
if len(p) != 1:
raise FatalError('Expected status, got: %s' % hexify(p))
status_code = struct.unpack('<B', p)[0]
if status_code != 0:
raise FatalError('Write failure, status: %x' % status_code)
return data
def flash_digest(self, addr, length, digest_block_size=0):
self._esp.write(struct.pack('<B', self.CMD_FLASH_DIGEST))
self._esp.write(struct.pack('<III', addr, length, digest_block_size))
digests = []
while True:
p = self._esp.read()
if len(p) == 16:
digests.append(p)
elif len(p) == 1:
status_code = struct.unpack('<B', p)[0]
if status_code != 0:
raise FatalError('Write failure, status: %x' % status_code)
break
else:
raise FatalError('Unexpected packet: %s' % hexify(p))
return digests[-1], digests[:-1]
def boot_fw(self):
self._esp.write(struct.pack('<B', self.CMD_BOOT_FW))
p = self._esp.read()
if len(p) != 1:
raise FatalError('Expected status, got: %s' % hexify(p))
status_code = struct.unpack('<B', p)[0]
if status_code != 0:
raise FatalError('Boot failure, status: %x' % status_code)
def slip_reader(port):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
partial_packet = None
in_escape = False
while True:
waiting = port.inWaiting()
read_bytes = port.read(1 if waiting == 0 else waiting)
if read_bytes == '':
raise FatalError("Timed out waiting for packet %s" % ("header" if partial_packet is None else "content"))
for b in read_bytes:
if partial_packet is None: # waiting for packet header
if b == '\xc0':
partial_packet = ""
else:
raise FatalError('Invalid head of packet (%r)' % b)
elif in_escape: # part-way through escape sequence
in_escape = False
if b == '\xdc':
partial_packet += '\xc0'
elif b == '\xdd':
partial_packet += '\xdb'
else:
raise FatalError('Invalid SLIP escape (%r%r)' % ('\xdb', b))
elif b == '\xdb': # start of escape sequence
in_escape = True
elif b == '\xc0': # end of packet
yield partial_packet
partial_packet = None
else: # normal byte in packet
partial_packet += b
def arg_auto_int(x):
return int(x, 0)
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) / int(b)
def binutils_safe_path(p):
"""Returns a 'safe' version of path 'p' to pass to binutils
Only does anything under Cygwin Python, where cygwin paths need to
be translated to Windows paths if the binutils wasn't compiled
using Cygwin (should also work with binutils compiled using
Cygwin, see #73.)
"""
if sys.platform == "cygwin":
try:
return subprocess.check_output(["cygpath", "-w", p]).rstrip('\n')
except subprocess.CalledProcessError:
print "WARNING: Failed to call cygpath to sanitise Cygwin path."
return p
def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1)
def hexify(s):
return ''.join('%02X' % ord(c) for c in s)
def unhexify(hs):
s = ''
for i in range(0, len(hs) - 1, 2):
s += chr(int(hs[i] + hs[i + 1], 16))
return s
class FatalError(RuntimeError):
"""
Wrapper class for runtime errors that aren't caused by internal bugs, but by
ESP8266 responses or input content.
"""
def __init__(self, message):
RuntimeError.__init__(self, message)
@staticmethod
def WithResult(message, result):
"""
Return a fatal error object that includes the hex values of
'result' as a string formatted argument.
"""
return FatalError(message % ", ".join(hex(ord(x)) for x in result))
# "Operation" commands, executable at command line. One function each
#
# Each function takes either two args (<ESPROM instance>, <args>) or a single <args>
# argument.
def load_ram(esp, args):
image = LoadFirmwareImage(args.filename)
print 'RAM boot...'
for (offset, size, data) in image.segments:
print 'Downloading %d bytes at %08x...' % (size, offset),
sys.stdout.flush()
esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset)
seq = 0
while len(data) > 0:
esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
data = data[esp.ESP_RAM_BLOCK:]
seq += 1
print 'done!'
print 'All segments done, executing at %08x' % image.entrypoint
esp.mem_finish(image.entrypoint)
def read_mem(esp, args):
print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address))
def write_mem(esp, args):
esp.write_reg(args.address, args.value, args.mask, 0)
print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address)
def dump_mem(esp, args):
f = file(args.filename, 'wb')
for i in xrange(args.size / 4):
d = esp.read_reg(args.address + (i * 4))
f.write(struct.pack('<I', d))
if f.tell() % 1024 == 0:
print '\r%d bytes read... (%d %%)' % (f.tell(),
f.tell() * 100 / args.size),
sys.stdout.flush()
print 'Done!'
def write_flash(esp, args):
flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size]
flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
flash_params = struct.pack('BB', flash_mode, flash_size_freq)
flasher = CesantaFlasher(esp, args.baud)
for address, argfile in args.addr_filename:
image = argfile.read()
argfile.seek(0) # rewind in case we need it again
# Fix sflash config data.
if address == 0 and image[0] == '\xe9':
print 'Flash params set to 0x%02x%02x' % (flash_mode, flash_size_freq)
image = image[0:2] + flash_params + image[4:]
# Pad to sector size, which is the minimum unit of writing (erasing really).
if len(image) % esp.ESP_FLASH_SECTOR != 0:
image += '\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR))
t = time.time()
flasher.flash_write(address, image, not args.no_progress)
t = time.time() - t
print ('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
% (len(image), address, t, len(image) / t * 8 / 1000))
print 'Leaving...'
if args.verify:
print 'Verifying just-written flash...'
_verify_flash(flasher, args, flash_params)
flasher.boot_fw()
def image_info(args):
image = LoadFirmwareImage(args.filename)
print('Image version: %d' % image.version)
print('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set'
print '%d segments' % len(image.segments)
print
checksum = ESPROM.ESP_CHECKSUM_MAGIC
for (idx, (offset, size, data)) in enumerate(image.segments):
if image.version == 2 and idx == 0:
print 'Segment 1: %d bytes IROM0 (no load address)' % size
else:
print 'Segment %d: %5d bytes at %08x' % (idx + 1, size, offset)
checksum = ESPROM.checksum(data, checksum)
print
print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!')
def make_image(args):
image = ESPFirmwareImage()
if len(args.segfile) == 0:
raise FatalError('No segments specified')
if len(args.segfile) != len(args.segaddr):
raise FatalError('Number of specified files does not match number of specified addresses')
for (seg, addr) in zip(args.segfile, args.segaddr):
data = file(seg, 'rb').read()
image.add_segment(addr, data)
image.entrypoint = args.entrypoint
image.save(args.output)
def elf2image(args):
e = ELFFile(args.input)
if args.version == '1':
image = ESPFirmwareImage()
else:
image = OTAFirmwareImage()
irom_data = e.load_section('.irom0.text')
if len(irom_data) == 0:
raise FatalError(".irom0.text section not found in ELF file - can't create V2 image.")
image.add_segment(0, irom_data, 16)
image.entrypoint = e.get_entry_point()
for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")):
data = e.load_section(section)
image.add_segment(e.get_symbol_addr(start), data)
image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size]
image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
irom_offs = e.get_symbol_addr("_irom0_text_start") - 0x40200000
if args.version == '1':
if args.output is None:
args.output = args.input + '-'
image.save(args.output + "0x00000.bin")
data = e.load_section(".irom0.text")
if irom_offs < 0:
raise FatalError('Address of symbol _irom0_text_start in ELF is located before flash mapping address. Bad linker script?')
if (irom_offs & 0xFFF) != 0: # irom0 isn't flash sector aligned
print "WARNING: irom0 section offset is 0x%08x. ELF is probably linked for 'elf2image --version=2'" % irom_offs
with open(args.output + "0x%05x.bin" % irom_offs, "wb") as f:
f.write(data)
f.close()
else: # V2 OTA image
if args.output is None:
args.output = "%s-0x%05x.bin" % (os.path.splitext(args.input)[0], irom_offs & ~(ESPROM.ESP_FLASH_SECTOR - 1))
image.save(args.output)
def read_mac(esp, args):
mac = esp.read_mac()
print 'MAC: %s' % ':'.join(map(lambda x: '%02x' % x, mac))
def chip_id(esp, args):
chipid = esp.chip_id()
print 'Chip ID: 0x%08x' % chipid
def erase_flash(esp, args):
print 'Erasing flash (this may take a while)...'
esp.flash_erase()
def run(esp, args):
esp.run()
def flash_id(esp, args):
flash_id = esp.flash_id()
print 'Manufacturer: %02x' % (flash_id & 0xff)
print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff)
def read_flash(esp, args):
flasher = CesantaFlasher(esp, args.baud)
t = time.time()
data = flasher.flash_read(args.address, args.size, not args.no_progress)
t = time.time() - t
print ('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
% (len(data), args.address, t, len(data) / t * 8 / 1000))
file(args.filename, 'wb').write(data)
def _verify_flash(flasher, args, flash_params=None):
differences = False
for address, argfile in args.addr_filename:
image = argfile.read()
argfile.seek(0) # rewind in case we need it again
if address == 0 and image[0] == '\xe9' and flash_params is not None:
image = image[0:2] + flash_params + image[4:]
image_size = len(image)
print 'Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name)
# Try digest first, only read if there are differences.
digest, _ = flasher.flash_digest(address, image_size)
digest = hexify(digest).upper()
expected_digest = hashlib.md5(image).hexdigest().upper()
if digest == expected_digest:
print '-- verify OK (digest matched)'
continue
else:
differences = True
if getattr(args, 'diff', 'no') != 'yes':
print '-- verify FAILED (digest mismatch)'
continue
flash = flasher.flash_read(address, image_size)
assert flash != image
diff = [i for i in xrange(image_size) if flash[i] != image[i]]
print '-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0])
for d in diff:
print ' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d]))
if differences:
raise FatalError("Verify failed.")
def verify_flash(esp, args, flash_params=None):
flasher = CesantaFlasher(esp)
_verify_flash(flasher, args, flash_params)
def version(args):
print __version__
#
# End of operations functions