eh_frame_parser.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. /*
  2. * SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. /**
  7. * @file DWARF Exception Frames parser
  8. *
  9. * This file performs parsing and execution of DWARF except frames described in
  10. * section `.eh_frame` and `.eh_frame_hdr`. This is currently used on RISC-V
  11. * boards to implement a complete backtracing when a panic occurs.
  12. *
  13. * More information about the sections structure and DWARF instructions can be
  14. * found in the official documentation:
  15. * http://dwarfstd.org/Download.php
  16. */
  17. #include "esp_private/eh_frame_parser.h"
  18. #include "esp_private/panic_internal.h"
  19. #include <string.h>
  20. #if CONFIG_ESP_SYSTEM_USE_EH_FRAME
  21. #include "eh_frame_parser_impl.h"
  22. /**
  23. * @brief Dimension of an array (number of elements)
  24. */
  25. #ifndef DIM
  26. #define DIM(array) (sizeof(array)/sizeof(*array))
  27. #endif
  28. /**
  29. * @brief DWARF Exception Header Encoding
  30. * This is used to know how the data in .eh_frame and .eh_frame_hdr sections
  31. * are encoded.
  32. */
  33. /* DWARF Exception Exception Header value format. */
  34. #define DW_EH_PE_omit 0xff /*!< No value is present */
  35. #define DW_EH_PE_uleb128 0x01 /*!< Unsigned value encoded in LEB128 (Little Endian Base 128). */
  36. #define DW_EH_PE_udata2 0x02 /*!< Unsigned 16-bit value. */
  37. #define DW_EH_PE_udata4 0x03 /*!< Unsigned 32-bit value. */
  38. #define DW_EH_PE_udata8 0x04 /*!< Unsigned 64-bit value. */
  39. #define DW_EH_PE_sleb128 0x09 /*!< Signed value encoded in LEB128 (Little Endian Base 128). */
  40. #define DW_EH_PE_sdata2 0x0A /*!< Signed 16-bit value. */
  41. #define DW_EH_PE_sdata4 0x0B /*!< Signed 32-bit value. */
  42. #define DW_EH_PE_sdata8 0x0C /*!< Signed 64-bit value. */
  43. /* DWARF Exception Exception Header value application.
  44. * These values are in fact represented in the high nibble of a given data.
  45. * For example:
  46. * 0x3A describes the values as signed 16-bit offsets relative to .eh_frame_hdr section.
  47. * 0x11 describes the values as unsigned value encoded in LEB128, relative to their location ion memory. */
  48. #define DW_EH_PE_absptr 0x00 /*!< The value itself is a pointer, it is not an offset. */
  49. #define DW_EH_PE_pcrel 0x01 /*!< The value is an offset, relative to its location in memory. */
  50. #define DW_EH_PE_datarel 0x03 /*!< The value is an offset, relative to .eh_frame_hdr section. */
  51. /* Macros simplifying testing relative offset data encoding. */
  52. #define ESP_ENCODING_PC_REL(ENCODING) (((ENCODING >> 4) & 0xf) == DW_EH_PE_pcrel)
  53. #define ESP_ENCODING_FRAME_HDR_REL(ENCODING) (((ENCODING >> 4) & 0xf) == DW_EH_PE_datarel)
  54. /**
  55. * @brief Call Frame Information (CIE) fields information.
  56. * As the size of CIE is variable, the simplest way to described it is to
  57. * have a pointer at the beginning of CIE structure and access the fields
  58. * thanks to the index macros defined here.
  59. */
  60. #define ESP_CIE_VARIABLE_FIELDS_IDX (9) /*!< Offset, in bytes, where variable length fields start. */
  61. /**
  62. * @brief Frame Description Entry (FDE) fields index.
  63. * For the same reasons as above, we prefer defining these macros rather than
  64. * having a structure.
  65. */
  66. #define ESP_FDE_LENGTH_IDX (0) /*!< Length, in bytes, of the FDE excluding this field. 4 bytes field. */
  67. #define ESP_FDE_CIE_IDX (1) /*!< Nearest preceding Common Information Entry (CIE) offset. 4 bytes field. */
  68. #define ESP_FDE_INITLOC_IDX (2) /*!< Initial location (of the function) the FDE describes. Variable size (encoding in CIE). */
  69. #define ESP_FDE_RANGELEN_IDX (3) /*!< Size, in bytes, of the function described by this FDE location the FDE describes. Variable size (encoding in CIE). */
  70. #define ESP_FDE_AUGMENTATION_IDX (4) /*!< Augmentation data length. Unsigned LEB128. */
  71. /**
  72. * @brief Pointers to both .eh_frame_hdr and .eh_frame sections.
  73. */
  74. #define EH_FRAME_HDR_ADDR (&__eh_frame_hdr)
  75. #define EH_FRAME_ADDR (&__eh_frame)
  76. /**
  77. * @brief Structure of .eh_frame_hdr section header.
  78. */
  79. typedef struct {
  80. uint8_t version; /*!< Structure version, must be 1.*/
  81. uint8_t eh_frame_ptr_enc; /*!< eh_frame_ptr entry encoding. */
  82. uint8_t fde_count_enc; /*!< fde_count entry encoding. */
  83. uint8_t table_enc; /*!< table entries encoding. */
  84. /* The rest of the structure has variable length. Thus, we cannot define
  85. * them here. Here are their names:
  86. * - eh_frame_ptr : encoded pointer to the .eh_frame section.
  87. * - fde_Count : number of entries in the array of table_entry.
  88. * - table_entry array : sorted array of table_entry. */
  89. } __attribute__((packed)) fde_header;
  90. /**
  91. * @brief .eh_frame_hdr table's entry format.
  92. * Each entry of the table contains 2 32-bit encoded addresses.
  93. * Encoding is defined in the previous structure. Check table_enc field.
  94. */
  95. typedef struct {
  96. uint32_t fun_addr; /*!< Address of the function described. */
  97. uint32_t fde_addr; /*!< Address of the FDE for the function.*/
  98. } table_entry;
  99. /**
  100. * @brief DWARF state constant macros.
  101. */
  102. #define ESP_EH_FRAME_STACK_SIZE (2) /*!< DWARF virtual machine can save the push the current on a virtual
  103. stack. we mimic the stack with an array. While testing, a stack
  104. size of 2 was enough. */
  105. /**
  106. * @brief
  107. * Structure representing the state of the DWARF virtual machine.
  108. */
  109. typedef struct {
  110. /* Stack for DWARF state registers.
  111. * For caller saved registers, save their CFA address (value in previous call frame).
  112. * As these registers will be used to define offset in the CFA, they will always be
  113. * multiple of CPU word (4-bytes in our case). Thus, it will save the offset in word-size, not
  114. * in bytes. Plus, the highest bit will be used to mark that this register is NOY
  115. * ESP_EH_FRAME_REG_SAME. (0x80000000 is a valid value then, meaning that the register value
  116. * is CFA + 0 offset) */
  117. uint32_t regs_offset[ESP_EH_FRAME_STACK_SIZE][EXECUTION_FRAME_MAX_REGS];
  118. /* reg_offset represents the state of registers when PC reaches the following location. */
  119. uint32_t location;
  120. /* Index of the registers offset to use (1 for saved offset, 0 else). */
  121. uint8_t offset_idx;
  122. } dwarf_regs;
  123. /**
  124. * @brief DWARF's register state.
  125. * When a DWARF register is set to ESP_EH_FRAME_REG_SAME, the CPU register corresponding to this
  126. * virtual register will be unchanged after executing DWARF instructions.
  127. * Please see esp_eh_frame_restore_caller_state() for more details.
  128. */
  129. #define ESP_EH_FRAME_REG_SAME (0)
  130. /**
  131. * @brief Set a register's offset (relative to CFA).
  132. * The highest bit is set to 1 to mark that this register needs to be retrived because it has been
  133. * altered.
  134. */
  135. #define ESP_EH_FRAME_SET_REG_OFFSET(offset) (0x80000000 | offset)
  136. /**
  137. * @brief Get a register's offset (relative to CFA).
  138. */
  139. #define ESP_EH_FRAME_GET_REG_OFFSET(offset) (0x7fffffff & offset)
  140. /**
  141. * @brief Get a register's CFA offset.
  142. */
  143. #define ESP_EH_FRAME_IS_CFA_RELATIVE(reg) ((reg >> 31) == 1)
  144. /**
  145. * @brief Test whether an offset is small enough to be stored
  146. * in our 32-bit register.
  147. * Note: the highest bit is used.
  148. */
  149. #define ESP_EH_FRAME_CFA_OFFSET_VALID(offset) (offset < 0x80000000)
  150. /**
  151. * @brief Index of Call Frame Address (CFA) in DWARF registers array.
  152. */
  153. #define ESP_ESH_FRAME_CFA_IDX (EXECUTION_FRAME_SP_REG)
  154. /**
  155. * @brief Macros to get and set CFA's relative register and offset.
  156. * Indeed, CFA is defined by two values: register and offset. CFA is then
  157. * calculated by adding the offset to the register value.
  158. * `register` will be stored in the lowest 8 bits.
  159. * `offset` will be stored in the highest 24 bits.
  160. *
  161. * NOTE: with this implementation, CFA will be affected by
  162. * DW_CFA_REMEMBER_STATE and DW_CFA_RESTORE_STATE instructions.
  163. */
  164. #if EXECUTION_FRAME_MAX_REGS > 255
  165. #error "Too many registers defined for the target ExecutionFrame"
  166. #endif
  167. #define ESP_EH_FRAME_CFA_REG_VALID(reg) (reg < EXECUTION_FRAME_MAX_REGS)
  168. #define ESP_EH_FRAME_CFA_OFF_VALID(off) (((off) >> 24) == 0)
  169. #define ESP_EH_FRAME_CFA(state) ((state)->regs_offset[(state)->offset_idx][ESP_ESH_FRAME_CFA_IDX])
  170. #define ESP_EH_FRAME_NEW_CFA(reg, off) (((off) << 8) | ((reg) & 0xff))
  171. #define ESP_EH_FRAME_SET_CFA_REG(value, reg) (((value) & ~0xff) | ((reg) & 0xff))
  172. #define ESP_EH_FRAME_SET_CFA_OFF(value, off) (((value) & 0xff) | ((off) << 8))
  173. #define ESP_EH_FRAME_GET_CFA_REG(value) ((value) & 0xff)
  174. #define ESP_EH_FRAME_GET_CFA_OFF(value) ((value) >> 8)
  175. /**
  176. * @brief Unsupported opcode value to return when exeucting 0-opcode type instructions.
  177. */
  178. #define ESP_EH_FRAME_UNSUPPORTED_OPCODE ((uint32_t) -1)
  179. /**
  180. * @brief Macros defining the DWARF instructions code.
  181. */
  182. #define DW_GET_OPCODE(OP) ((OP) >> 6)
  183. #define DW_GET_PARAM(OP) ((OP) & 0b111111)
  184. #define DW_CFA_ADVANCE_LOC (1)
  185. #define DW_CFA_OFFSET (2)
  186. #define DW_CFA_RESTORE (3)
  187. /**
  188. * @brief Constant for DWARF instructions code when high 2 bits are 0.
  189. */
  190. #define DW_CFA_0_OPCODE (0)
  191. #define DW_CFA_NOP (0x0)
  192. #define DW_CFA_SET_LOC (0x1)
  193. #define DW_CFA_ADVANCE_LOC1 (0x2)
  194. #define DW_CFA_ADVANCE_LOC2 (0x3)
  195. #define DW_CFA_ADVANCE_LOC4 (0x4)
  196. #define DW_CFA_OFFSET_EXTENDED (0x5)
  197. #define DW_CFA_RESTORE_EXTENDED (0x6)
  198. #define DW_CFA_UNDEFINED (0x7)
  199. #define DW_CFA_SAME_VALUE (0x8)
  200. #define DW_CFA_REGISTER (0x9)
  201. #define DW_CFA_REMEMBER_STATE (0xA)
  202. #define DW_CFA_RESTORE_STATE (0xB)
  203. #define DW_CFA_DEF_CFA (0xC)
  204. #define DW_CFA_DEF_CFA_REGISTER (0xD)
  205. #define DW_CFA_DEF_CFA_OFFSET (0xE)
  206. #define DW_CFA_DEF_CFA_EXPRESSION (0xF)
  207. #define DW_CFA_EXPRESSION (0x10)
  208. #define DW_CFA_OFFSET_EXTENDED_SF (0x11)
  209. #define DW_CFA_DEF_CFA_SF (0x12)
  210. #define DW_CFA_DEF_CFA_OFFSET_SF (0x13)
  211. #define DW_CFA_VAL_OFFSET (0x14)
  212. #define DW_CFA_VAL_OFFSET_SF (0x15)
  213. #define DW_CFA_VAL_EXPRESSION (0x16)
  214. #define DW_CFA_LO_USER (0x1C)
  215. /**
  216. * @brief Constants used for decoding (U)LEB128 integers.
  217. */
  218. #define DW_LEB128_HIGHEST_BIT(byte) (((byte) >> 7) & 1)
  219. #define DW_LEB128_SIGN_BIT(byte) (((byte) >> 6) & 1)
  220. #define DW_LEB128_MAX_SHIFT (31)
  221. /**
  222. * @brief Symbols defined by the linker.
  223. * Retrieve the addresses of both .eh_frame_hdr and .eh_frame sections.
  224. */
  225. extern char __eh_frame_hdr;
  226. extern char __eh_frame;
  227. /**
  228. * @brief Decode multiple bytes encoded in LEB128.
  229. *
  230. * @param bytes bytes encoded in LEB128. They will not be modified.
  231. * @param is_signed true if bytes represent a signed value, false else.
  232. * @param size Size in bytes of the encoded value.
  233. *
  234. * @return Decoded bytes.
  235. */
  236. static uint32_t decode_leb128(const uint8_t* bytes, bool is_signed, uint32_t* lebsize)
  237. {
  238. uint32_t res = 0;
  239. uint32_t shf = 0;
  240. uint32_t size = 0;
  241. uint8_t byte = 0;
  242. while(1) {
  243. byte = bytes[size++];
  244. res |= (byte & 0x7f) << shf;
  245. shf += 7;
  246. if (DW_LEB128_HIGHEST_BIT(byte) == 0)
  247. break;
  248. }
  249. if (is_signed && shf <= DW_LEB128_MAX_SHIFT && DW_LEB128_SIGN_BIT(byte)) {
  250. res |= ((uint32_t) ~0 << shf);
  251. }
  252. if (lebsize) {
  253. *lebsize = size;
  254. }
  255. return res;
  256. }
  257. /**
  258. * @brief Get the value of data encoded.
  259. *
  260. * @param data Pointer to the encoded data.
  261. * @param encoding Encoding for the data to read.
  262. * @param psize Reference to be filled with data size, in bytes.
  263. *
  264. * @return Decoded data read from the pointer.
  265. */
  266. static uint32_t esp_eh_frame_get_encoded(void* data, uint8_t encoding, uint32_t* psize)
  267. {
  268. int32_t svalue = 0;
  269. uint32_t uvalue = 0;
  270. uint32_t fvalue = 0;
  271. uint32_t size = 0;
  272. const uint32_t high = encoding >> 4;
  273. const uint32_t low = encoding & 0xf;
  274. assert(psize != NULL);
  275. if (encoding == DW_EH_PE_omit) {
  276. *psize = size;
  277. return uvalue;
  278. }
  279. switch (low) {
  280. case DW_EH_PE_udata2:
  281. size = 2;
  282. uvalue = *((uint16_t*) data);
  283. break;
  284. case DW_EH_PE_udata4:
  285. size = 4;
  286. uvalue = *((uint32_t*) data);
  287. break;
  288. case DW_EH_PE_sdata2:
  289. size = 2;
  290. svalue = *((int16_t*) data);
  291. break;
  292. case DW_EH_PE_sdata4:
  293. size = 4;
  294. svalue = *((int32_t*) data);
  295. break;
  296. default:
  297. /* Unsupported yet. */
  298. assert(false);
  299. break;
  300. }
  301. switch (high) {
  302. case DW_EH_PE_absptr:
  303. /* Do not change the values, as one of them will be 0, fvalue will
  304. * contain the data no matter whether it is signed or unsigned. */
  305. fvalue = svalue + uvalue;
  306. break;
  307. case DW_EH_PE_pcrel:
  308. /* Relative to the address of the data.
  309. * svalue has been casted to an 32-bit value, so even if it was a
  310. * 2-byte signed value, fvalue will be calculated correctly here. */
  311. fvalue = (uint32_t) data + svalue + uvalue;
  312. break;
  313. case DW_EH_PE_datarel:
  314. fvalue = (uint32_t) EH_FRAME_HDR_ADDR + svalue + uvalue;
  315. break;
  316. }
  317. *psize = size;
  318. return fvalue;
  319. }
  320. /**
  321. * @brief Find entry in the table for the given return_address.
  322. *
  323. * @param sorted_table Pointer to the sorted table of entries.
  324. * @param length Number of entries in the table.
  325. * @param encoding Encoding for the addresses in the table
  326. * (Check DWARF documentation for more info about encoding).
  327. * @param return_address The address to find in the table. This address can be
  328. * part of one in the function listed.
  329. *
  330. * @note The table is structured like this (after decoding the addresses):
  331. * Function address FDE address Index
  332. * +-------------------------------+
  333. * |0x403805a4 0x4038d014| 0
  334. * +-------------------------------+
  335. * |0x403805be 0x4038d034| 1
  336. * +-------------------------------+
  337. * |0x403805d8 0x4038d070| 2
  338. * +-------------------------------+
  339. * |.......... ..........| ...
  340. * +-------------------------------+
  341. * |0x42020c48 0x4038ddb4| length-3
  342. * +-------------------------------+
  343. * |0x42020dca 0x4038dde4| length-2
  344. *+-------------------------------+
  345. * |0x42020f92 0x4038debc| length-1
  346. * +-------------------------------+
  347. *
  348. * For example, if return_address passed is 0x403805b4, this function will
  349. * return a pointer to the entry (0x403805a4, 0x4038d014).
  350. *
  351. * @return Pointer to the entry found, NULL if not found.
  352. */
  353. static const table_entry* esp_eh_frame_find_entry(const table_entry* sorted_table,
  354. const uint32_t length,
  355. const uint32_t encoding,
  356. const uint32_t return_address)
  357. {
  358. int32_t ra = 0;
  359. /* Used for decoding addresses in the table. */
  360. uint32_t is_signed = (encoding & 0xf) >= 0x9;
  361. uint32_t pc_relative = true;
  362. /* The following local variables are used for dichotomic search. */
  363. uint32_t found = false;
  364. uint32_t begin = 0;
  365. uint32_t end = length;
  366. uint32_t middle = (end + begin) / 2;
  367. /* If the addresses in the table are offsets relative to the eh_frame section,
  368. * instead of decoding each of them, we can simply encode the return_address
  369. * we have to find. If addresses are offsets relative to the programe counter,
  370. * then we have no other choice than decoding each of them to compare them
  371. * with return_address. */
  372. if (ESP_ENCODING_FRAME_HDR_REL(encoding)) {
  373. ra = return_address - (uint32_t) EH_FRAME_HDR_ADDR;
  374. pc_relative = false;
  375. }
  376. /* Perform dichotomic search. */
  377. while (end != 0 && middle != (length - 1) && !found) {
  378. const uint32_t fun_addr = sorted_table[middle].fun_addr;
  379. const uint32_t nxt_addr = sorted_table[middle + 1].fun_addr;
  380. if (pc_relative) {
  381. ra = return_address - (uint32_t) (sorted_table + middle);
  382. }
  383. if (is_signed) {
  384. /* Signed comparisons. */
  385. const int32_t sfun_addr = (int32_t) fun_addr;
  386. const int32_t snxt_addr = (int32_t) nxt_addr;
  387. if (sfun_addr <= ra && snxt_addr > ra)
  388. found = true;
  389. else if (snxt_addr <= ra)
  390. begin = middle + 1;
  391. else
  392. end = middle;
  393. } else {
  394. /* Unsigned comparisons. */
  395. const uint32_t ura = (uint32_t) ra;
  396. if (fun_addr <= ura && nxt_addr > ura)
  397. found = true;
  398. else if (nxt_addr <= ura)
  399. begin = middle + 1;
  400. else
  401. end = middle;
  402. }
  403. middle = (end + begin) / 2;
  404. }
  405. /* If 'end' reached the beginning of the array, it means the return_address
  406. * passed was below the first address of the array, thus, it was wrong.
  407. * Else, return the address found. */
  408. return (end == 0) ? 0 : sorted_table + middle;
  409. }
  410. /**
  411. * @brief Decode an address according to the encoding passed.
  412. *
  413. * @param addr Pointer to the address to decode.
  414. * This pointer's value MUST be an address in .eh_frame_hdr section.
  415. * @param encoding DWARF encoding byte.
  416. *
  417. * @return address dedoded (e.g. absolute address)
  418. */
  419. static inline uint32_t* esp_eh_frame_decode_address(const uint32_t* addr,
  420. const uint32_t encoding)
  421. {
  422. uint32_t* decoded = 0;
  423. if (ESP_ENCODING_FRAME_HDR_REL(encoding))
  424. decoded = (uint32_t*) (*addr + (uint32_t) EH_FRAME_HDR_ADDR);
  425. else if (ESP_ENCODING_PC_REL(encoding))
  426. decoded = (uint32_t*) (*addr + (uint32_t) addr);
  427. else
  428. decoded = (uint32_t*) (*addr);
  429. return decoded;
  430. }
  431. /**
  432. * @brief Execute the DWARF instruction which high 2 bits are 0.
  433. *
  434. * @param opcode low 6 bits of the instruction code.
  435. * @param operands pointer to the possible operands.
  436. * @param state state of the DWARF machine. Its registers may be modified.
  437. *
  438. * @return Number of operands used for executing the instruction.
  439. */
  440. static inline uint32_t esp_eh_frame_execute_opcode_0(const uint32_t opcode, const uint8_t* operands,
  441. dwarf_regs* state)
  442. {
  443. uint32_t operand1 = 0;
  444. uint32_t used_operands = 0;
  445. uint32_t operand2 = 0;
  446. uint32_t used_operands2 = 0;
  447. switch(opcode) {
  448. case DW_CFA_NOP:
  449. break;
  450. case DW_CFA_ADVANCE_LOC1:
  451. /* Advance location with a 1-byte delta. */
  452. used_operands = 1;
  453. state->location += *operands;
  454. break;
  455. case DW_CFA_ADVANCE_LOC2:
  456. /* Advance location with a 2-byte delta. */
  457. used_operands = 2;
  458. state->location += *((const uint16_t*) operands);
  459. break;
  460. case DW_CFA_ADVANCE_LOC4:
  461. /* Advance location with a 4-byte delta. */
  462. used_operands = 4;
  463. state->location += *((const uint32_t*) operands);
  464. break;
  465. case DW_CFA_REMEMBER_STATE:
  466. assert(state->offset_idx == 0);
  467. memcpy(state->regs_offset[1], state->regs_offset[0],
  468. EXECUTION_FRAME_MAX_REGS * sizeof(uint32_t));
  469. state->offset_idx++;
  470. break;
  471. case DW_CFA_RESTORE_STATE:
  472. assert(state->offset_idx == 1);
  473. /* Drop the saved state. */
  474. state->offset_idx--;
  475. break;
  476. case DW_CFA_DEF_CFA:
  477. /* CFA changes according to a register and an offset.
  478. * This instruction appears when the assembly code saves the
  479. * SP in the middle of a routine, before modifying it.
  480. * For example (on RISC-V):
  481. * addi s0, sp, 80
  482. * addi sp, sp, -10
  483. * ... */
  484. /* Operand1 is the register containing the CFA value. */
  485. operand1 = decode_leb128(operands, false, &used_operands);
  486. /* Offset for the register's value. */
  487. operand2 = decode_leb128(operands + used_operands, false, &used_operands2);
  488. /* Calculate the number of bytes */
  489. used_operands += used_operands2;
  490. /* Assert that the register and the offset are valid. */
  491. assert(ESP_EH_FRAME_CFA_REG_VALID(operand1));
  492. assert(ESP_EH_FRAME_CFA_OFF_VALID(operand2));
  493. ESP_EH_FRAME_CFA(state) = ESP_EH_FRAME_NEW_CFA(operand1, operand2);
  494. break;
  495. case DW_CFA_DEF_CFA_REGISTER:
  496. /* Define the register of the current frame address (CFA).
  497. * Its operand is in the next bytes, its type is ULEB128. */
  498. operand1 = decode_leb128(operands, false, &used_operands);
  499. /* Check whether the value is valid or not. */
  500. assert(ESP_EH_FRAME_CFA_OFF_VALID(operand1));
  501. /* Offset will be unchanged, only register changes. */
  502. ESP_EH_FRAME_CFA(state) = ESP_EH_FRAME_SET_CFA_REG(ESP_EH_FRAME_CFA(state), operand1);
  503. break;
  504. case DW_CFA_DEF_CFA_OFFSET:
  505. /* Same as above but for the offset. The register of CFA remains unchanged. */
  506. operand1 = decode_leb128(operands, false, &used_operands);
  507. assert(ESP_EH_FRAME_CFA_OFF_VALID(operand1));
  508. ESP_EH_FRAME_CFA(state) = ESP_EH_FRAME_SET_CFA_OFF(ESP_EH_FRAME_CFA(state), operand1);
  509. break;
  510. default:
  511. panic_print_str("\r\nUnsupported DWARF opcode 0: 0x");
  512. panic_print_hex(opcode);
  513. panic_print_str("\r\n");
  514. used_operands = ESP_EH_FRAME_UNSUPPORTED_OPCODE;
  515. break;
  516. }
  517. return used_operands;
  518. }
  519. /**
  520. * @brief Execute DWARF instructions.
  521. *
  522. * @param instructions Array of instructions to execute.
  523. * @param instructions_length Length of the array of instructions.
  524. * @param frame Execution frame of the crashed task. This will only be used to
  525. * get the PC where the task crashed.
  526. * @param state DWARF machine state. The registers contained in the state will
  527. * modified accordingly to the instructions.
  528. *
  529. * @return true if the execution went fine, false if an unsupported instruction was met.
  530. */
  531. static bool esp_eh_frame_execute(const uint8_t* instructions, const uint32_t instructions_length,
  532. const ExecutionFrame* frame, dwarf_regs* state)
  533. {
  534. for (uint32_t i = 0; i < instructions_length; i++) {
  535. const uint8_t instr = instructions[i];
  536. const uint8_t param = DW_GET_PARAM(instr);
  537. uint32_t operand1 = 0;
  538. uint32_t size = 0;
  539. uint32_t used_operands = 0;
  540. /* Decode the instructions. According to DWARF documentation, there are three
  541. * types of Call Frame Instructions. The upper 2 bits defines the type. */
  542. switch (DW_GET_OPCODE(instr)) {
  543. case DW_CFA_0_OPCODE:
  544. used_operands = esp_eh_frame_execute_opcode_0(param, &instructions[i + 1], state);
  545. /* Exit the function if an unsupported opcode was met. */
  546. if (used_operands == ESP_EH_FRAME_UNSUPPORTED_OPCODE) {
  547. return false;
  548. }
  549. i += used_operands;
  550. break;
  551. case DW_CFA_ADVANCE_LOC:
  552. /* Move the location forward. This instruction will mark when to stop:
  553. * once we reach the instruction where the PC left, we can break out of the loop
  554. * The delta is part of the lowest 6 bits.
  555. */
  556. state->location += param;
  557. break;
  558. case DW_CFA_OFFSET:
  559. operand1 = decode_leb128(&instructions[i + 1], false, &size);
  560. assert(ESP_EH_FRAME_CFA_OFFSET_VALID(operand1));
  561. state->regs_offset[state->offset_idx][param] = ESP_EH_FRAME_SET_REG_OFFSET(operand1);
  562. i += size;
  563. break;
  564. case DW_CFA_RESTORE:
  565. state->regs_offset[state->offset_idx][param] = ESP_EH_FRAME_REG_SAME;
  566. break;
  567. default:
  568. /* Illegal opcode */
  569. assert(false);
  570. break;
  571. }
  572. /* As the state->location can also be modified by 0-opcode instructions (in the function)
  573. * and also because we need to break the loop (and not only the switch), let's put this
  574. * check here, after the execution of the instruction, outside of the switch block. */
  575. if (state->location >= EXECUTION_FRAME_PC(*frame))
  576. break;
  577. }
  578. /* Everything went fine, no unsupported opcode was met, return true. */
  579. return true;
  580. }
  581. /**
  582. * @brief Initialize the DWARF registers state by parsing and executing CIE instructions.
  583. *
  584. * @param cie Pointer to the CIE data.
  585. * @param frame Pointer to the execution frame.
  586. * @param state DWARF machine state (DWARF registers).
  587. *
  588. * @return index of the DWARF register containing the return address.
  589. */
  590. static uint32_t esp_eh_frame_initialize_state(const uint8_t* cie, ExecutionFrame* frame, dwarf_regs* state)
  591. {
  592. char c = 0;
  593. uint32_t size = 0;
  594. /* The first word in the CIE structure is the length of the structure,
  595. * excluding this field itself. */
  596. const uint32_t length = ((uint32_t*) cie)[0];
  597. /* ID of the CIE, should be 0 for .eh_frame (which is our case) */
  598. const uint32_t id = ((uint32_t*) cie)[1];
  599. assert(id == 0);
  600. /* Ignore CIE version (1 byte). */
  601. /* The following data in the structure have variable length as they are
  602. * encoded in (U)LEB128. Thus, let's use a byte pointer to parse them. */
  603. uint8_t* cie_data = (uint8_t*) cie + ESP_CIE_VARIABLE_FIELDS_IDX;
  604. /* Next field is a null-terminated UTF-8 string. Ignore it, look for the end. */
  605. while((c = *cie_data++) != 0);
  606. /* Field alignment factor shall be 1. It is encoded in ULEB128. */
  607. const uint32_t code_align = decode_leb128(cie_data, false, &size);
  608. assert(code_align == 1);
  609. /* Jump to the next field */
  610. cie_data += size;
  611. /* Same goes for data alignment factor. Shall be equal to -4. */
  612. const int32_t data_align = decode_leb128(cie_data, true, &size);
  613. cie_data += size;
  614. assert(data_align == -4);
  615. /* Field describing the index of the DWARF register which will contain
  616. * the return address. */
  617. const uint32_t ra_reg = decode_leb128(cie_data, false, &size);
  618. cie_data += size;
  619. /* Augmentation data length is encoded in ULEB128. It represents the,
  620. * length of the augmentation data. Jump after it to retrieve the
  621. * instructions to execute. */
  622. const uint32_t augmentation_len = decode_leb128(cie_data, false, &size);
  623. cie_data += size + augmentation_len;
  624. /* Calculate the instructions length in order to prevent any out of bounds
  625. * bug. Subtract the offset of this field (minus sizeof(uint32_t) because
  626. * `length` field is not part of the structure length) to the total length
  627. * of the structure. */
  628. const uint32_t instructions_length = length - (cie_data - sizeof(uint32_t) - cie);
  629. /* Execute the instructions contained in CIE structure. Their goal is to
  630. * initialize the DWARF registers. Usually it binds the CFA (virtual stack
  631. * pointer), to its hardware equivalent. It will also bind a hardware
  632. * register to the virtual return address register. For example, x86
  633. * doesn't have a return address register, the address to return to
  634. * it stored on the stack when `call` instruction is used. DWARF will
  635. * use `eip` (instruction pointer, a.k.a. program counter) as a
  636. * register containing the return address register. */
  637. esp_eh_frame_execute(cie_data, instructions_length, frame, state);
  638. return ra_reg;
  639. }
  640. /**
  641. * @brief Modify the execution frame and DWARF VM state for restoring caller's context.
  642. *
  643. * @param fde Pointer to the Frame Description Entry for the current program counter (defined by frame's MEPC register)
  644. * @param frame Snapshot of the CPU registers when the CPU stopped its normal execution.
  645. * @param state DWARF VM registers.
  646. *
  647. * @return Return Address of the current context. Frame has been restored to the previous context
  648. * (before calling the function program counter is currently going throught).
  649. */
  650. static uint32_t esp_eh_frame_restore_caller_state(const uint32_t* fde,
  651. ExecutionFrame* frame,
  652. dwarf_regs* state)
  653. {
  654. /* Length of the whole Frame Description Entry (FDE), excluding this field. */
  655. const uint32_t length = fde[ESP_FDE_LENGTH_IDX];
  656. /* The addresses in FDE are relative to the location of each field.
  657. * Thus, to get the absolute address of the function it is pointing to,
  658. * we have to compute:
  659. * fun_addr = &fde[IDX] +/- fde[IDX]
  660. */
  661. const uint8_t* cie = (uint8_t*) ((uint32_t) &fde[ESP_FDE_CIE_IDX] - fde[ESP_FDE_CIE_IDX]);
  662. const uint32_t initial_location = ((uint32_t) &fde[ESP_FDE_INITLOC_IDX] + fde[ESP_FDE_INITLOC_IDX]);
  663. const uint32_t range_length = fde[ESP_FDE_RANGELEN_IDX];
  664. const uint8_t augmentation = *((uint8_t*) (fde + ESP_FDE_AUGMENTATION_IDX));
  665. /* The length, in byte, of the instructions is the size of the FDE header minus
  666. * the above fields' length. */
  667. const uint32_t instructions_length = length - 3 * sizeof(uint32_t) - sizeof(uint8_t);
  668. const uint8_t* instructions = ((uint8_t*) (fde + ESP_FDE_AUGMENTATION_IDX)) + 1;
  669. /* Make sure this FDE is the correct one for the PC given. */
  670. assert(initial_location <= EXECUTION_FRAME_PC(*frame) &&
  671. EXECUTION_FRAME_PC(*frame) < initial_location + range_length);
  672. /* Augmentation not supported. */
  673. assert(augmentation == 0);
  674. /* Initialize the DWARF state by executing the CIE's instructions. */
  675. const uint32_t ra_reg = esp_eh_frame_initialize_state(cie, frame, state);
  676. state->location = initial_location;
  677. /**
  678. * Execute the DWARf instructions is order to create rules that will be executed later to retrieve
  679. * the registers former value.
  680. */
  681. bool success = esp_eh_frame_execute(instructions, instructions_length, frame, state);
  682. if (!success) {
  683. /* An error occured (unsupported opcode), return PC as the return address.
  684. * This will be tested by the caller, and the backtrace will be finished. */
  685. return EXECUTION_FRAME_PC(*frame);
  686. }
  687. /* Execute the rules calculated previously. Start with the CFA. */
  688. const uint32_t cfa_val = ESP_EH_FRAME_CFA(state);
  689. const uint32_t cfa_reg = ESP_EH_FRAME_GET_CFA_REG(cfa_val);
  690. const uint32_t cfa_off = ESP_EH_FRAME_GET_CFA_OFF(cfa_val);
  691. const uint32_t cfa_addr = EXECUTION_FRAME_REG(frame, cfa_reg) + cfa_off;
  692. /* Restore the registers that need to be restored. */
  693. for (uint32_t i = 0; i < DIM(state->regs_offset[0]); i++) {
  694. uint32_t value_addr = state->regs_offset[state->offset_idx][i];
  695. /* Check that the value changed and that we are not treating the CFA register (if it is part of the array). */
  696. if (i != ESP_ESH_FRAME_CFA_IDX && value_addr != ESP_EH_FRAME_REG_SAME) {
  697. /* value_addr contains a description of how to find its address:
  698. * it has an offset relative to the CFA, which will point to the actual former value.
  699. * In fact, the register's previous value (in the context of the caller) is on the stack,
  700. * this is what value_addr will point to. */
  701. value_addr = cfa_addr - ESP_EH_FRAME_GET_REG_OFFSET(value_addr) * sizeof(uint32_t);
  702. EXECUTION_FRAME_REG(frame, i) = *((uint32_t*) value_addr);
  703. }
  704. }
  705. /* Restore the stack pointer according to DWARF CFA register. */
  706. EXECUTION_FRAME_SP(*frame) = cfa_addr;
  707. /* If the frame was not available, it would be possible to retrieve the return address
  708. * register thanks to CIE structure.
  709. * The return address points to the address the PC needs to jump to. It
  710. * does NOT point to the instruction where the routine call occured.
  711. * This can cause problems with functions without epilogue (i.e. function
  712. * which last instruction is a function call). This happens when compiler
  713. * optimization are ON or when a function is marked as "noreturn".
  714. *
  715. * Thus, in order to point to the call/jal instruction, we need to
  716. * subtract at least 1 byte but not more than an instruction size.
  717. */
  718. return EXECUTION_FRAME_REG(frame, ra_reg) - 2;
  719. }
  720. /**
  721. * @brief Test whether the DWARF information for the given PC are missing or not.
  722. *
  723. * @param fde FDE associated to this PC. This FDE is the one found thanks to
  724. * `esp_eh_frame_find_entry()`.
  725. * @param pc PC to get information from.
  726. *
  727. * @return true is DWARF information are missing, false else.
  728. */
  729. static bool esp_eh_frame_missing_info(const uint32_t* fde, uint32_t pc) {
  730. if (fde == NULL) {
  731. return true;
  732. }
  733. /* Get the range of this FDE entry. It is possible that there are some
  734. * gaps between DWARF entries, in that case, the FDE entry found has
  735. * indeed an initial_location very close to PC but doesn't reach it.
  736. * For example, if FDE initial_location is 0x40300000 and its length is
  737. * 0x100, but PC value is 0x40300200, then some DWARF information
  738. * are missing as there is a gap.
  739. * End the backtrace. */
  740. const uint32_t initial_location = ((uint32_t) &fde[ESP_FDE_INITLOC_IDX] + fde[ESP_FDE_INITLOC_IDX]);
  741. const uint32_t range_length = fde[ESP_FDE_RANGELEN_IDX];
  742. return (initial_location + range_length) <= pc;
  743. }
  744. /**
  745. * @brief When one step of the backtrace is generated, output it to the serial.
  746. * This function can be overriden as it is defined as weak.
  747. *
  748. * @param pc Program counter of the backtrace step.
  749. * @param sp Stack pointer of the backtrace step.
  750. */
  751. void __attribute__((weak)) esp_eh_frame_generated_step(uint32_t pc, uint32_t sp)
  752. {
  753. panic_print_str(" 0x");
  754. panic_print_hex(pc);
  755. panic_print_str(":0x");
  756. panic_print_hex(sp);
  757. }
  758. /**
  759. * @brief Print backtrace for the given execution frame.
  760. *
  761. * @param frame_or Snapshot of the CPU registers when the CPU stopped its normal execution.
  762. */
  763. void esp_eh_frame_print_backtrace(const void *frame_or)
  764. {
  765. assert(frame_or != NULL);
  766. static dwarf_regs state = { 0 };
  767. ExecutionFrame frame = *((ExecutionFrame*) frame_or);
  768. uint32_t size = 0;
  769. uint8_t* enc_values = NULL;
  770. bool end_of_backtrace = false;
  771. /* Start parsing the .eh_frame_hdr section. */
  772. fde_header* header = (fde_header*) EH_FRAME_HDR_ADDR;
  773. assert(header->version == 1);
  774. /* Make enc_values point to the end of the structure, where the encoded
  775. * values start. */
  776. enc_values = (uint8_t*) (header + 1);
  777. /* Retrieve the encoded value eh_frame_ptr. Get the size of the data also. */
  778. const uint32_t eh_frame_ptr = esp_eh_frame_get_encoded(enc_values, header->eh_frame_ptr_enc, &size);
  779. assert(eh_frame_ptr == (uint32_t) EH_FRAME_ADDR);
  780. enc_values += size;
  781. /* Same for the number of entries in the sorted table. */
  782. const uint32_t fde_count = esp_eh_frame_get_encoded(enc_values, header->fde_count_enc, &size);
  783. enc_values += size;
  784. /* enc_values points now at the beginning of the sorted table. */
  785. /* Only support 4-byte entries. */
  786. const uint32_t table_enc = header->table_enc;
  787. assert(((table_enc >> 4) == 0x3) || ((table_enc >> 4) == 0xB));
  788. const table_entry* sorted_table = (const table_entry*) enc_values;
  789. panic_print_str("Backtrace:");
  790. while (!end_of_backtrace) {
  791. /* Output one step of the backtrace. */
  792. esp_eh_frame_generated_step(EXECUTION_FRAME_PC(frame), EXECUTION_FRAME_SP(frame));
  793. const table_entry* from_fun = esp_eh_frame_find_entry(sorted_table, fde_count,
  794. table_enc, EXECUTION_FRAME_PC(frame));
  795. /* Get absolute address of FDE entry describing the function where PC left of. */
  796. uint32_t* fde = NULL;
  797. if (from_fun != NULL) {
  798. fde = esp_eh_frame_decode_address(&from_fun->fde_addr, table_enc);
  799. }
  800. if (esp_eh_frame_missing_info(fde, EXECUTION_FRAME_PC(frame))) {
  801. /* Address was not found in the list. */
  802. panic_print_str("\r\nBacktrace ended abruptly: cannot find DWARF information for"
  803. " instruction at address 0x");
  804. panic_print_hex(EXECUTION_FRAME_PC(frame));
  805. panic_print_str("\r\n");
  806. break;
  807. }
  808. /* Clean and set the DWARF register structure. */
  809. memset(&state, 0, sizeof(dwarf_regs));
  810. const uint32_t prev_sp = EXECUTION_FRAME_SP(frame);
  811. /* Retrieve the return address of the frame. The frame's registers will be modified.
  812. * The frame we get then is the caller's one. */
  813. uint32_t ra = esp_eh_frame_restore_caller_state(fde, &frame, &state);
  814. /* End of backtrace is reached if the stack and the PC don't change anymore. */
  815. end_of_backtrace = (EXECUTION_FRAME_SP(frame) == prev_sp) && (EXECUTION_FRAME_PC(frame) == ra);
  816. /* Go back to the caller: update stack pointer and program counter. */
  817. EXECUTION_FRAME_PC(frame) = ra;
  818. }
  819. panic_print_str("\r\n");
  820. }
  821. #endif //ESP_SYSTEM_USE_EH_FRAME