1 /*
2  * Copyright (c) 2024 Meta Platforms
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <string.h>
8 #include <stdbool.h>
9 
10 #include <zephyr/debug/symtab.h>
11 
symtab_get(void)12 const struct symtab_info *const symtab_get(void)
13 {
14 	extern const struct symtab_info z_symtab;
15 
16 	return &z_symtab;
17 }
18 
symtab_find_symbol_name(uintptr_t addr,uint32_t * offset)19 const char *const symtab_find_symbol_name(uintptr_t addr, uint32_t *offset)
20 {
21 	const struct symtab_info *const symtab = symtab_get();
22 	const uint32_t symbol_offset = addr - symtab->first_addr;
23 	uint32_t left = 0, right = symtab->length;
24 	uint32_t ret_offset = 0;
25 	const char *ret_name = "?";
26 
27 	/* No need to search if the address is out-of-bound */
28 	if (symbol_offset < symtab->entries[symtab->length].offset) {
29 		while (left <= right) {
30 			uint32_t mid = left + (right - left) / 2;
31 
32 			if ((symbol_offset >= symtab->entries[mid].offset) &&
33 			(symbol_offset < symtab->entries[mid + 1].offset)) {
34 				ret_offset = symbol_offset - symtab->entries[mid].offset;
35 				ret_name = symtab->entries[mid].name;
36 				break;
37 			} else if (symbol_offset < symtab->entries[mid].offset) {
38 				right = mid - 1;
39 			} else {
40 				left = mid + 1;
41 			}
42 		}
43 	}
44 
45 	if (offset != NULL) {
46 		*offset = ret_offset;
47 	}
48 
49 	return ret_name;
50 }
51