threatflux_binary_analysis/
types.rs

1//! Core types and data structures for binary analysis
2
3use std::collections::HashMap;
4
5#[cfg(feature = "serde-support")]
6use serde::{Deserialize, Serialize};
7
8// Type aliases to reduce complexity
9pub type BinaryResult<T> = crate::Result<T>;
10pub type ParsedBinary = Box<dyn BinaryFormatTrait>;
11pub type ParseResult = BinaryResult<ParsedBinary>;
12pub type ImportExportResult = BinaryResult<(Vec<Import>, Vec<Export>)>;
13pub type ByteSliceResult<'a> = BinaryResult<&'a [u8]>;
14pub type PatternMatchMap =
15    HashMap<crate::utils::patterns::PatternCategory, Vec<crate::utils::patterns::PatternMatch>>;
16pub type HexPatternResult = BinaryResult<Vec<Option<u8>>>;
17pub type HexPattern = Vec<Option<u8>>;
18
19/// Supported binary formats
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
21#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
22pub enum BinaryFormat {
23    /// Executable and Linkable Format (Linux/Unix)
24    Elf,
25    /// Portable Executable (Windows)
26    Pe,
27    /// Mach Object (macOS/iOS)
28    MachO,
29    /// Java Class file
30    Java,
31    /// WebAssembly
32    Wasm,
33    /// Raw binary data
34    Raw,
35    /// Unknown format
36    #[default]
37    Unknown,
38}
39
40impl std::fmt::Display for BinaryFormat {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            BinaryFormat::Elf => write!(f, "ELF"),
44            BinaryFormat::Pe => write!(f, "PE"),
45            BinaryFormat::MachO => write!(f, "Mach-O"),
46            BinaryFormat::Java => write!(f, "Java"),
47            BinaryFormat::Wasm => write!(f, "WebAssembly"),
48            BinaryFormat::Raw => write!(f, "Raw"),
49            BinaryFormat::Unknown => write!(f, "Unknown"),
50        }
51    }
52}
53
54/// Supported architectures
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
56#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
57pub enum Architecture {
58    /// x86 32-bit
59    X86,
60    /// x86 64-bit
61    X86_64,
62    /// ARM 32-bit
63    Arm,
64    /// ARM 64-bit
65    Arm64,
66    /// MIPS
67    Mips,
68    /// MIPS 64-bit
69    Mips64,
70    /// PowerPC
71    PowerPC,
72    /// PowerPC 64-bit
73    PowerPC64,
74    /// RISC-V
75    RiscV,
76    /// RISC-V 64-bit
77    RiscV64,
78    /// WebAssembly
79    Wasm,
80    /// Java Virtual Machine
81    Jvm,
82    /// Unknown architecture
83    #[default]
84    Unknown,
85}
86
87impl std::fmt::Display for Architecture {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        match self {
90            Architecture::X86 => write!(f, "x86"),
91            Architecture::X86_64 => write!(f, "x86-64"),
92            Architecture::Arm => write!(f, "ARM"),
93            Architecture::Arm64 => write!(f, "ARM64"),
94            Architecture::Mips => write!(f, "MIPS"),
95            Architecture::Mips64 => write!(f, "MIPS64"),
96            Architecture::PowerPC => write!(f, "PowerPC"),
97            Architecture::PowerPC64 => write!(f, "PowerPC64"),
98            Architecture::RiscV => write!(f, "RISC-V"),
99            Architecture::RiscV64 => write!(f, "RISC-V64"),
100            Architecture::Wasm => write!(f, "WebAssembly"),
101            Architecture::Jvm => write!(f, "JVM"),
102            Architecture::Unknown => write!(f, "Unknown"),
103        }
104    }
105}
106
107/// Binary metadata
108#[derive(Debug, Clone)]
109#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
110pub struct BinaryMetadata {
111    /// File size in bytes
112    pub size: usize,
113    /// Detected format
114    pub format: BinaryFormat,
115    /// Target architecture
116    pub architecture: Architecture,
117    /// Entry point address
118    pub entry_point: Option<u64>,
119    /// Base address for loading
120    pub base_address: Option<u64>,
121    /// Compilation timestamp
122    pub timestamp: Option<u64>,
123    /// Compiler information
124    pub compiler_info: Option<String>,
125    /// Endianness
126    pub endian: Endianness,
127    /// Security features
128    pub security_features: SecurityFeatures,
129}
130
131/// Endianness
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
134pub enum Endianness {
135    Little,
136    Big,
137}
138
139/// Security features detected in the binary
140#[derive(Debug, Clone, Default)]
141#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
142pub struct SecurityFeatures {
143    /// Data Execution Prevention / No-Execute bit
144    pub nx_bit: bool,
145    /// Address Space Layout Randomization
146    pub aslr: bool,
147    /// Stack canaries / stack protection
148    pub stack_canary: bool,
149    /// Control Flow Integrity
150    pub cfi: bool,
151    /// Fortify source
152    pub fortify: bool,
153    /// Position Independent Executable
154    pub pie: bool,
155    /// Relocation Read-Only
156    pub relro: bool,
157    /// Signed binary
158    pub signed: bool,
159}
160
161/// Binary section information
162#[derive(Debug, Clone)]
163#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
164pub struct Section {
165    /// Section name
166    pub name: String,
167    /// Virtual address
168    pub address: u64,
169    /// Size in bytes
170    pub size: u64,
171    /// File offset
172    pub offset: u64,
173    /// Section permissions
174    pub permissions: SectionPermissions,
175    /// Section type
176    pub section_type: SectionType,
177    /// Raw data (optional, for small sections)
178    pub data: Option<Vec<u8>>,
179}
180
181/// Section permissions
182#[derive(Debug, Clone, Default)]
183#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
184pub struct SectionPermissions {
185    pub read: bool,
186    pub write: bool,
187    pub execute: bool,
188}
189
190/// Section types
191#[derive(Debug, Clone, PartialEq, Eq)]
192#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
193pub enum SectionType {
194    Code,
195    Data,
196    ReadOnlyData,
197    Bss,
198    Debug,
199    Symbol,
200    String,
201    Relocation,
202    Dynamic,
203    Note,
204    Other(String),
205}
206
207/// Symbol information
208#[derive(Debug, Clone)]
209#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
210pub struct Symbol {
211    /// Symbol name
212    pub name: String,
213    /// Demangled name (if applicable)
214    pub demangled_name: Option<String>,
215    /// Address
216    pub address: u64,
217    /// Size
218    pub size: u64,
219    /// Symbol type
220    pub symbol_type: SymbolType,
221    /// Binding
222    pub binding: SymbolBinding,
223    /// Visibility
224    pub visibility: SymbolVisibility,
225    /// Section index
226    pub section_index: Option<usize>,
227}
228
229/// Symbol types
230#[derive(Debug, Clone, PartialEq, Eq)]
231#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
232pub enum SymbolType {
233    Function,
234    Object,
235    Section,
236    File,
237    Common,
238    Thread,
239    Other(String),
240}
241
242/// Symbol binding
243#[derive(Debug, Clone, PartialEq, Eq)]
244#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
245pub enum SymbolBinding {
246    Local,
247    Global,
248    Weak,
249    Other(String),
250}
251
252/// Symbol visibility
253#[derive(Debug, Clone, PartialEq, Eq)]
254#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
255pub enum SymbolVisibility {
256    Default,
257    Internal,
258    Hidden,
259    Protected,
260}
261
262/// Import information
263#[derive(Debug, Clone)]
264#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
265pub struct Import {
266    /// Function or symbol name
267    pub name: String,
268    /// Library name
269    pub library: Option<String>,
270    /// Address (if resolved)
271    pub address: Option<u64>,
272    /// Ordinal (for PE files)
273    pub ordinal: Option<u16>,
274}
275
276/// Export information
277#[derive(Debug, Clone)]
278#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
279pub struct Export {
280    /// Function or symbol name
281    pub name: String,
282    /// Address
283    pub address: u64,
284    /// Ordinal (for PE files)
285    pub ordinal: Option<u16>,
286    /// Forwarded name (if applicable)
287    pub forwarded_name: Option<String>,
288}
289
290/// Disassembled instruction
291#[derive(Debug, Clone)]
292#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
293pub struct Instruction {
294    /// Instruction address
295    pub address: u64,
296    /// Raw instruction bytes
297    pub bytes: Vec<u8>,
298    /// Assembly mnemonic
299    pub mnemonic: String,
300    /// Operand string
301    pub operands: String,
302    /// Instruction category
303    pub category: InstructionCategory,
304    /// Control flow information
305    pub flow: ControlFlow,
306    /// Size in bytes
307    pub size: usize,
308}
309
310/// Instruction categories
311#[derive(Debug, Clone, PartialEq, Eq, Hash)]
312#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
313pub enum InstructionCategory {
314    Arithmetic,
315    Logic,
316    Memory,
317    Control,
318    System,
319    Crypto,
320    Vector,
321    Float,
322    Unknown,
323}
324
325/// Control flow information
326#[derive(Debug, Clone, PartialEq, Eq)]
327#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
328pub enum ControlFlow {
329    /// Normal sequential flow
330    Sequential,
331    /// Unconditional jump
332    Jump(u64),
333    /// Conditional jump
334    ConditionalJump(u64),
335    /// Function call
336    Call(u64),
337    /// Function return
338    Return,
339    /// Interrupt/system call
340    Interrupt,
341    /// Unknown/indirect
342    Unknown,
343}
344
345/// Basic block in control flow graph
346#[derive(Debug, Clone)]
347#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
348pub struct BasicBlock {
349    /// Block ID
350    pub id: usize,
351    /// Start address
352    pub start_address: u64,
353    /// End address
354    pub end_address: u64,
355    /// Instructions in this block
356    pub instructions: Vec<Instruction>,
357    /// Successor blocks
358    pub successors: Vec<usize>,
359    /// Predecessor blocks
360    pub predecessors: Vec<usize>,
361    /// Block type classification
362    pub block_type: BlockType,
363    /// Dominator block ID (if computed)
364    pub dominator: Option<usize>,
365    /// Dominance frontier block IDs
366    pub dominance_frontier: Vec<usize>,
367}
368
369/// Control flow graph
370#[derive(Debug, Clone)]
371#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
372pub struct ControlFlowGraph {
373    /// Function information
374    pub function: Function,
375    /// Basic blocks
376    pub basic_blocks: Vec<BasicBlock>,
377    /// Complexity metrics
378    pub complexity: ComplexityMetrics,
379    /// Detected loops (enhanced analysis)
380    pub loops: Vec<Loop>,
381}
382
383/// Function information
384#[derive(Debug, Clone)]
385#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
386pub struct Function {
387    /// Function name
388    pub name: String,
389    /// Start address
390    pub start_address: u64,
391    /// End address
392    pub end_address: u64,
393    /// Size in bytes
394    pub size: u64,
395    /// Function type
396    pub function_type: FunctionType,
397    /// Calling convention
398    pub calling_convention: Option<String>,
399    /// Parameters (if available)
400    pub parameters: Vec<Parameter>,
401    /// Return type (if available)
402    pub return_type: Option<String>,
403}
404
405/// Function types
406#[derive(Debug, Clone, PartialEq, Eq)]
407#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
408pub enum FunctionType {
409    Normal,
410    Constructor,
411    Destructor,
412    Operator,
413    Main,
414    Entrypoint,
415    Import,
416    Export,
417    Thunk,
418    Unknown,
419}
420
421/// Function parameter
422#[derive(Debug, Clone)]
423#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
424pub struct Parameter {
425    /// Parameter name
426    pub name: Option<String>,
427    /// Parameter type
428    pub param_type: String,
429    /// Register or stack location
430    pub location: ParameterLocation,
431}
432
433/// Parameter location
434#[derive(Debug, Clone, PartialEq)]
435#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
436pub enum ParameterLocation {
437    Register(String),
438    Stack(i64),
439    Unknown,
440}
441
442/// Complexity metrics for control flow
443#[derive(Debug, Clone, Default)]
444#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
445pub struct ComplexityMetrics {
446    /// Cyclomatic complexity
447    pub cyclomatic_complexity: u32,
448    /// Number of basic blocks
449    pub basic_block_count: u32,
450    /// Number of edges
451    pub edge_count: u32,
452    /// Depth of nesting
453    pub nesting_depth: u32,
454    /// Number of loops
455    pub loop_count: u32,
456    /// Cognitive complexity (different from cyclomatic)
457    pub cognitive_complexity: u32,
458    /// Halstead metrics (if calculated)
459    pub halstead_metrics: Option<HalsteadMetrics>,
460    /// Maintainability index (if calculated)
461    pub maintainability_index: Option<f64>,
462}
463
464/// Halstead metrics for software complexity
465#[derive(Debug, Clone)]
466#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
467pub struct HalsteadMetrics {
468    /// Number of distinct operators
469    pub n1: u32,
470    /// Number of distinct operands
471    pub n2: u32,
472    /// Total number of operators
473    pub capital_n1: u32,
474    /// Total number of operands
475    pub capital_n2: u32,
476    /// Program vocabulary
477    pub vocabulary: u32,
478    /// Program length
479    pub length: u32,
480    /// Calculated length
481    pub calculated_length: f64,
482    /// Volume
483    pub volume: f64,
484    /// Difficulty
485    pub difficulty: f64,
486    /// Effort
487    pub effort: f64,
488    /// Time required to program
489    pub time: f64,
490    /// Number of delivered bugs
491    pub bugs: f64,
492}
493
494/// Loop types for enhanced control flow analysis
495#[derive(Debug, Clone, PartialEq, Eq, Hash)]
496#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
497pub enum LoopType {
498    /// Single entry point (reducible)
499    Natural,
500    /// Multiple entry points
501    Irreducible,
502    /// Test at end
503    DoWhile,
504    /// Test at beginning
505    While,
506    /// Counted loop with induction variable
507    For,
508    /// No clear exit condition
509    Infinite,
510    /// Unknown loop type
511    Unknown,
512}
513
514/// Loop information for control flow analysis
515#[derive(Debug, Clone)]
516#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
517pub struct Loop {
518    /// Loop header block ID
519    pub header_block: usize,
520    /// Loop body block IDs
521    pub body_blocks: Vec<usize>,
522    /// Loop exit block IDs
523    pub exit_blocks: Vec<usize>,
524    /// Loop type classification
525    pub loop_type: LoopType,
526    /// Induction variables (if detected)
527    pub induction_variables: Vec<String>,
528    /// Whether this is a natural loop
529    pub is_natural: bool,
530    /// Nesting level
531    pub nesting_level: u32,
532}
533
534/// Basic block types for enhanced classification
535#[derive(Debug, Clone, PartialEq, Eq)]
536#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
537pub enum BlockType {
538    Entry,
539    Exit,
540    Normal,
541    LoopHeader,
542    LoopBody,
543    LoopExit,
544    Conditional,
545    Call,
546    Return,
547    Exception,
548}
549
550/// Entropy analysis results
551#[derive(Debug, Clone)]
552#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
553pub struct EntropyAnalysis {
554    /// Overall entropy score (0.0 - 8.0)
555    pub overall_entropy: f64,
556    /// Section-wise entropy
557    pub section_entropy: HashMap<String, f64>,
558    /// High entropy regions
559    pub high_entropy_regions: Vec<EntropyRegion>,
560    /// Packing indicators
561    pub packing_indicators: PackingIndicators,
562}
563
564/// High entropy region
565#[derive(Debug, Clone)]
566#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
567pub struct EntropyRegion {
568    /// Start offset
569    pub start: u64,
570    /// End offset
571    pub end: u64,
572    /// Entropy value
573    pub entropy: f64,
574    /// Possible explanation
575    pub description: String,
576}
577
578/// Packing indicators
579#[derive(Debug, Clone, Default)]
580#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
581pub struct PackingIndicators {
582    /// Likely packed
583    pub is_packed: bool,
584    /// Detected packer (if any)
585    pub packer_name: Option<String>,
586    /// Compression ratio estimate
587    pub compression_ratio: Option<f64>,
588    /// Obfuscation indicators
589    pub obfuscation_level: ObfuscationLevel,
590}
591
592/// Obfuscation level
593#[derive(Debug, Clone, PartialEq, Eq, Default)]
594#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
595pub enum ObfuscationLevel {
596    #[default]
597    None,
598    Low,
599    Medium,
600    High,
601    Extreme,
602}
603
604/// Security indicators
605#[derive(Debug, Clone, Default)]
606#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
607pub struct SecurityIndicators {
608    /// Suspicious API calls
609    pub suspicious_apis: Vec<String>,
610    /// Anti-debugging techniques
611    pub anti_debug: Vec<String>,
612    /// Anti-VM techniques
613    pub anti_vm: Vec<String>,
614    /// Cryptographic indicators
615    pub crypto_indicators: Vec<String>,
616    /// Network indicators
617    pub network_indicators: Vec<String>,
618    /// File system indicators
619    pub filesystem_indicators: Vec<String>,
620    /// Registry indicators (Windows)
621    pub registry_indicators: Vec<String>,
622}
623
624/// Call graph analysis results
625#[derive(Debug, Clone)]
626#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
627pub struct CallGraph {
628    /// Call graph nodes (functions)
629    pub nodes: Vec<CallGraphNode>,
630    /// Call graph edges (calls)
631    pub edges: Vec<CallGraphEdge>,
632    /// Entry point function addresses
633    pub entry_points: Vec<u64>,
634    /// Unreachable function addresses
635    pub unreachable_functions: Vec<u64>,
636    /// Call graph statistics
637    pub statistics: CallGraphStatistics,
638}
639
640/// Call graph node representing a function
641#[derive(Debug, Clone)]
642#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
643pub struct CallGraphNode {
644    /// Function address
645    pub function_address: u64,
646    /// Function name
647    pub function_name: String,
648    /// Node type classification
649    pub node_type: NodeType,
650    /// Function complexity
651    pub complexity: u32,
652    /// Number of callers
653    pub in_degree: u32,
654    /// Number of callees
655    pub out_degree: u32,
656    /// Whether function is recursive
657    pub is_recursive: bool,
658    /// Distance from entry point
659    pub call_depth: Option<u32>,
660}
661
662/// Call graph node types
663#[derive(Debug, Clone, PartialEq, Eq)]
664#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
665pub enum NodeType {
666    /// Program entry point (main, _start, DllMain)
667    EntryPoint,
668    /// Standard library function
669    Library,
670    /// User-defined function
671    Internal,
672    /// Imported function
673    External,
674    /// Function pointer or indirect call
675    Indirect,
676    /// C++ virtual method
677    Virtual,
678    /// Unknown function type
679    Unknown,
680}
681
682/// Call graph edge representing a function call
683#[derive(Debug, Clone)]
684#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
685pub struct CallGraphEdge {
686    /// Calling function address
687    pub caller: u64,
688    /// Called function address
689    pub callee: u64,
690    /// Type of call
691    pub call_type: CallType,
692    /// All call sites for this edge
693    pub call_sites: Vec<CallSite>,
694}
695
696/// Types of function calls
697#[derive(Debug, Clone, PartialEq, Eq)]
698#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
699pub enum CallType {
700    /// Direct call (call 0x401000)
701    Direct,
702    /// Indirect call (call \[eax\], call rax)
703    Indirect,
704    /// Tail call optimization (jmp)
705    TailCall,
706    /// C++ virtual method call
707    Virtual,
708    /// Recursive call (self-calling)
709    Recursive,
710    /// Call inside conditional block
711    Conditional,
712}
713
714/// Individual call site information
715#[derive(Debug, Clone)]
716#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
717pub struct CallSite {
718    /// Address of the call instruction
719    pub address: u64,
720    /// Raw instruction bytes
721    pub instruction_bytes: Vec<u8>,
722    /// Call context
723    pub context: CallContext,
724}
725
726/// Context in which a call occurs
727#[derive(Debug, Clone, PartialEq, Eq)]
728#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
729pub enum CallContext {
730    Normal,
731    Exception,
732    Loop,
733    Conditional,
734}
735
736/// Call graph statistics
737#[derive(Debug, Clone, Default)]
738#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
739pub struct CallGraphStatistics {
740    /// Total number of functions
741    pub total_functions: usize,
742    /// Total number of calls
743    pub total_calls: usize,
744    /// Direct function calls
745    pub direct_calls: usize,
746    /// Indirect function calls
747    pub indirect_calls: usize,
748    /// Recursive functions
749    pub recursive_functions: usize,
750    /// Leaf functions (make no calls)
751    pub leaf_functions: usize,
752    /// Number of entry points
753    pub entry_points: usize,
754    /// Number of unreachable functions
755    pub unreachable_functions: usize,
756    /// Maximum call depth
757    pub max_call_depth: u32,
758    /// Average call depth
759    pub average_call_depth: f64,
760    /// Number of cyclic dependencies
761    pub cyclic_dependencies: usize,
762}
763
764/// Configuration for call graph analysis
765#[derive(Debug, Clone)]
766#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
767pub struct CallGraphConfig {
768    /// Analyze indirect calls (function pointers)
769    pub analyze_indirect_calls: bool,
770    /// Detect tail call optimizations
771    pub detect_tail_calls: bool,
772    /// Resolve virtual calls (C++)
773    pub resolve_virtual_calls: bool,
774    /// Follow import thunks
775    pub follow_import_thunks: bool,
776    /// Maximum call depth to analyze
777    pub max_call_depth: Option<u32>,
778    /// Include library function calls
779    pub include_library_calls: bool,
780}
781
782impl Default for CallGraphConfig {
783    fn default() -> Self {
784        Self {
785            analyze_indirect_calls: true,
786            detect_tail_calls: true,
787            resolve_virtual_calls: false,
788            follow_import_thunks: true,
789            max_call_depth: Some(50),
790            include_library_calls: false,
791        }
792    }
793}
794
795/// Complete analysis result
796#[derive(Debug, Clone, Default)]
797#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
798pub struct AnalysisResult {
799    /// Binary format
800    pub format: BinaryFormat,
801    /// Target architecture
802    pub architecture: Architecture,
803    /// Entry point
804    pub entry_point: Option<u64>,
805    /// Binary metadata
806    pub metadata: BinaryMetadata,
807    /// Sections
808    pub sections: Vec<Section>,
809    /// Symbols
810    pub symbols: Vec<Symbol>,
811    /// Imports
812    pub imports: Vec<Import>,
813    /// Exports
814    pub exports: Vec<Export>,
815    /// Disassembly (optional)
816    pub disassembly: Option<Vec<Instruction>>,
817    /// Control flow graphs (optional)
818    pub control_flow: Option<Vec<ControlFlowGraph>>,
819    /// Entropy analysis (optional)
820    pub entropy: Option<EntropyAnalysis>,
821    /// Security indicators (optional)
822    pub security: Option<SecurityIndicators>,
823    /// Call graph analysis (optional)
824    pub call_graph: Option<CallGraph>,
825    /// Enhanced control flow analysis (optional)
826    pub enhanced_control_flow: Option<EnhancedControlFlowAnalysis>,
827}
828
829/// Enhanced control flow analysis results
830#[derive(Debug, Clone)]
831#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
832pub struct EnhancedControlFlowAnalysis {
833    /// Control flow graphs with enhanced features
834    pub control_flow_graphs: Vec<ControlFlowGraph>,
835    /// Cognitive complexity summary
836    pub cognitive_complexity_summary: CognitiveComplexityStats,
837    /// Loop analysis summary
838    pub loop_analysis_summary: LoopAnalysisStats,
839}
840
841/// Cognitive complexity statistics
842#[derive(Debug, Clone, Default)]
843#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
844pub struct CognitiveComplexityStats {
845    /// Total cognitive complexity across all functions
846    pub total_cognitive_complexity: u32,
847    /// Average cognitive complexity per function
848    pub average_cognitive_complexity: f64,
849    /// Maximum cognitive complexity in a single function
850    pub max_cognitive_complexity: u32,
851    /// Function with highest cognitive complexity
852    pub most_complex_function: Option<String>,
853    /// Number of functions analyzed
854    pub functions_analyzed: usize,
855}
856
857/// Loop analysis statistics
858#[derive(Debug, Clone, Default)]
859#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
860pub struct LoopAnalysisStats {
861    /// Total number of loops detected
862    pub total_loops: usize,
863    /// Natural loops count
864    pub natural_loops: usize,
865    /// Irreducible loops count
866    pub irreducible_loops: usize,
867    /// Nested loops count
868    pub nested_loops: usize,
869    /// Maximum nesting depth
870    pub max_nesting_depth: u32,
871    /// Loops by type
872    pub loops_by_type: HashMap<LoopType, usize>,
873}
874
875impl Default for BinaryMetadata {
876    fn default() -> Self {
877        Self {
878            size: 0,
879            format: BinaryFormat::Unknown,
880            architecture: Architecture::Unknown,
881            entry_point: None,
882            base_address: None,
883            timestamp: None,
884            compiler_info: None,
885            endian: Endianness::Little,
886            security_features: SecurityFeatures::default(),
887        }
888    }
889}
890
891/// Trait for binary format parsers
892pub trait BinaryFormatParser {
893    /// Parse binary data
894    fn parse(data: &[u8]) -> ParseResult;
895
896    /// Check if this parser can handle the data
897    fn can_parse(data: &[u8]) -> bool;
898}
899
900/// Trait implemented by all binary formats
901pub trait BinaryFormatTrait: Send + Sync {
902    /// Get format type
903    fn format_type(&self) -> BinaryFormat;
904
905    /// Get target architecture
906    fn architecture(&self) -> Architecture;
907
908    /// Get entry point
909    fn entry_point(&self) -> Option<u64>;
910
911    /// Get sections
912    fn sections(&self) -> &[Section];
913
914    /// Get symbols
915    fn symbols(&self) -> &[Symbol];
916
917    /// Get imports
918    fn imports(&self) -> &[Import];
919
920    /// Get exports
921    fn exports(&self) -> &[Export];
922
923    /// Get metadata
924    fn metadata(&self) -> &BinaryMetadata;
925}