forked from memfault/memfault-firmware-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memfault_gdb.py
1750 lines (1453 loc) · 64.8 KB
/
memfault_gdb.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
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019, Memfault
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code or in binary form must reproduce
# the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the
# distribution.
#
# 2. Neither the name of Memfault nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# 3. This software, with or without modification, must only be used with
# the Memfault services and integrated with the Memfault server.
#
# 4. Any software provided in binary form under this license must not be
# reverse engineered, decompiled, modified and/or disassembled.
#
# THIS SOFTWARE IS PROVIDED BY MEMFAULT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL MEMFAULT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
import argparse
import os
import platform
import re
import sys
import traceback
import uuid
from binascii import b2a_base64
from hashlib import md5
from json import dump, dumps, load, loads
from os.path import expanduser
from struct import pack, unpack
from tempfile import TemporaryFile
from threading import Thread
from time import sleep, time
try:
import gdb
except ImportError:
error_str = """
This script can only be run within gdb!
"""
raise Exception(error_str)
# Note: not using `requests` but using the built-in http.client instead, so
# there will be no additional dependencies other than Python itself.
try:
from httplib import HTTPConnection, HTTPSConnection
from Queue import Queue
from urlparse import urlparse, urlunparse
except ImportError:
from http.client import HTTPConnection, HTTPSConnection
from queue import Queue
from urllib.parse import urlparse, urlunparse
MEMFAULT_DEFAULT_INGRESS_BASE_URI = "https://ingress.memfault.com"
MEMFAULT_DEFAULT_CHUNKS_BASE_URI = "https://chunks.memfault.com"
MEMFAULT_DEFAULT_API_BASE_URI = "https://api.memfault.com"
MEMFAULT_TRY_INGRESS_BASE_URI = "https://ingress.try.memfault.com"
MEMFAULT_TRY_API_BASE_URI = "https://api.try.memfault.com"
try:
# In Python 3.x, raw_input was renamed to input
# NOTE: Python 2.x also had an input() function which eval'd the input...!
input = raw_input
except NameError:
pass
class MemfaultConfig(object):
ingress_uri = MEMFAULT_DEFAULT_INGRESS_BASE_URI
api_uri = MEMFAULT_DEFAULT_API_BASE_URI
email = None
password = None
organization = None
project = None
user_id = None
# indirection so tests can mock this
prompt = input
# Added `json_path` and `input` as attributes on the config to aid unit testing:
json_path = expanduser("~/.memfault/gdb.json")
def can_make_project_api_request(self):
return self.email and self.password and self.project and self.organization
MEMFAULT_CONFIG = MemfaultConfig()
def register_value_to_bytes(gdb_scalar_value, little_endian=True):
"""
This helper is meant to be used with values that are not addressable, i.e. registers.
If you've got an addressable value, it's probably faster/better to use the Inferior.read_memory() API.
"""
# try to get the int representation of the value from gdb via py-value.c valpy_long/ valpy_int
#
# If that fails, fallback to parsing the string. Older versions of the GDB python API
# can't do int conversions on certain types such as pointers which some registers get
# defined as (i.e pc & sp)
try:
value_as_int = int(gdb_scalar_value)
except gdb.error:
# register string representation can look something like: "0x17d8 <__start>"
value_as_str = str(gdb_scalar_value).split()[0]
value_as_int = int(value_as_str, 0)
# if the value we get back from gdb python is negative, use the signed representation instead
# of the unsigned representation
#
# We represent all registers in the kMfltCoredumpBlockType_CurrentRegisters section of the coredump as 32 bit values (MfltCortexMRegs) so try
# to convert to a 4 byte representation regardless of the width reported by the gdb-server
fmt = "i" if value_as_int < 0 else "I"
return pack(fmt, value_as_int)
def _get_register_value(reglist, name):
return unpack("<I", reglist[name])[0]
def _pc_in_vector_table(register_list, exception_number, analytics_props):
try:
# The VTOR is implemented on armv6m and up though on chips like the Cortex-M0,
# it will always read as 0
vtor, _ = _read_register(0xE000ED08)
curr_pc = _get_register_value(register_list, "pc")
exc_handler, _ = _read_register(0x0 + vtor + (exception_number * 4))
exc_handler &= ~0x1 # Clear thumb bit
return exc_handler == curr_pc
except Exception: # noqa
analytics_props["pc_in_vtor_check_error"] = {"traceback": traceback.format_exc()}
return False
def check_and_patch_reglist_for_fault(register_list, analytics_props):
# Fault exceptions on armv6m, armv7m, & armv8m will fall between 2 and 10
exception_number = _get_register_value(register_list, "xpsr") & 0xF
analytics_props["exception_number"] = exception_number
if exception_number < 2 or exception_number > 10:
# Not in an exception so keep the register list we already have
return
# If we have faulted it's typically useful to get the backtrace for the code where the fault
# originated. The integrated memfault-firmware-sdk does this by installing into the fault
# handlers and capturing the necessary registers. For the try script, we'll try to apply the
# same logic
FAULT_START_PROMPT = """
We see you are trying out Memfault from a Fault handler. That's great!
For the best results and to mirror the behavior of our firmware SDK,
please run "memfault coredump" at exception entry before other code has run
in the exception handler
"""
GDB_HOW_TO_FAULT_PROMPT = """
It's easy to halt at exception entry by installing a breakpoint from gdb.
For example,
(gdb) breakpoint HardFault_Handler
"""
exc_return = _get_register_value(register_list, "lr")
if exc_return >> 28 != 0xF:
print("{} {}".format(FAULT_START_PROMPT, GDB_HOW_TO_FAULT_PROMPT))
raise Exception("LR no longer set to EXC_RETURN value")
# DCRS - armv8m only - only relevant when chaining secure and non-secure exceptions
# so pretty unlikely to be hit in a try test scenario
if exc_return & (1 << 5) == 0:
raise Exception("DCRS exception unwinding unimplemented")
if not _pc_in_vector_table(register_list, exception_number, analytics_props):
analytics_props["displayed_fault_prompt"] = True
# The pc is not at the start of the exception handler. Some firmware implementations
# will redirect the vector table to a software vector table. If that's the case, it's
# hard to detect programmatically, let's check in with the user
y = MEMFAULT_CONFIG.prompt(
"{}\nAre you currently at the start of an exception handler [y/n]?".format(
FAULT_START_PROMPT
)
)
if "Y" not in y.upper():
print(GDB_HOW_TO_FAULT_PROMPT)
raise Exception("User did not confirm being at beginning of exception")
else:
analytics_props["displayed_fault_prompt"] = False
sp_name = "psp" if (exc_return & 0x4 != 0) else "msp"
sp = _get_register_value(register_list, sp_name)
# restore the register state prior to exception entry so we get an unwind
# from where the exception actually occurred
exception_frame = ("r0", "r1", "r2", "r3", "r12", "lr", "pc", "xpsr")
for idx, r in enumerate(exception_frame):
_, data = _read_register(sp + idx * 4)
register_list[r] = data
orig_sp_offset = 0x68 if (exc_return & (1 << 4) == 0) else 0x20
if _get_register_value(register_list, "xpsr") & (1 << 9) != 0:
orig_sp_offset += 0x4
register_list["sp"] = pack("<I", sp + orig_sp_offset)
def is_debug_info_section(section):
return section.name.startswith(".debug_")
def should_capture_section(section):
if section.size == 0:
return False
# Assuming we never want to grab .text:
if section.name == ".text":
return False
# Assuming we never want to grab debug info:
if is_debug_info_section(section):
return False
# Sometimes these get flagged incorrectly as READONLY:
if filter(lambda n: n in section.name, (".heap", ".bss", ".data", ".stack")):
return True
# Only grab non-readonly stuff:
return not section.read_only
class CoredumpArch(object):
pass
class XtensaCoredumpArch(CoredumpArch):
MACHINE_TYPE = 94 # XTENSA
@property
def num_cores(self):
return 2
@property
def register_collection_list(self):
# The order in which we collect XTENSA registers in a crash
# fmt: off
return (
# We use the first word to convey what registers are collected in the coredump
"collection_type",
# Actual registers
"pc", "ps", "ar0", "ar1", "ar2", "ar3", "ar4", "ar5", "ar6", "ar7", "ar8", "ar9",
"ar10", "ar11", "ar12", "ar13", "ar14", "ar15", "ar16", "ar17", "ar18", "ar19", "ar20",
"ar21", "ar22", "ar23", "ar24", "ar25", "ar26", "ar27", "ar28", "ar29", "ar30", "ar31",
"ar32", "ar33", "ar34", "ar35", "ar36", "ar37", "ar38", "ar39", "ar40", "ar41", "ar42",
"ar43", "ar44", "ar45", "ar46", "ar47", "ar48", "ar49", "ar50", "ar51", "ar52", "ar53",
"ar54", "ar55", "ar56", "ar57", "ar58", "ar59", "ar60", "ar61", "ar62", "ar63", "sar",
# Note: Only enabled for xtensa targets which define XCHAL_HAVE_LOOPS
"lbeg",
"lend",
"lcount",
# Special registers to collect
"windowbase",
"windowstart",
)
# fmt: on
@property
def alternative_register_name_dict(self):
return {}
def add_platform_specific_sections(self, cd_writer, inferior, analytics_props):
pass
def guess_ram_regions(self, elf_sections):
# TODO: support esp32-s2 & esp8266
# For now we just use the memory map from the esp32 for xtensa
# Memory map:
# https://github.com/espressif/esp-idf/blob/v3.3.1/components/soc/esp32/include/soc/soc.h#L286-L304
regions = (
# SOC_DRAM
(0x3FFAE000, 0x52000),
# SOC_RTC_DATA
(0x50000000, 0x2000),
# SOC_RTC_DRAM
(0x3FF80000, 0x2000),
)
return regions
def _read_registers(self, core, gdb_thread, analytics_props):
# NOTE: The only way I could figure out to read raw registers for CPU1 was
# to send the raw gdb command,"g" after explicitly setting the active core
gdb.execute("mon set_core {}".format(core))
registers = gdb.execute("maintenance packet g", to_string=True)
registers = registers.split("received: ")[1].replace('"', "")
# The order GDB sends xtensa registers (for esp32) in:
# https://github.com/espressif/xtensa-overlays/blob/master/xtensa_esp32/gdb/gdb/regformats/reg-xtensa.dat#L3-L107
# fmt: off
xtensa_gdb_idx_regs = (
"pc", "ar0", "ar1", "ar2", "ar3", "ar4", "ar5", "ar6", "ar7",
"ar8", "ar9", "ar10", "ar11", "ar12", "ar13", "ar14", "ar15", "ar16", "ar17", "ar18",
"ar19", "ar20", "ar21", "ar22", "ar23", "ar24", "ar25", "ar26", "ar27", "ar28", "ar29",
"ar30", "ar31", "ar32", "ar33", "ar34", "ar35", "ar36", "ar37", "ar38", "ar39", "ar40",
"ar41", "ar42", "ar43", "ar44", "ar45", "ar46", "ar47", "ar48", "ar49", "ar50", "ar51",
"ar52", "ar53", "ar54", "ar55", "ar56", "ar57", "ar58", "ar59", "ar60", "ar61", "ar62",
"ar63", "lbeg", "lend", "lcount", "sar", "windowbase", "windowstart", "configid0",
"configid1", "ps", "threadptr", "br", "scompare1", "acclo", "acchi", "m0", "m1", "m2",
"m3", "expstate", "f64r_lo", "f64r_hi", "f64s", "f0", "f1", "f2", "f3", "f4", "f5",
"f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "fcr", "fsr",
)
# fmt: on
# Scoop up all register values
vals = []
for i in range(0, len(xtensa_gdb_idx_regs)):
start_idx = i * 8
hexstr = registers[start_idx : start_idx + 8]
vals.append(bytearray.fromhex(hexstr))
register_list = {}
for register_name in self.register_collection_list:
# A "special" value we use to convey what ESP32 registers were collected
if register_name == "collection_type":
# A value of 0 means we collected the full set of windows. When a debugger is
# active, some register windows may not have been spilled to the stack so we need
# all the windows.
register_list[register_name] = bytearray.fromhex("00000000")
continue
idx = xtensa_gdb_idx_regs.index(register_name)
register_list[register_name] = vals[idx]
return register_list
def get_current_registers(self, gdb_thread, analytics_props):
result = []
try:
for core_id in range(0, self.num_cores):
result.append(self._read_registers(core_id, gdb_thread, analytics_props))
except Exception: # noqa
analytics_props["core_reg_collection_error"] = {"traceback": traceback.format_exc()}
return result
class ArmCortexMCoredumpArch(CoredumpArch):
MACHINE_TYPE = 40 # ARM
@property
def num_cores(self):
return 1
@property
def register_collection_list(self):
# The order in which we collect ARM registers in a crash
return (
"r0",
"r1",
"r2",
"r3",
"r4",
"r5",
"r6",
"r7",
"r8",
"r9",
"r10",
"r11",
"r12",
"sp",
"lr",
"pc", # 15
"xpsr",
"msp",
"psp",
"primask",
"control",
)
@property
def alternative_register_name_dict(self):
# GDB allows the remote server to provide register names via the target description which can
# be exchanged between client and server:
# https://sourceware.org/gdb/onlinedocs/gdb/Target-Description-Format.html#Target-Description-Format
#
# Different implementations of the gdb server use different names for these custom register sets
# This dictionary holds known mappings between the names we will use and the ones in different GDBDebugContextFacade
# server implementations
#
# NOTE: If the only difference is capitalization, that will be automagically resolved below
return {"xpsr": ("cpsr",)}
@staticmethod
def _try_collect_mpu_settings():
cpuid = 0xE000ED00
reg_val, _ = _read_register(cpuid)
partno = (reg_val >> 4) & 0xFFF
CORTEX_M_CPUIDS = {
0xC20: "M0",
0xC21: "M1",
0xC23: "M3",
0xC24: "M4",
0xC27: "M7",
0xC60: "M0+",
}
if partno not in CORTEX_M_CPUIDS:
return None
print("Cortex-{} detected".format(CORTEX_M_CPUIDS[partno]))
mpu_type = 0xE000ED90
mpu_ctrl = 0xE000ED94
mpu_rnr = 0xE000ED98
mpu_rbar = 0xE000ED9C
mpu_rasr = 0xE000EDA0
result = b""
mpu_type, mpu_type_data = _read_register(mpu_type)
result += mpu_type_data
mpu_ctrl, mpu_ctrl_data = _read_register(mpu_ctrl)
result += mpu_ctrl_data
num_regions = (mpu_type >> 8) & 0xFF
for i in range(0, num_regions):
_write_register(mpu_rnr, i)
_, data = _read_register(mpu_rbar)
result += data
_, data = _read_register(mpu_rasr)
result += data
return result
def add_platform_specific_sections(self, cd_writer, inferior, analytics_props):
mem_mapped_regs = [
("ictr", "Interrupt Controller Type Register", 0xE000E004, 0xE000E008),
("systick", "ARMv7-M System Timer", 0xE000E010, 0xE000E020),
("scb", "ARMv7-M System Control Block", 0xE000ED00, 0xE000ED8F),
("scs_debug", "ARMv7-M SCS Debug Registers", 0xE000EDFC, 0xE000EE00),
("nvic", "ARMv7-M External Interrupt Controller", 0xE000E100, 0xE000E600),
]
for mem_mapped_reg in mem_mapped_regs:
try:
short_name, desc, base, top = mem_mapped_reg
section = Section(base, top - base, desc)
section.data = inferior.read_memory(section.addr, section.size)
cd_writer.add_section(section)
analytics_props["{}_ok".format(short_name)] = True
except Exception: # noqa
analytics_props["{}_collection_error".format(short_name)] = {
"traceback": traceback.format_exc()
}
try:
cd_writer.armv67_mpu = self._try_collect_mpu_settings()
print("Collected MPU config")
except Exception: # noqa
analytics_props["mpu_collection_error"] = {"traceback": traceback.format_exc()}
def guess_ram_regions(self, elf_sections):
capturable_elf_sections = list(filter(should_capture_section, elf_sections))
def _is_ram(base_addr):
# See Table B3-1 ARMv7-M address map in "ARMv7-M Architecture Reference Manual"
return base_addr in (0x20000000, 0x60000000, 0x80000000)
capture_size = 1024 * 1024 # Capture up to 1MB
base_addrs = map(lambda section: section.addr & 0xE0000000, capturable_elf_sections)
filtered_addrs = set(filter(_is_ram, base_addrs))
# Capture up to 1MB for each region
return [(addr, capture_size) for addr in filtered_addrs]
def get_current_registers(self, gdb_thread, analytics_props):
gdb_thread.switch()
# GDB Doesn't have a convenient way to know all of the registers in Python, so this is the
# best way. Call this, rip out the first element in each row...that's the register name
#
# NOTE: We use the "all" argument below because on some versions of gdb "msp, psp, etc" are not considered part of them
# core set. This will also dump all the fpu registers which we don't collect but thats fine
info_reg_all_list = gdb.execute("info reg all", to_string=True)
return (lookup_registers_from_list(self, info_reg_all_list, analytics_props),)
# FIXME: De-duplicate with code from rtos_register_stacking.py
def concat_registers_dict_to_bytes(arch, regs):
result = b""
for reg_name in arch.register_collection_list:
assert reg_name.lower() == reg_name
if reg_name not in regs:
result += b"\x00\x00\x00\x00"
continue
result += regs[reg_name]
return result
def _is_expected_reg(arch, reg_name):
return reg_name in arch.register_collection_list
def _add_reg_collection_error_analytic(arch, analytics_props, reg_name, error):
if not _is_expected_reg(arch, reg_name):
return
REG_COLLECTION_ERROR = "reg_collection_error"
if REG_COLLECTION_ERROR not in analytics_props:
analytics_props[REG_COLLECTION_ERROR] = {}
analytics_props[REG_COLLECTION_ERROR][reg_name] = error
def _try_read_register(arch, frame, lookup_name, register_list, analytics_props, result_name=None):
# `info reg` will print all registers, even though they are not part of the core.
# If that's the case, doing frame.read_register() will raise a gdb.error.
try:
if hasattr(frame, "read_register"):
value = frame.read_register(lookup_name)
else:
# GCC <= 4.9 doesn't have the read_register API
value = gdb.parse_and_eval("${}".format(lookup_name))
value_str = str(value)
if value_str != "<unavailable>":
name_to_use = lookup_name if result_name is None else result_name
register_list[name_to_use] = register_value_to_bytes(value)
else:
_add_reg_collection_error_analytic(
arch, analytics_props, lookup_name, "<unavailable> value"
)
except Exception: # noqa
_add_reg_collection_error_analytic(
arch, analytics_props, lookup_name, traceback.format_exc()
)
pass
def lookup_registers_from_list(arch, info_reg_all_list, analytics_props):
frame = gdb.newest_frame()
frame.select()
register_names = []
for reg_row in info_reg_all_list.strip().split("\n"):
name = reg_row.split()[0]
register_names.append(name)
def _search_list_for_alt_name(reg, found_registers):
# first see if it's just case getting in the way i.e 'CONTROL' instead of 'control'. We
# need to preserve case when we actually issue the read so the gdb API works correctly
for found_reg in found_registers:
if found_reg.lower() == reg:
return found_reg
alt_reg_names = arch.alternative_register_name_dict.get(reg, [])
for alt_reg_name in alt_reg_names:
if alt_reg_name in found_registers:
return alt_reg_name
return None
alt_reg_names = []
for expected_reg in arch.register_collection_list:
if expected_reg in register_names:
continue
alt_reg_name = _search_list_for_alt_name(expected_reg, register_names)
if alt_reg_name:
alt_reg_names.append((alt_reg_name, expected_reg))
continue
_add_reg_collection_error_analytic(
arch, analytics_props, expected_reg, "Not found in register set"
)
# Iterate over all register names and pull the value out of the frame
register_list = {}
# Remove register_names we don't care about before actually looking up values
register_names = filter(lambda n: _is_expected_reg(arch, n), register_names)
for reg_name in register_names:
_try_read_register(arch, frame, reg_name, register_list, analytics_props)
for lookup_reg_name, result_reg_name in alt_reg_names:
_try_read_register(
arch, frame, lookup_reg_name, register_list, analytics_props, result_reg_name
)
# if we can't patch the registers, we'll just fallback to the active state
try:
check_and_patch_reglist_for_fault(register_list, analytics_props)
except Exception: # noqa
analytics_props["fault_register_recover_error"] = {"traceback": traceback.format_exc()}
pass
return register_list
# FIXME: De-duplicate with code from core_convert.py
MEMFAULT_COREDUMP_MAGIC = 0x45524F43
MEMFAULT_COREDUMP_VERSION = 1
MEMFAULT_COREDUMP_FILE_HEADER_FMT = "<III" # magic, version, file length (incl. file header)
MEMFAULT_COREDUMP_BLOCK_HEADER_FMT = "<bxxxII" # type, address, block payload length
class MemfaultCoredumpBlockType(object): # (IntEnum): # trying to be python2.7 compatible
CURRENT_REGISTERS = 0
MEMORY_REGION = 1
DEVICE_SERIAL = 2
FIRMWARE_VERSION = 3
HARDWARE_REVISION = 4
TRACE_REASON = 5
PADDING_REGION = 6
MACHINE_TYPE = 7
VENDOR_COREDUMP_ESP_IDF_V2_TO_V3_1 = 8
ARM_V7M_MPU = 9
SOFTWARE_VERSION = 10
SOFTWARE_TYPE = 11
class MemfaultCoredumpWriter(object):
def __init__(self, arch):
self.device_serial = "DEMOSERIALNUMBER"
self.software_version = "1.0.0"
self.software_type = "main"
self.hardware_revision = "DEVBOARD"
self.trace_reason = 5 # Debugger Halted
self.regs = {}
self.sections = []
self.armv67_mpu = None
self.arch = arch
def add_section(self, section):
self.sections.append(section)
def _write(self, write, file_length=0):
# file header:
write(
pack(
MEMFAULT_COREDUMP_FILE_HEADER_FMT,
MEMFAULT_COREDUMP_MAGIC,
MEMFAULT_COREDUMP_VERSION,
file_length,
)
)
def _write_block(type, payload, address=0):
write(pack(MEMFAULT_COREDUMP_BLOCK_HEADER_FMT, type, address, len(payload)))
write(payload)
for core_regs in self.regs:
_write_block(
MemfaultCoredumpBlockType.CURRENT_REGISTERS,
concat_registers_dict_to_bytes(self.arch, core_regs),
)
_write_block(MemfaultCoredumpBlockType.DEVICE_SERIAL, self.device_serial.encode("utf8"))
_write_block(
MemfaultCoredumpBlockType.SOFTWARE_VERSION, self.software_version.encode("utf8")
)
_write_block(MemfaultCoredumpBlockType.SOFTWARE_TYPE, self.software_type.encode("utf8"))
_write_block(
MemfaultCoredumpBlockType.HARDWARE_REVISION, self.hardware_revision.encode("utf8")
)
_write_block(MemfaultCoredumpBlockType.MACHINE_TYPE, pack("<I", self.arch.MACHINE_TYPE))
_write_block(MemfaultCoredumpBlockType.TRACE_REASON, pack("<I", self.trace_reason))
# Record the time in a fake memory region. By doing this we guarantee a unique coredump
# will be generated each time "memfault coredump" is run. This makes it easier to discover
# the de-duplication logic get run by the Memfault backend
time_data = pack("<I", int(time()))
_write_block(MemfaultCoredumpBlockType.MEMORY_REGION, time_data, 0xFFFFFFFC)
for section in self.sections:
_write_block(MemfaultCoredumpBlockType.MEMORY_REGION, section.data, section.addr)
if self.armv67_mpu:
_write_block(MemfaultCoredumpBlockType.ARM_V7M_MPU, self.armv67_mpu)
def write(self, out_f):
# Count the total size first:
total_size = {"size": 0}
def _counting_write(data):
# nonlocal total_size # Not python 2.x compatible :(
# total_size += len(data)
total_size["size"] = total_size["size"] + len(data)
self._write(_counting_write)
# Actually write out to the file:
self._write(out_f.write, total_size["size"])
class Section(object):
def __init__(self, addr, size, name, read_only=True):
self.addr = addr
self.size = size
self.name = name
self.read_only = read_only
self.data = b""
def __eq__(self, other):
return (
self.addr == other.addr
and self.size == other.size
and self.name == other.name
and self.read_only == other.read_only
and self.data == other.data
)
def parse_maintenance_info_sections(output):
fn_match = re.search(r"`([^']+)', file type", output)
if fn_match is None:
return None, None
# Using groups() here instead of fn_match[1] for python2.x compatibility
fn = fn_match.groups()[0]
# Grab start addr, end addr, name and flags for each section line:
# [2] 0x6b784->0x6b7a8 at 0x0004b784: .gnu_build_id ALLOC LOAD READONLY DATA HAS_CONTENTS
section_matches = re.findall(
r"\s+\[\d+\]\s+(0x[\da-fA-F]+)[^0]+(0x[\da-fA-F]+)[^:]+: ([^ ]+) (.*)$",
output,
re.MULTILINE,
)
def _tuple_to_section(tpl):
addr = int(tpl[0], base=16)
size = int(tpl[1], base=16) - addr
name = tpl[2]
read_only = "READONLY" in tpl[3]
return Section(addr, size, name, read_only)
sections = map(_tuple_to_section, section_matches)
return fn, list(sections)
def read_memory_until_error(inferior, start, size, read_size=4 * 1024):
data = b""
end = start + size
try:
for addr in range(start, end, read_size):
data += bytes(inferior.read_memory(addr, min(read_size, end - addr)))
except Exception as e: # Catch gdbserver read exceptions -- not sure what exception classes can get raised here
print(e)
return data
def _create_http_connection(base_uri):
url = urlparse(base_uri)
if url.hostname is None:
raise Exception("Invalid base URI, must be http(s)://hostname")
if url.scheme == "http":
conn_class = HTTPConnection
default_port = 80
else:
conn_class = HTTPSConnection
default_port = 443
port = url.port if url.port else default_port
return conn_class(url.hostname, port=port)
def _http(method, base_uri, path, headers=None, body=None):
if headers is None:
headers = {}
conn = _create_http_connection(base_uri)
# Convert to a string/bytes object so 'Content-Length' is set appropriately
# Python 2.7 uses this by default but 3.6 & up were using 'chunked'
if sys.version_info.major >= 3 and hasattr(body, "read"):
body = body.read()
conn.request(method, path, body=body, headers=headers)
response = conn.getresponse()
status = response.status
reason = response.reason
body = response.read()
try:
json_body = loads(body)
except Exception: # noqa
json_body = None
conn.close()
return status, reason, json_body
def add_basic_auth(user, password, headers=None):
headers = dict(headers) if headers else {}
headers["Authorization"] = "Basic {}".format(
b2a_base64("{}:{}".format(user, password).encode("utf8")).decode("ascii").strip()
)
return headers
class HttpApiError(Exception):
def __init__(self, status, reason):
super(Exception, self).__init__("{} (HTTP {})".format(reason, status))
def _check_http_response(status, reason):
if status < 200 or status >= 300:
raise HttpApiError(status, reason)
def _http_api(config, method, path, headers=None, body=None, should_raise=False):
headers = add_basic_auth(config.email, config.password, headers=headers)
status, reason, body = _http(method, config.api_uri, path, headers, body)
if should_raise:
_check_http_response(status, reason)
return status, reason, body
def http_post_coredump(coredump_file, project_key, ingress_uri):
headers = {"Content-Type": "application/octet-stream", "Memfault-Project-Key": project_key}
status, reason, _ = _http(
"POST", ingress_uri, "/api/v0/upload/coredump", headers=headers, body=coredump_file
)
return status, reason
def http_post_chunk(chunk_data_file, project_key, chunks_uri, device_serial):
headers = {"Content-Type": "application/octet-stream", "Memfault-Project-Key": project_key}
status, reason, _ = _http(
"POST",
chunks_uri,
"/api/v0/chunks/{}".format(device_serial),
headers=headers,
body=chunk_data_file,
)
return status, reason
def http_get_auth_me(api_uri, email, password):
headers = add_basic_auth(email, password)
return _http("GET", api_uri, "/auth/me", headers=headers)
def http_get_prepared_url(config):
_, _, body = _http_api(
config,
"POST",
"/api/v0/organizations/{organization}/projects/{project}/upload".format(
organization=config.organization,
project=config.project,
),
headers={"Accept": "application/json"},
should_raise=True,
)
data = body["data"]
return data["token"], data["upload_url"]
def http_upload_file(config, file_readable):
token, upload_url = http_get_prepared_url(config)
url_parts = urlparse(upload_url)
base_uri = urlunparse((url_parts[0], url_parts[1], "", "", "", ""))
path = urlunparse(("", "", url_parts[2], url_parts[3], url_parts[4], url_parts[5]))
status, reason, _ = _http(
"PUT",
base_uri,
path,
# NB: Prepared upload API does not expect Content-Type to be set so
# we need to exclude the Content-Type or set it to an empty string
headers={"Content-Type": ""},
body=file_readable,
)
_check_http_response(status, reason)
return token
def http_upload_symbol_file(config, artifact_readable, software_type, software_version):
token = http_upload_file(config, artifact_readable)
_http_api(
config,
"POST",
"/api/v0/organizations/{organization}/projects/{project}/symbols".format(
organization=config.organization,
project=config.project,
),
headers={"Content-Type": "application/json", "Accept": "application/json"},
body=dumps(
{
"file": {"token": token, "name": "symbols.elf"},
"software_version": {
"version": software_version,
"software_type": software_type,
},
}
),
should_raise=True,
)
def http_get_software_version(config, software_type, software_version):
SOFTWARE_VERSION_URL = "/api/v0/organizations/{organization}/projects/{project}/software_types/{software_type}/software_versions/{software_version}".format(
organization=config.organization,
project=config.project,
software_type=software_type,
software_version=software_version,
)
status, reason, body = _http_api(config, "GET", SOFTWARE_VERSION_URL)
if status < 200 or status >= 300:
return None
return body["data"]
def http_get_project_key(config):
status, reason, body = _http_api(
config,
"GET",
"/api/v0/organizations/{organization}/projects/{project}/api_key".format(
organization=config.organization, project=config.project
),
headers={"Accept": "application/json"},
)
if status < 200 or status >= 300:
return None, (status, reason)
return body["data"]["api_key"], None
def get_file_hash(fn):
with open(fn, "rb") as f:
return md5(f.read()).hexdigest()
def has_uploaded_symbols(config, software_type, software_version):
software_version_obj = http_get_software_version(config, software_type, software_version)
if not software_version_obj:
return False
artifacts = software_version_obj["artifacts"]
return any(map(lambda artifact: artifact["type"] == "symbols", artifacts))
def upload_symbols_if_needed(config, elf_fn, software_type, software_version):
has_symbols = has_uploaded_symbols(config, software_type, software_version)
if has_symbols:
print("Symbols have already been uploaded, skipping!")
return
if not has_symbols:
print("Uploading symbols...")
with open(elf_fn, "rb") as elf_f:
try:
http_upload_symbol_file(config, elf_f, software_type, software_version)
# NOTE: upload is processed asynchronously. Give the symbol file
# a little time to be processed. In the future, we could poll here
# for completion
sleep(0.3)
print("Done!")
except HttpApiError as e:
print("Failed to upload symbols: {}".format(e))
# FIXME: Duped from tools/gdb_memfault.py
class MemfaultGdbArgumentParseError(Exception):
pass
class MemfaultGdbArgumentParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
if message:
self._print_message(message)
# Don't call sys.exit()
raise MemfaultGdbArgumentParseError()
def populate_config_args_and_parse_args(parser, unicode_args, config):
parser.add_argument(
"--email",
help="The username (email address) of the user to use",
default=MEMFAULT_CONFIG.email,
)
parser.add_argument(
"--password",
help="The user API key or password of the user to use",
default=MEMFAULT_CONFIG.password,
)
parser.add_argument(
"--organization",
"-o",
help="Default organization (slug) to use",
default=MEMFAULT_CONFIG.organization,
)
parser.add_argument(
"--project", "-p", help="Default project (slug) to use", default=MEMFAULT_CONFIG.project
)
parser.add_argument(
"--ingress-uri",
default=MEMFAULT_CONFIG.ingress_uri,