-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathstructural_analysis.rs
More file actions
227 lines (213 loc) · 7.43 KB
/
Copy pathstructural_analysis.rs
File metadata and controls
227 lines (213 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Copyright (c) 2024-2026 Elias Bachaalany
// SPDX-License-Identifier: LicenseRef-Human-Origin-Source-1.0
//
// This file is licensed under the Human-Origin Source License v1.0.
// See LICENSE.
//
// structural_analysis: Demonstrate structural analysis RPCs (switch tables, dominators,
// post-dominators, loops) and decompile token inspection.
//
// Usage: structural_analysis [host_url]
use libghidra as ghidra;
use std::collections::HashMap;
fn main() {
let args: Vec<String> = std::env::args().collect();
let url = args.get(1).map_or("http://127.0.0.1:18080", |s| s.as_str());
let client = ghidra::connect(url);
// 1. Get server status
let status = client.get_status().unwrap_or_else(|e| {
eprintln!("get_status failed: {e}");
std::process::exit(1);
});
println!(
"Connected to {} v{} (mode={})",
status.service_name, status.service_version, status.host_mode
);
// 2. List functions and pick the first non-trivial one (size > 64 bytes)
let funcs = client
.list_functions(0, u64::MAX, 200, 0)
.unwrap_or_else(|e| {
eprintln!("list_functions failed: {e}");
std::process::exit(1);
});
let target = funcs
.functions
.iter()
.find(|f| f.size > 64)
.unwrap_or_else(|| {
eprintln!("No non-trivial function found (size > 64 bytes)");
std::process::exit(1);
});
println!(
"\nSelected function: {} at 0x{:x} ({} bytes)",
target.name, target.entry_address, target.size
);
let range_start = target.entry_address;
let range_end = target.entry_address + target.size;
// 3. Switch tables
let switch_resp = client
.list_switch_tables(range_start, range_end, 100, 0)
.unwrap_or_else(|e| {
eprintln!("list_switch_tables failed: {e}");
std::process::exit(1);
});
println!(
"\nSwitch tables ({} found):",
switch_resp.switch_tables.len()
);
for st in &switch_resp.switch_tables {
println!(
" switch at 0x{:x}: {} cases, default -> 0x{:x}",
st.switch_address, st.case_count, st.default_address
);
for c in &st.cases {
println!(" case {} -> 0x{:x}", c.value, c.target_address);
}
}
// 4. Dominators (immediate dominator tree)
let dom_resp = client
.list_dominators(range_start, range_end, 1000, 0)
.unwrap_or_else(|e| {
eprintln!("list_dominators failed: {e}");
std::process::exit(1);
});
println!("\nDominators ({} blocks):", dom_resp.dominators.len());
for d in &dom_resp.dominators {
if d.is_entry {
println!(" 0x{:x} [ENTRY] depth={}", d.block_address, d.depth);
} else {
println!(
" 0x{:x} idom=0x{:x} depth={}",
d.block_address, d.idom_address, d.depth
);
}
}
// Build dominator tree children map for summary
let mut dom_children: HashMap<u64, Vec<u64>> = HashMap::new();
for d in &dom_resp.dominators {
if !d.is_entry {
dom_children
.entry(d.idom_address)
.or_default()
.push(d.block_address);
}
}
let max_dom_depth = dom_resp
.dominators
.iter()
.map(|d| d.depth)
.max()
.unwrap_or(0);
println!(" Max dominator tree depth: {max_dom_depth}");
// 5. Post-dominators (immediate post-dominator tree)
let pdom_resp = client
.list_post_dominators(range_start, range_end, 1000, 0)
.unwrap_or_else(|e| {
eprintln!("list_post_dominators failed: {e}");
std::process::exit(1);
});
println!(
"\nPost-dominators ({} blocks):",
pdom_resp.post_dominators.len()
);
for pd in &pdom_resp.post_dominators {
if pd.is_exit {
println!(" 0x{:x} [EXIT] depth={}", pd.block_address, pd.depth);
} else {
println!(
" 0x{:x} ipdom=0x{:x} depth={}",
pd.block_address, pd.ipdom_address, pd.depth
);
}
}
let max_pdom_depth = pdom_resp
.post_dominators
.iter()
.map(|pd| pd.depth)
.max()
.unwrap_or(0);
println!(" Max post-dominator tree depth: {max_pdom_depth}");
// 6. Loops (natural loops detected via back edges)
let loops_resp = client
.list_loops(range_start, range_end, 100, 0)
.unwrap_or_else(|e| {
eprintln!("list_loops failed: {e}");
std::process::exit(1);
});
println!("\nLoops ({} found):", loops_resp.loops.len());
for lp in &loops_resp.loops {
println!(
" header=0x{:x} back_edge_from=0x{:x} kind={} blocks={} depth={}",
lp.header_address, lp.back_edge_source, lp.loop_kind, lp.block_count, lp.depth
);
}
// 7. Decompile the function and inspect tokens
let decomp_resp = client
.get_decompilation(target.entry_address, 30000)
.unwrap_or_else(|e| {
eprintln!("get_decompilation failed: {e}");
std::process::exit(1);
});
let decomp = decomp_resp.decompilation.unwrap_or_else(|| {
eprintln!("No decompilation returned");
std::process::exit(1);
});
println!("\nDecompilation of '{}':", decomp.function_name);
println!(" Prototype: {}", decomp.prototype);
println!(" Completed: {}", decomp.completed);
println!(" Locals: {}", decomp.locals.len());
println!(" Tokens: {}", decomp.tokens.len());
// Token kind histogram
let mut kind_counts: HashMap<String, usize> = HashMap::new();
for tok in &decomp.tokens {
*kind_counts.entry(format!("{:?}", tok.kind)).or_default() += 1;
}
println!("\n Token kind breakdown:");
let mut sorted_kinds: Vec<_> = kind_counts.into_iter().collect();
sorted_kinds.sort_by(|a, b| b.1.cmp(&a.1));
for (kind, count) in &sorted_kinds {
println!(" {kind:<16} {count}");
}
// Show first 20 tokens as a sample
let sample_count = decomp.tokens.len().min(20);
println!("\n First {sample_count} tokens:");
for tok in decomp.tokens.iter().take(sample_count) {
let extra = if !tok.var_name.is_empty() {
format!(" (var={})", tok.var_name)
} else {
String::new()
};
println!(
" L{}:C{} {:?} {:?}{}",
tok.line_number, tok.column_offset, tok.kind, tok.text, extra
);
}
// 8. Summary
println!(
"\n--- Structural Analysis Summary for '{}' ---",
target.name
);
println!(" Function size: {} bytes", target.size);
println!(
" Switch tables: {}",
switch_resp.switch_tables.len()
);
println!(
" Total switch cases: {}",
switch_resp
.switch_tables
.iter()
.map(|s| s.case_count)
.sum::<u32>()
);
println!(" Dominator nodes: {}", dom_resp.dominators.len());
println!(" Max dom depth: {max_dom_depth}");
println!(
" Post-dominator nodes: {}",
pdom_resp.post_dominators.len()
);
println!(" Max pdom depth: {max_pdom_depth}");
println!(" Natural loops: {}", loops_resp.loops.len());
println!(" Decompile tokens: {}", decomp.tokens.len());
println!(" Decompile locals: {}", decomp.locals.len());
}