ds_decomp/analysis/
functions.rs

1use std::{
2    backtrace::Backtrace,
3    collections::{BTreeMap, BTreeSet},
4};
5
6use snafu::Snafu;
7use unarm::{
8    args::{Argument, Reg, Register},
9    thumb, ArmVersion, Endian, Ins, ParseFlags, ParseMode, ParsedIns, Parser,
10};
11
12use crate::{
13    config::symbol::{SymbolMap, SymbolMapError},
14    util::bytes::FromSlice,
15};
16
17use super::{
18    function_branch::FunctionBranchState,
19    function_start::is_valid_function_start,
20    illegal_code::IllegalCodeState,
21    inline_table::{InlineTable, InlineTableState},
22    jump_table::{JumpTable, JumpTableState},
23    secure_area::SecureAreaState,
24};
25
26// All keys in the types below are instruction addresses
27pub type Labels = BTreeSet<u32>;
28pub type PoolConstants = BTreeSet<u32>;
29pub type JumpTables = BTreeMap<u32, JumpTable>;
30pub type InlineTables = BTreeMap<u32, InlineTable>;
31pub type FunctionCalls = BTreeMap<u32, CalledFunction>;
32pub type DataLoads = BTreeMap<u32, u32>;
33
34#[derive(Debug, Clone)]
35pub struct Function {
36    name: String,
37    start_address: u32,
38    end_address: u32,
39    first_instruction_address: u32,
40    thumb: bool,
41    labels: Labels,
42    pool_constants: PoolConstants,
43    jump_tables: JumpTables,
44    inline_tables: InlineTables,
45    function_calls: FunctionCalls,
46}
47
48#[derive(Debug, Snafu)]
49pub enum FunctionAnalysisError {
50    #[snafu(transparent)]
51    IntoFunction { source: IntoFunctionError },
52    #[snafu(transparent)]
53    SymbolMap { source: SymbolMapError },
54}
55
56impl Function {
57    pub fn size(&self) -> u32 {
58        self.end_address - self.start_address
59    }
60
61    fn is_thumb_function(address: u32, code: &[u8]) -> bool {
62        if (address & 3) != 0 {
63            // Not 4-aligned, must be Thumb
64            true
65        } else if code.len() < 4 {
66            // Can't contain a full ARM instruction
67            true
68        } else if code[3] & 0xf0 == 0xe0 {
69            // First instruction has the AL condition code, must be ARM
70            false
71        } else {
72            // Thumb otherwise
73            true
74        }
75    }
76
77    #[allow(clippy::match_like_matches_macro)]
78    fn is_entry_instruction(ins: Ins, parsed_ins: &ParsedIns) -> bool {
79        if ins.is_conditional() {
80            return false;
81        }
82
83        let args = &parsed_ins.args;
84        match (parsed_ins.mnemonic, args[0], args[1], args[2]) {
85            (
86                "stmdb",
87                Argument::Reg(Reg { reg: Register::Sp, writeback: true, deref: false }),
88                Argument::RegList(regs),
89                Argument::None,
90            )
91            | ("push", Argument::RegList(regs), Argument::None, Argument::None)
92                if regs.contains(Register::Lr) =>
93            {
94                true
95            }
96            _ => false,
97        }
98    }
99
100    fn is_return(
101        ins: Ins,
102        parsed_ins: &ParsedIns,
103        address: u32,
104        function_start: u32,
105        module_start_address: u32,
106        module_end_address: u32,
107    ) -> bool {
108        if ins.is_conditional() {
109            return false;
110        }
111
112        let args = &parsed_ins.args;
113        match (parsed_ins.mnemonic, args[0], args[1]) {
114            // bx *
115            ("bx", _, _) => true,
116            // mov pc, *
117            ("mov", Argument::Reg(Reg { reg: Register::Pc, .. }), _) => true,
118            // ldmia *, {..., pc}
119            ("ldmia", _, Argument::RegList(reg_list)) if reg_list.contains(Register::Pc) => true,
120            // pop {..., pc}
121            ("pop", Argument::RegList(reg_list), _) if reg_list.contains(Register::Pc) => true,
122            // backwards branch
123            ("b", Argument::BranchDest(offset), _) if offset < 0 => {
124                // Branch must be within current function (infinite loop) or outside current module (tail call)
125                Self::is_branch(ins, parsed_ins, address)
126                    .map(|destination| {
127                        destination >= function_start
128                            || destination < module_start_address
129                            || destination >= module_end_address
130                    })
131                    .unwrap_or(false)
132            }
133            // subs pc, lr, *
134            ("subs", Argument::Reg(Reg { reg: Register::Pc, .. }), Argument::Reg(Reg { reg: Register::Lr, .. })) => true,
135            // ldr pc, *
136            ("ldr", Argument::Reg(Reg { reg: Register::Pc, .. }), _) => true,
137            _ => false,
138        }
139    }
140
141    fn is_branch(ins: Ins, parsed_ins: &ParsedIns, address: u32) -> Option<u32> {
142        if ins.mnemonic() != "b" {
143            return None;
144        }
145        let dest = parsed_ins.branch_destination().unwrap();
146        Some((address as i32 + dest).try_into().unwrap())
147    }
148
149    fn is_pool_load(ins: Ins, parsed_ins: &ParsedIns, address: u32, thumb: bool) -> Option<u32> {
150        if ins.mnemonic() != "ldr" {
151            return None;
152        }
153        match (parsed_ins.args[0], parsed_ins.args[1], parsed_ins.args[2]) {
154            (Argument::Reg(dest), Argument::Reg(base), Argument::OffsetImm(offset)) => {
155                if dest.reg == Register::Pc {
156                    None
157                } else if !base.deref || base.reg != Register::Pc {
158                    None
159                } else if offset.post_indexed {
160                    None
161                } else {
162                    // ldr *, [pc + *]
163                    let load_address = (address as i32 + offset.value) as u32 & !3;
164                    let load_address = load_address + if thumb { 4 } else { 8 };
165                    Some(load_address)
166                }
167            }
168            _ => None,
169        }
170    }
171
172    fn is_function_call(ins: Ins, parsed_ins: &ParsedIns, address: u32, thumb: bool) -> Option<CalledFunction> {
173        let args = &parsed_ins.args;
174        match (ins.mnemonic(), args[0], args[1]) {
175            ("bl", Argument::BranchDest(offset), Argument::None) => {
176                let destination = (address as i32 + offset) as u32;
177                Some(CalledFunction { ins, address: destination, thumb })
178            }
179            ("blx", Argument::BranchDest(offset), Argument::None) => {
180                let destination = (address as i32 + offset) as u32;
181                let destination = if thumb { destination & !3 } else { destination };
182                Some(CalledFunction { ins, address: destination, thumb: !thumb })
183            }
184            _ => None,
185        }
186    }
187
188    fn function_parser_loop(
189        mut parser: Parser<'_>,
190        options: FunctionParseOptions,
191    ) -> Result<ParseFunctionResult, FunctionAnalysisError> {
192        let thumb = parser.mode == ParseMode::Thumb;
193        let mut context = ParseFunctionContext::new(thumb, options);
194
195        let Some((address, ins, parsed_ins)) = parser.next() else { return Ok(ParseFunctionResult::NoEpilogue) };
196        if !is_valid_function_start(address, ins, &parsed_ins) {
197            return Ok(ParseFunctionResult::InvalidStart { address, ins, parsed_ins });
198        }
199
200        let state = context.handle_ins(&mut parser, address, ins, parsed_ins);
201        let result = if state.ended() {
202            return Ok(context.into_function(state)?);
203        } else {
204            loop {
205                let Some((address, ins, parsed_ins)) = parser.next() else {
206                    break context.into_function(ParseFunctionState::Done);
207                };
208                let state = context.handle_ins(&mut parser, address, ins, parsed_ins);
209                if state.ended() {
210                    break context.into_function(state);
211                }
212            }
213        };
214
215        let result = result?;
216        let ParseFunctionResult::Found(mut function) = result else {
217            return Ok(result);
218        };
219
220        if let Some(first_pool_address) = function.pool_constants.first() {
221            if *first_pool_address < function.start_address {
222                log::info!(
223                    "Function at {:#010x} was adjusted to include pre-code constant pool at {:#010x}",
224                    function.start_address,
225                    first_pool_address
226                );
227
228                function.first_instruction_address = function.start_address;
229                function.start_address = *first_pool_address;
230            }
231        }
232
233        Ok(ParseFunctionResult::Found(function))
234    }
235
236    pub fn parse_function(options: FunctionParseOptions) -> Result<ParseFunctionResult, FunctionAnalysisError> {
237        let FunctionParseOptions { start_address, base_address, module_code, parse_options, .. } = &options;
238
239        let thumb = parse_options.thumb.unwrap_or(Function::is_thumb_function(*start_address, module_code));
240        let parse_mode = if thumb { ParseMode::Thumb } else { ParseMode::Arm };
241        let start = (start_address - base_address) as usize;
242        let function_code = &module_code[start..];
243        let parser = Parser::new(
244            parse_mode,
245            *start_address,
246            Endian::Little,
247            ParseFlags { version: ArmVersion::V5Te, ual: false },
248            function_code,
249        );
250
251        Self::function_parser_loop(parser, options)
252    }
253
254    pub fn find_functions(options: FindFunctionsOptions) -> Result<BTreeMap<u32, Function>, FunctionAnalysisError> {
255        let FindFunctionsOptions {
256            default_name_prefix,
257            base_address,
258            module_code,
259            symbol_map,
260            module_start_address,
261            module_end_address,
262            search_options,
263        } = options;
264
265        let mut functions = BTreeMap::new();
266
267        let start_address = search_options.start_address.unwrap_or(base_address);
268        assert!((start_address & 1) == 0);
269        let start_offset = start_address - base_address;
270        let end_address = search_options.end_address.unwrap_or(base_address + module_code.len() as u32);
271        let end_offset = end_address - base_address;
272        let module_code = &module_code[..end_offset as usize];
273        let mut function_code = &module_code[start_offset as usize..end_offset as usize];
274
275        log::debug!("Searching for functions from {:#010x} to {:#010x}", start_address, end_address);
276
277        let mut last_function_address = search_options.last_function_address.unwrap_or(end_address);
278        let mut address = start_address;
279
280        while !function_code.is_empty() && address <= last_function_address {
281            let thumb = Function::is_thumb_function(address, function_code);
282
283            let parse_mode = if thumb { ParseMode::Thumb } else { ParseMode::Arm };
284            let parser = Parser::new(
285                parse_mode,
286                address,
287                Endian::Little,
288                ParseFlags { version: ArmVersion::V5Te, ual: false },
289                function_code,
290            );
291
292            let (name, new) = if let Some((_, symbol)) = symbol_map.by_address(address)? {
293                (symbol.name.clone(), false)
294            } else {
295                (format!("{}{:08x}", default_name_prefix, address), true)
296            };
297
298            let function_result = Function::function_parser_loop(
299                parser,
300                FunctionParseOptions {
301                    name,
302                    start_address: address,
303                    base_address,
304                    module_code,
305                    known_end_address: None,
306                    module_start_address,
307                    module_end_address,
308                    existing_functions: search_options.existing_functions,
309                    parse_options: Default::default(),
310                },
311            )?;
312            let function = match function_result {
313                ParseFunctionResult::Found(function) => function,
314                ParseFunctionResult::IllegalIns { address: illegal_address, ins, .. } => {
315                    if search_options.keep_searching_for_valid_function_start {
316                        // It's possible that we've attempted to analyze pool constants as code, which can happen if the
317                        // function has a constant pool ahead of its code.
318                        let mut next_address = (address + 1).next_multiple_of(4);
319                        if let Some(function_addresses) = search_options.function_addresses.as_ref() {
320                            if let Some(&next_function) = function_addresses.range(address + 1..).next() {
321                                next_address = next_function;
322                            }
323                        }
324                        address = next_address;
325                        function_code = &module_code[(address - base_address) as usize..];
326                        continue;
327                    } else {
328                        if thumb {
329                            log::debug!(
330                                "Terminating function analysis due to illegal instruction at {:#010x}: {:04x}",
331                                illegal_address,
332                                ins.code()
333                            );
334                        } else {
335                            log::debug!(
336                                "Terminating function analysis due to illegal instruction at {:#010x}: {:08x}",
337                                illegal_address,
338                                ins.code()
339                            );
340                        }
341                        break;
342                    }
343                }
344                ParseFunctionResult::NoEpilogue => {
345                    log::debug!(
346                        "Terminating function analysis due to no epilogue in function starting from {:#010x}",
347                        address
348                    );
349                    break;
350                }
351                ParseFunctionResult::InvalidStart { address: start_address, ins, parsed_ins } => {
352                    if search_options.keep_searching_for_valid_function_start {
353                        let ins_size = parse_mode.instruction_size(0);
354                        address += ins_size as u32;
355                        function_code = &function_code[ins_size..];
356                        continue;
357                    } else {
358                        if thumb {
359                            log::debug!(
360                                "Terminating function analysis due to invalid function start at {:#010x}: {:04x} {}",
361                                start_address,
362                                ins.code(),
363                                parsed_ins.display(Default::default())
364                            );
365                        } else {
366                            log::debug!(
367                                "Terminating function analysis due to invalid function start at {:#010x}: {:08x} {}",
368                                start_address,
369                                ins.code(),
370                                parsed_ins.display(Default::default())
371                            );
372                        }
373                        break;
374                    }
375                }
376            };
377
378            if new {
379                symbol_map.add_function(&function);
380            }
381            function.add_local_symbols_to_map(symbol_map)?;
382
383            address = function.end_address;
384            function_code = &module_code[(address - base_address) as usize..];
385
386            // Look for pointers to data in this module, to use as an upper bound for finding functions
387            if search_options.use_data_as_upper_bound {
388                for pool_constant in function.iter_pool_constants(module_code, base_address) {
389                    let pointer_value = pool_constant.value & !1;
390                    if pointer_value >= last_function_address {
391                        continue;
392                    }
393                    if pointer_value >= start_address && pointer_value >= address {
394                        let offset = (pointer_value - base_address) as usize;
395                        if offset < module_code.len() {
396                            let thumb = Function::is_thumb_function(pointer_value, &module_code[offset..]);
397                            let mut parser = Parser::new(
398                                if thumb { ParseMode::Thumb } else { ParseMode::Arm },
399                                pointer_value,
400                                Endian::Little,
401                                ParseFlags { ual: false, version: ArmVersion::V5Te },
402                                &module_code[offset..],
403                            );
404                            let (address, ins, parsed_ins) = parser.next().unwrap();
405                            if !is_valid_function_start(address, ins, &parsed_ins) {
406                                // The pool constant points to data, limit the upper bound
407                                last_function_address = pointer_value;
408                                log::debug!(
409                                    "Upper bound found: address to data at {:#010x} from pool constant at {:#010x} from function {}",
410                                    pool_constant.value,
411                                    pool_constant.address,
412                                    function.name
413                                );
414                            }
415                        }
416                    }
417                }
418            }
419
420            functions.insert(function.first_instruction_address, function);
421        }
422        Ok(functions)
423    }
424
425    pub fn add_local_symbols_to_map(&self, symbol_map: &mut SymbolMap) -> Result<(), SymbolMapError> {
426        for address in self.labels.iter() {
427            symbol_map.add_label(*address, self.thumb)?;
428        }
429        for address in self.pool_constants.iter() {
430            symbol_map.add_pool_constant(*address)?;
431        }
432        for jump_table in self.jump_tables() {
433            symbol_map.add_jump_table(jump_table)?;
434        }
435        for inline_table in self.inline_tables().values() {
436            symbol_map.add_data(None, inline_table.address, (*inline_table).into())?;
437        }
438        Ok(())
439    }
440
441    pub fn find_secure_area_functions(
442        module_code: &[u8],
443        base_addr: u32,
444        symbol_map: &mut SymbolMap,
445    ) -> BTreeMap<u32, Function> {
446        let mut functions = BTreeMap::new();
447
448        let parse_flags = ParseFlags { ual: false, version: ArmVersion::V5Te };
449
450        let mut address = base_addr;
451        let mut state = SecureAreaState::default();
452        for ins_code in module_code.chunks_exact(2) {
453            let ins_code = u16::from_le_slice(ins_code);
454            let ins = thumb::Ins::new(ins_code as u32, &parse_flags);
455            let parsed_ins = ins.parse(&parse_flags);
456
457            state = state.handle(address, &parsed_ins);
458            if let Some(function) = state.get_function() {
459                let function = Function {
460                    name: function.name().to_string(),
461                    start_address: function.start(),
462                    end_address: function.end(),
463                    first_instruction_address: function.start(),
464                    thumb: true,
465                    labels: Labels::new(),
466                    pool_constants: PoolConstants::new(),
467                    jump_tables: JumpTables::new(),
468                    inline_tables: InlineTables::new(),
469                    function_calls: FunctionCalls::new(),
470                };
471                symbol_map.add_function(&function);
472                functions.insert(function.first_instruction_address, function);
473            }
474
475            address += 2;
476        }
477
478        functions
479    }
480
481    pub fn parser<'a>(&'a self, module_code: &'a [u8], base_address: u32) -> Parser<'a> {
482        Parser::new(
483            if self.thumb { ParseMode::Thumb } else { ParseMode::Arm },
484            self.start_address,
485            Endian::Little,
486            ParseFlags { ual: false, version: ArmVersion::V5Te },
487            self.code(module_code, base_address),
488        )
489    }
490
491    pub fn code<'a>(&self, module_code: &'a [u8], base_address: u32) -> &'a [u8] {
492        let start = (self.start_address - base_address) as usize;
493        let end = (self.end_address - base_address) as usize;
494        &module_code[start..end]
495    }
496
497    pub fn name(&self) -> &str {
498        &self.name
499    }
500
501    pub fn start_address(&self) -> u32 {
502        self.start_address
503    }
504
505    pub fn end_address(&self) -> u32 {
506        self.end_address
507    }
508
509    pub fn first_instruction_address(&self) -> u32 {
510        self.first_instruction_address
511    }
512
513    pub fn is_thumb(&self) -> bool {
514        self.thumb
515    }
516
517    pub fn labels(&self) -> impl Iterator<Item = &u32> {
518        self.labels.iter()
519    }
520
521    pub fn jump_tables(&self) -> impl Iterator<Item = &JumpTable> {
522        self.jump_tables.values()
523    }
524
525    pub fn inline_tables(&self) -> &InlineTables {
526        &self.inline_tables
527    }
528
529    pub fn get_inline_table_at(&self, address: u32) -> Option<&InlineTable> {
530        Self::inline_table_at(&self.inline_tables, address)
531    }
532
533    fn inline_table_at(inline_tables: &InlineTables, address: u32) -> Option<&InlineTable> {
534        inline_tables.values().find(|table| address >= table.address && address < table.address + table.size)
535    }
536
537    pub fn pool_constants(&self) -> &PoolConstants {
538        &self.pool_constants
539    }
540
541    pub fn iter_pool_constants<'a>(
542        &'a self,
543        module_code: &'a [u8],
544        base_address: u32,
545    ) -> impl Iterator<Item = PoolConstant> + 'a {
546        self.pool_constants.iter().map(move |&address| {
547            let start = (address - base_address) as usize;
548            let bytes = &module_code[start..];
549            PoolConstant { address, value: u32::from_le_slice(bytes) }
550        })
551    }
552
553    pub fn function_calls(&self) -> &FunctionCalls {
554        &self.function_calls
555    }
556}
557
558#[derive(Default)]
559pub struct FunctionParseOptions<'a> {
560    pub name: String,
561    pub start_address: u32,
562    pub base_address: u32,
563    pub module_code: &'a [u8],
564    pub known_end_address: Option<u32>,
565    pub module_start_address: u32,
566    pub module_end_address: u32,
567    pub existing_functions: Option<&'a BTreeMap<u32, Function>>,
568
569    pub parse_options: ParseFunctionOptions,
570}
571
572pub struct FindFunctionsOptions<'a> {
573    pub default_name_prefix: &'a str,
574    pub base_address: u32,
575    pub module_code: &'a [u8],
576    pub symbol_map: &'a mut SymbolMap,
577    pub module_start_address: u32,
578    pub module_end_address: u32,
579
580    pub search_options: FunctionSearchOptions<'a>,
581}
582
583struct ParseFunctionContext<'a> {
584    name: String,
585    start_address: u32,
586    thumb: bool,
587    end_address: Option<u32>,
588    known_end_address: Option<u32>,
589    labels: Labels,
590    pool_constants: PoolConstants,
591    jump_tables: JumpTables,
592    inline_tables: InlineTables,
593    function_calls: FunctionCalls,
594
595    module_start_address: u32,
596    module_end_address: u32,
597    existing_functions: Option<&'a BTreeMap<u32, Function>>,
598
599    /// Address of last conditional instruction, so we can detect the final return instruction
600    last_conditional_destination: Option<u32>,
601    /// Address of last pool constant, to get the function's true end address
602    last_pool_address: Option<u32>,
603    /// State machine for detecting jump tables and adding them as symbols
604    jump_table_state: JumpTableState,
605    /// State machine for detecting branches (B, not BL) to other functions
606    function_branch_state: FunctionBranchState,
607    /// State machine for detecting inline data tables within the function
608    inline_table_state: InlineTableState,
609    /// State machine for detecting illegal code sequences
610    illegal_code_state: IllegalCodeState,
611
612    prev_ins: Option<Ins>,
613    prev_parsed_ins: Option<ParsedIns>,
614    prev_address: Option<u32>,
615}
616
617#[derive(Debug, Snafu)]
618pub enum IntoFunctionError {
619    #[snafu(display("Cannot turn parse context into function before parsing is done"))]
620    NotDone { backtrace: Backtrace },
621}
622
623impl<'a> ParseFunctionContext<'a> {
624    pub fn new(thumb: bool, options: FunctionParseOptions<'a>) -> Self {
625        let FunctionParseOptions {
626            name,
627            start_address,
628            known_end_address,
629            module_start_address,
630            module_end_address,
631            existing_functions,
632            ..
633        } = options;
634
635        Self {
636            name,
637            start_address,
638            thumb,
639            end_address: None,
640            known_end_address,
641            labels: Labels::new(),
642            pool_constants: PoolConstants::new(),
643            jump_tables: JumpTables::new(),
644            inline_tables: InlineTables::new(),
645            function_calls: FunctionCalls::new(),
646
647            module_start_address,
648            module_end_address,
649            existing_functions,
650
651            last_conditional_destination: None,
652            last_pool_address: None,
653            jump_table_state: if thumb {
654                JumpTableState::Thumb(Default::default())
655            } else {
656                JumpTableState::Arm(Default::default())
657            },
658            function_branch_state: Default::default(),
659            inline_table_state: Default::default(),
660            illegal_code_state: Default::default(),
661
662            prev_ins: None,
663            prev_parsed_ins: None,
664            prev_address: None,
665        }
666    }
667
668    fn handle_ins_inner(&mut self, parser: &mut Parser, address: u32, ins: Ins, parsed_ins: &ParsedIns) -> ParseFunctionState {
669        if self.pool_constants.contains(&address) {
670            parser.seek_forward(address + 4);
671            return ParseFunctionState::Continue;
672        }
673        if let Some(inline_table) = Function::inline_table_at(&self.inline_tables, address) {
674            parser.seek_forward(inline_table.address + inline_table.size);
675            return ParseFunctionState::Continue;
676        }
677
678        self.jump_table_state = self.jump_table_state.handle(address, ins, parsed_ins, &mut self.jump_tables);
679        self.last_conditional_destination = self.last_conditional_destination.max(self.jump_table_state.table_end_address());
680        if let Some(label) = self.jump_table_state.get_label(address, ins) {
681            self.labels.insert(label);
682            self.last_conditional_destination = self.last_conditional_destination.max(Some(label));
683        }
684
685        if self.jump_table_state.is_numerical_jump_offset() {
686            // Not an instruction, continue
687            return ParseFunctionState::Continue;
688        }
689
690        let ins_size = if let Ins::Thumb(thumb_ins) = ins {
691            if thumb_ins.op != thumb::Opcode::Bl && thumb_ins.op != thumb::Opcode::BlxI {
692                // Typical Thumb instruction
693                2
694            } else if matches!(parsed_ins.args[0], Argument::BranchDest(_)) {
695                // Combined BL/BLX instruction
696                4
697            } else {
698                // Not combined
699                return ParseFunctionState::IllegalIns { address, ins, parsed_ins: parsed_ins.clone() };
700            }
701        } else {
702            // ARM instruction
703            4
704        };
705
706        self.illegal_code_state = self.illegal_code_state.handle(ins, parsed_ins);
707        if self.illegal_code_state.is_illegal() {
708            return ParseFunctionState::IllegalIns { address, ins, parsed_ins: parsed_ins.clone() };
709        }
710
711        let in_conditional_block = Some(address) < self.last_conditional_destination;
712        let is_return = Function::is_return(
713            ins,
714            parsed_ins,
715            address,
716            self.start_address,
717            self.module_start_address,
718            self.module_end_address,
719        );
720        if !in_conditional_block && is_return {
721            let end_address = address + ins_size;
722            if let Some(destination) = Function::is_branch(ins, parsed_ins, address) {
723                let outside_function = destination < self.start_address || destination >= end_address;
724                if outside_function {
725                    // Tail call
726                    self.function_calls.insert(address, CalledFunction { ins, address: destination, thumb: self.thumb });
727                }
728            }
729
730            // We're not inside a conditional code block, so this is the final return instruction
731            self.end_address = Some(address + ins_size);
732            return ParseFunctionState::Done;
733        }
734
735        if address > self.start_address && Function::is_entry_instruction(ins, parsed_ins) {
736            'check_tail_call: {
737                let Some(prev_ins) = self.prev_ins else {
738                    break 'check_tail_call;
739                };
740                let Some(prev_parsed_ins) = self.prev_parsed_ins.as_ref() else {
741                    break 'check_tail_call;
742                };
743                let Some(prev_address) = self.prev_address else {
744                    break 'check_tail_call;
745                };
746                if Function::is_branch(prev_ins, prev_parsed_ins, prev_address).is_some() {
747                    let is_conditional = in_conditional_block || prev_ins.is_conditional();
748                    if is_conditional {
749                        // Tail call
750                        self.end_address = Some(address);
751                        return ParseFunctionState::Done;
752                    }
753                }
754            };
755        }
756
757        self.function_branch_state = self.function_branch_state.handle(ins, parsed_ins);
758        if let Some(destination) = Function::is_branch(ins, parsed_ins, address) {
759            let in_current_module = destination >= self.module_start_address && destination < self.module_end_address;
760            if !in_current_module {
761                // Tail call
762                self.function_calls.insert(address, CalledFunction { ins, address: destination, thumb: self.thumb });
763            } else if self.function_branch_state.is_function_branch()
764                || self.existing_functions.map(|functions| functions.contains_key(&destination)).unwrap_or(false)
765            {
766                if !ins.is_conditional() && !in_conditional_block {
767                    // This is an unconditional backwards function branch, which means this function has ended
768                    self.end_address = Some(address + ins_size);
769                    return ParseFunctionState::Done;
770                } else {
771                    // TODO: Always run this (move it outside of else block). SectionExt::relocatable_code must take condition
772                    // code into account so the game matches after linking
773                    self.function_calls.insert(address, CalledFunction { ins, address: destination, thumb: self.thumb });
774                }
775            } else {
776                // Normal branch instruction, insert a label
777                if let Some(state) = self.handle_label(destination, address, parser, ins_size) {
778                    return state;
779                }
780            }
781        }
782
783        if let Some(pool_address) = Function::is_pool_load(ins, parsed_ins, address, self.thumb) {
784            self.pool_constants.insert(pool_address);
785            self.last_pool_address = self.last_pool_address.max(Some(pool_address));
786        }
787
788        self.inline_table_state = self.inline_table_state.handle(self.thumb, address, parsed_ins);
789        if let Some(table) = self.inline_table_state.get_table() {
790            log::debug!("Inline table found at {:#x}, size {:#x}", table.address, table.size);
791            self.inline_tables.insert(table.address, table);
792        }
793
794        if let Some(called_function) = Function::is_function_call(ins, parsed_ins, address, self.thumb) {
795            self.function_calls.insert(address, called_function);
796        }
797
798        ParseFunctionState::Continue
799    }
800
801    pub fn handle_ins(&mut self, parser: &mut Parser, address: u32, ins: Ins, parsed_ins: ParsedIns) -> ParseFunctionState {
802        let state = self.handle_ins_inner(parser, address, ins, &parsed_ins);
803        self.prev_ins = Some(ins);
804        self.prev_parsed_ins = Some(parsed_ins);
805        self.prev_address = Some(address);
806        state
807    }
808
809    fn handle_label(
810        &mut self,
811        destination: u32,
812        address: u32,
813        parser: &mut Parser,
814        ins_size: u32,
815    ) -> Option<ParseFunctionState> {
816        self.labels.insert(destination);
817        self.last_conditional_destination = self.last_conditional_destination.max(Some(destination));
818
819        let next_address = address + ins_size;
820        if self.pool_constants.contains(&next_address) {
821            let branch_backwards = destination <= address;
822
823            // Load instructions in ARM mode can have an offset of up to ±4kB. Therefore, some functions must
824            // emit pool constants in the middle so they can all be accessed by PC-relative loads. There will
825            // also be branch instruction right before, so that the pool constants don't get executed.
826
827            // Sometimes, the pre-pool branch is conveniently placed at an actual branch in the code, and
828            // leads even further than the end of the pool constants. In that case we should already have found
829            // a label at a lower address.
830            if let Some(after_pools) = self.labels.range(address + 1..).next().copied() {
831                if after_pools > address + 0x1000 {
832                    log::warn!("Massive gap from constant pool at {:#x} to next label at {:#x}", next_address, after_pools);
833                }
834                parser.seek_forward(after_pools);
835            } else if !branch_backwards {
836                // Backwards branch with no further branch labels. This type of function contains some kind of infinite loop,
837                // hence the lack of return instruction as the final instruction.
838                self.end_address = Some(next_address);
839                return Some(ParseFunctionState::Done);
840            } else {
841                let after_pools = (next_address..).step_by(4).find(|addr| !self.pool_constants.contains(addr)).unwrap();
842                log::warn!(
843                    "No label past constant pool at {:#x}, jumping to first address not occupied by a pool constant ({:#x})",
844                    next_address,
845                    after_pools
846                );
847                parser.seek_forward(after_pools);
848            }
849        }
850
851        None
852    }
853
854    fn into_function(self, state: ParseFunctionState) -> Result<ParseFunctionResult, IntoFunctionError> {
855        match state {
856            ParseFunctionState::Continue => {
857                return NotDoneSnafu.fail();
858            }
859            ParseFunctionState::IllegalIns { address, ins, parsed_ins } => {
860                return Ok(ParseFunctionResult::IllegalIns { address, ins, parsed_ins })
861            }
862            ParseFunctionState::Done => {}
863        };
864        let Some(end_address) = self.end_address else {
865            return Ok(ParseFunctionResult::NoEpilogue);
866        };
867
868        let end_address = self
869            .known_end_address
870            .unwrap_or(end_address.max(self.last_pool_address.map(|a| a + 4).unwrap_or(0)).next_multiple_of(4));
871        if end_address > self.module_end_address {
872            return Ok(ParseFunctionResult::NoEpilogue);
873        }
874
875        Ok(ParseFunctionResult::Found(Function {
876            name: self.name,
877            start_address: self.start_address,
878            end_address,
879            first_instruction_address: self.start_address,
880            thumb: self.thumb,
881            labels: self.labels,
882            pool_constants: self.pool_constants,
883            jump_tables: self.jump_tables,
884            inline_tables: self.inline_tables,
885            function_calls: self.function_calls,
886        }))
887    }
888}
889
890#[derive(Default)]
891pub struct ParseFunctionOptions {
892    /// Whether the function is in Thumb or ARM mode, or None if it should be detected automatically.
893    pub thumb: Option<bool>,
894}
895
896enum ParseFunctionState {
897    Continue,
898    IllegalIns { address: u32, ins: Ins, parsed_ins: ParsedIns },
899    Done,
900}
901
902impl ParseFunctionState {
903    pub fn ended(&self) -> bool {
904        match self {
905            Self::Continue => false,
906            Self::IllegalIns { .. } | Self::Done => true,
907        }
908    }
909}
910
911#[derive(Debug)]
912pub enum ParseFunctionResult {
913    Found(Function),
914    IllegalIns { address: u32, ins: Ins, parsed_ins: ParsedIns },
915    NoEpilogue,
916    InvalidStart { address: u32, ins: Ins, parsed_ins: ParsedIns },
917}
918
919#[derive(Default)]
920pub struct FunctionSearchOptions<'a> {
921    /// Address to start searching from. Defaults to the base address.
922    pub start_address: Option<u32>,
923    /// Last address that a function can start from. Defaults to [`Self::end_address`].
924    pub last_function_address: Option<u32>,
925    /// Address to end the search. Defaults to the base address plus code size.
926    pub end_address: Option<u32>,
927    /// If false, end the search when an illegal starting instruction is found.
928    pub keep_searching_for_valid_function_start: bool,
929    /// If true, pointers to data will be used to limit the upper bound address.
930    pub use_data_as_upper_bound: bool,
931    /// Guarantees that all these addresses will be analyzed, even if the function analysis would terminate before they are
932    /// reached. Used for .init functions.
933    /// Note: This will override `keep_searching_for_valid_function_start`, they are not intended to be used together.
934    pub function_addresses: Option<BTreeSet<u32>>,
935    /// If a branch instruction branches into one of these functions, it will be treated as a function branch instead of
936    /// inserting a label at the branch destination.
937    /// If the function branch is unconditional, it will also be treated as a tail call and terminate the analysis of the
938    /// current function.
939    pub existing_functions: Option<&'a BTreeMap<u32, Function>>,
940}
941
942#[derive(Clone, Copy, Debug)]
943pub struct CalledFunction {
944    pub ins: Ins,
945    pub address: u32,
946    pub thumb: bool,
947}
948
949pub struct PoolConstant {
950    pub address: u32,
951    pub value: u32,
952}