22#include <decode.h>
33#include <memory.h>
44#include <disasm.h>
5+ #include "ftrace.h"
56
67extern int itrace_enabled ;
8+ extern int ftrace_enabled ;
9+ extern SymbolTable * sym_table ;
710extern LLVMDisasmContextRef disasm_ctx ;
11+
12+ int indentaton_level = 0 ;
813CPU_state cpu = {};
914static int running = 1 ;
1015
@@ -14,7 +19,29 @@ void init_cpu(){
1419 memset (cpu .csr , 0 , sizeof (cpu .csr ));
1520}
1621
17-
22+ static int is_call (uint32_t inst ) {
23+ uint32_t opcode = inst & 0x7f ;
24+ uint32_t rd = (inst >> 7 ) & 0x1f ;
25+ if (opcode == 0x6f && rd == 1 ) { // JAL && rd == x1 (ra)
26+ return 1 ;
27+ }
28+ if (opcode == 0x67 && rd == 1 ) { // JALR && rd == x1 (ra)
29+ return 1 ;
30+ }
31+ return 0 ;
32+ }
33+
34+ static int is_ret (uint32_t inst ) {
35+ uint32_t opcode = inst & 0x7f ;
36+ uint32_t rs1 = (inst >> 15 ) & 0x1f ;
37+ uint32_t rd = (inst >> 7 ) & 0x1f ;
38+ uint32_t imm = (inst >> 20 ) & 0xfff ;
39+ if (opcode == 0x67 && rs1 == 1 && rd == 0 && imm == 0 ) { // JALR x0, 0(x1)
40+ return 1 ;
41+ }
42+ return 0 ;
43+ }
44+
1845void exec_once (){
1946 Decode s ;
2047 s .pc = cpu .pc ;
@@ -30,6 +57,29 @@ void exec_once(){
3057 disassemble_inst (disasm_ctx , bytes , 4 , s .pc , asm_buf , sizeof (asm_buf ));
3158 printf ("\33[1;34m0x%016lx\33[1;0m: %08x %s\n" , s .pc , s .inst , asm_buf );
3259 }
60+ if (ftrace_enabled ) {
61+ if (is_call (s .inst )) {
62+ const FuncSymbol * func_symbol = find_func (sym_table , s .pc );
63+ const char * func_name = func_symbol ? func_symbol -> name : "unknown_function" ;
64+ const uint64_t func_addr = func_symbol ? func_symbol -> address : 0 ;
65+ printf ("\33[1;34m0x%08lx\33[1;0m: " , s .pc );
66+ for (int i = 0 ; i < indentaton_level ; i ++ ) {
67+ printf (" " );
68+ }
69+ printf ("call [%s@%08lx]\n" , func_name , func_addr );
70+ indentaton_level ++ ;
71+ } else if (is_ret (s .inst )) {
72+ indentaton_level -- ;
73+ if (indentaton_level < 0 ) indentaton_level = 0 ;
74+ const FuncSymbol * func_symbol = find_func (sym_table , s .pc );
75+ const char * func_name = func_symbol ? func_symbol -> name : "unknown_function" ;
76+ printf ("\33[1;34m0x%08lx\33[1;0m: " , s .pc );
77+ for (int i = 0 ; i < indentaton_level ; i ++ ) {
78+ printf (" " );
79+ }
80+ printf ("ret [%s]\n" , func_name );
81+ }
82+ }
3383 decode_exec (& s );
3484 cpu .pc = s .dnpc ;
3585}
0 commit comments