1+ #include <stdio.h>
2+ #include <stdlib.h>
3+ #include <string.h>
4+ #include "ftrace.h"
5+
6+ void init_symbol_table (SymbolTable * table ) {
7+ if (!table ) return ;
8+ table -> symbols = NULL ;
9+ table -> count = 0 ;
10+ table -> capacity = 0 ;
11+ }
12+
13+ void add_func_symbol (SymbolTable * table , uint64_t addr , const char * name ) {
14+ if (!table || !name ) return ;
15+
16+ if (table -> count >= table -> capacity ) {
17+ int new_capacity = (table -> capacity == 0 ) ? 16 : table -> capacity * 2 ;
18+ FuncSymbol * new_symbols = realloc (table -> symbols , new_capacity * sizeof (FuncSymbol ));
19+ if (!new_symbols ) {
20+ perror ("Failed to reallocate symbol table" );
21+ return ;
22+ }
23+ table -> symbols = new_symbols ;
24+ table -> capacity = new_capacity ;
25+ }
26+
27+ char * name_copy = strdup (name );
28+ if (!name_copy ) {
29+ perror ("Failed to duplicate symbol name" );
30+ return ;
31+ }
32+
33+ table -> symbols [table -> count ].address = addr ;
34+ table -> symbols [table -> count ].name = name_copy ;
35+ table -> count ++ ;
36+ }
37+
38+ static int compare_symbols (const void * a , const void * b ) {
39+ FuncSymbol * sym_a = (FuncSymbol * )a ;
40+ FuncSymbol * sym_b = (FuncSymbol * )b ;
41+ if (sym_a -> address < sym_b -> address ) return -1 ;
42+ if (sym_a -> address > sym_b -> address ) return 1 ;
43+ return 0 ;
44+ }
45+
46+ void sort_symbols_by_address (SymbolTable * table ) {
47+ if (!table || table -> count == 0 ) return ;
48+ qsort (table -> symbols , table -> count , sizeof (FuncSymbol ), compare_symbols );
49+ }
50+
51+ const char * find_func_name (SymbolTable * table , uint64_t addr ) {
52+ if (!table || table -> count == 0 ) return "unknown_function" ;
53+
54+ int low = 0 , high = table -> count - 1 ;
55+ int best_match_idx = -1 ;
56+
57+ while (low <= high ) {
58+ int mid = low + (high - low ) / 2 ;
59+ if (table -> symbols [mid ].address <= addr ) {
60+ best_match_idx = mid ;
61+ low = mid + 1 ;
62+ } else {
63+ high = mid - 1 ;
64+ }
65+ }
66+
67+ if (best_match_idx != -1 ) {
68+ return table -> symbols [best_match_idx ].name ;
69+ }
70+
71+ return "unknown_function" ;
72+ }
73+
74+
75+ void free_symbol_table (SymbolTable * table ) {
76+ if (!table ) return ;
77+ for (int i = 0 ; i < table -> count ; ++ i ) {
78+ free (table -> symbols [i ].name );
79+ }
80+ free (table -> symbols );
81+ table -> symbols = NULL ;
82+ table -> count = 0 ;
83+ table -> capacity = 0 ;
84+ }
0 commit comments