eh_frame_parser.c 37 KB

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