idakit 0.2.0

Idiomatic Rust bindings for IDA Pro's idalib kernel
Documentation
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Enumerates a database's functions, reads them through the [`Function`] view, and edits them
//! through the [`FunctionEdit`] cursor.
//!
//! [`FunctionEdit`] carries the whole-prototype writes ([`set_type`](FunctionEdit::set_type),
//! [`clear_type`](FunctionEdit::clear_type)) and the field-at-a-time surgery verbs
//! ([`set_return_type`](FunctionEdit::set_return_type),
//! [`set_arg_type`](FunctionEdit::set_arg_type), [`rename_arg`](FunctionEdit::rename_arg),
//! [`set_calling_convention`](FunctionEdit::set_calling_convention),
//! [`prepend_this`](FunctionEdit::prepend_this)). A surgery verb reads the existing prototype,
//! mutates one field, and re-applies; a failure is a typed
//! [`TypeWriteError`](crate::types::TypeWriteError).

use std::ffi::c_int;

use idakit_sys as sys;
use serde::{Deserialize, Serialize};

use crate::Database;
use crate::address::Address;
use crate::bitness::Bitness;
use crate::decompiler::DecompiledFunction;
use crate::decompiler::ctree::Ctree;
use crate::error::{Error, Result};
use crate::ffi::nul_checked;
use crate::flowchart::{FlowChart, flowchart_flags};
use crate::instruction::Instructions;
use crate::location::{LocationMut, PendingInvalidation};
use crate::stack::StackFrame;
use crate::types::{Type, TypeExpr, TypeInfo, walk_type};
use crate::xref::Xrefs;

mod signature;

pub use signature::CallingConvention;
use signature::sig_result;

impl Database {
    /// A typed cursor at `address`.
    ///
    /// Does not verify a function lives there; absence surfaces lazily. Use
    /// [`functions`](Self::functions) to enumerate real ones.
    #[inline]
    #[must_use]
    #[doc(alias("get_func"))]
    pub fn function(&self, address: Address) -> Function<'_> {
        Function::new(address, self)
    }

    /// A view of the function containing `address`, or `None` if none does.
    ///
    /// The read-only mirror of [`function_mut`](Self::function_mut): it normalizes to the
    /// containing function's entry, so a mid-body address and the entry yield the same view.
    /// Unlike [`function`](Self::function), which trusts the address you give it, this verifies a
    /// function actually lives there.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let entry = db.functions().next().unwrap().address();
    /// let view = db.function_at(entry).expect("entry resolves to its function");
    /// assert_eq!(view.address(), entry);
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[inline]
    #[must_use]
    #[doc(alias("get_func"))]
    pub fn function_at(&self, address: Address) -> Option<Function<'_>> {
        let entry = Address::try_new(self.func_start(address))?;
        Some(Function::new(entry, self))
    }

    /// Iterates every function in the database, in kernel order.
    #[inline]
    #[must_use]
    #[doc(alias("get_func_qty"))]
    pub fn functions(&self) -> Functions<'_> {
        Functions::new(self)
    }

    /// A write cursor for the function containing `address`, or `None` if none does.
    ///
    /// Normalizes to the function's entry, so `db.function_mut(f.address())` and a mid-body address
    /// target the same function. Acquired by the address key, not by promoting a [`Function`] view.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let entry = db.functions().next().unwrap().address();
    /// if let Some(mut function) = db.function_mut(entry) {
    ///     function.set_type("int handler(int code)")?;
    /// }
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[inline]
    #[must_use]
    #[doc(alias("get_func"))]
    pub fn function_mut(&mut self, address: Address) -> Option<FunctionEdit<'_>> {
        let entry = Address::try_new(self.func_start(address))?;
        Some(FunctionEdit {
            inner: self.at_mut(entry),
        })
    }

    /// Runs `f` against a write cursor for the function containing `address`, or returns `None`
    /// (without calling `f`) if no function does.
    ///
    /// The scoped-closure companion to [`function_mut`](Self::function_mut).
    pub fn with_function_mut<R>(
        &mut self,
        address: Address,
        f: impl FnOnce(&mut FunctionEdit<'_>) -> R,
    ) -> Option<R> {
        let mut cursor = self.function_mut(address)?;
        Some(f(&mut cursor))
    }
}

/// A borrowed view of one function, keyed by entry address.
#[derive(Clone, Copy)]
#[doc(alias("func_t"))]
pub struct Function<'db> {
    address: Address,
    db: &'db Database,
}

impl<'db> Function<'db> {
    #[inline]
    pub(crate) fn new(address: Address, db: &'db Database) -> Self {
        Self { address, db }
    }

    /// The function's entry address.
    #[inline]
    #[must_use]
    pub const fn address(&self) -> Address {
        self.address
    }

    /// The function's name and how IDA assigned it.
    ///
    /// [`FunctionName`] carries the provenance too. A function entry always has a name (an
    /// address-derived placeholder at worst), so this is not optional.
    #[must_use]
    #[doc(alias("get_func_name"))]
    pub fn name(&self) -> FunctionName {
        let text = self.db.func_name(self.address).unwrap_or_default();
        FunctionName::from_flags(self.db.get_flags(self.address), text)
    }

    /// The one-line C prototype, or `None` if the kernel has no type info.
    #[must_use]
    #[doc(alias("print_type"))]
    pub fn prototype(&self) -> Option<String> {
        self.db.func_type(self.address)
    }

    /// Walks this function's stored prototype into an owned [`Type`].
    ///
    /// The structured counterpart to [`prototype`](Self::prototype), whose root is a
    /// [`TypeShape::Function`](crate::types::TypeShape::Function). `Ok(None)` if the kernel has
    /// no type info for the function.
    ///
    /// # Errors
    /// [`Error::Extract`] if the walked type is malformed.
    #[doc(alias("get_tinfo"))]
    pub fn prototype_type(&self) -> Result<Option<Type>> {
        // Re-point the kernel at this thread if the database moved, then walk the prototype.
        crate::claim::ensure_kernel_thread();
        walk_type(|sink| sys::walk_func_type(self.address.get(), sink)).map_err(|source| {
            Error::Extract {
                address: self.address.get(),
                source,
            }
        })
    }

    /// Lazily iterates this function's chunks, starting with the entry chunk, then any tail
    /// chunks in address order.
    ///
    /// A contiguous function yields exactly one [`FunctionChunk`].
    #[must_use]
    pub fn chunks(&self) -> FunctionChunks {
        FunctionChunks::new(self.address, self.db)
    }

    /// Total size in bytes across every chunk (entry chunk plus tails).
    ///
    /// A pure sum over [`chunks`](Self::chunks)' `[start, end)` spans, matching what
    /// `calc_func_size` computes from the same fragments. Equal to [`size`](Self::size) for a
    /// contiguous function; larger when tail chunks lie outside the entry chunk's span.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let f = db.functions().next().unwrap();
    /// assert!(f.total_size() >= f.size());
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[must_use]
    #[doc(alias("calc_func_size"))]
    pub fn total_size(&self) -> u64 {
        self.chunks()
            .map(|chunk| chunk.start.distance_to(chunk.end))
            .sum()
    }

    /// The function-level comment, or `None` if that channel carries none.
    ///
    /// Set with `set_func_cmt`, and works across every chunk; distinct from the item-level
    /// [`Database::comment`](crate::Database::comment), which reads a single address's comment.
    /// `repeatable` selects the repeatable channel (propagated to call sites) over the regular
    /// one.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let f = db.functions().next().unwrap();
    /// let _: Option<String> = f.comment(false);
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[must_use]
    #[doc(alias("get_func_cmt"))]
    pub fn comment(&self, repeatable: bool) -> Option<String> {
        self.db.func_cmt(self.address, repeatable)
    }

    /// Whether this function is known to return.
    ///
    /// Richer than [`is_noreturn`](Self::is_noreturn): consults call-site analysis (`is_noret()`)
    /// in addition to the `FUNC_NORET` flag, which matters for imported functions that have only
    /// a pointer, not a body, to analyze.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let f = db.functions().next().unwrap();
    /// if !f.is_noreturn() {
    ///     assert!(f.does_return());
    /// }
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[must_use]
    #[doc(alias("func_does_return"))]
    pub fn does_return(&self) -> bool {
        self.db.func_does_return(self.address)
    }

    /// This function's addressing width, or `None` if the entry no longer resolves to a function
    /// or reports an unrecognized width.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// let f = db.functions().next().unwrap();
    /// assert!(f.bitness().is_some());
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    #[must_use]
    #[doc(alias("get_func_bitness"))]
    pub fn bitness(&self) -> Option<Bitness> {
        Bitness::try_from_bits(self.db.func_bitness(self.address).max(0) as u8)
    }

    /// Lazily iterates this function's instructions, in address order within each chunk,
    /// across every chunk.
    ///
    /// Data items and the alignment tail are skipped; see [`Instructions`].
    #[must_use]
    pub fn instructions(&self) -> Instructions<'db> {
        Instructions::new(self.db, self.address)
    }

    /// The function's exclusive end address: the entry chunk's `end_ea`.
    ///
    /// `None` only if the entry is no longer a function.
    #[must_use]
    #[doc(alias("end_ea"))]
    pub fn end(&self) -> Option<Address> {
        Address::try_new(self.db.func_end(self.address))
    }

    /// The entry chunk's size in bytes (`end - start`), or `0` if the end is unavailable.
    ///
    /// A chunked function's tail chunks lie outside this span; walk [`chunks`](Self::chunks)
    /// for the full extent.
    #[must_use]
    pub fn size(&self) -> u64 {
        self.end().map_or(0, |end| self.address.distance_to(end))
    }

    /// Whether IDA flags this as a library function.
    #[must_use]
    #[doc(alias("FUNC_LIB"))]
    pub fn is_lib(&self) -> bool {
        sys::FuncFlags::from_bits_retain(self.db.func_flags(self.address))
            .contains(sys::FuncFlags::LIB)
    }

    /// Whether this is a thunk, a trampoline that jumps straight to another function.
    #[must_use]
    #[doc(alias("FUNC_THUNK"))]
    pub fn is_thunk(&self) -> bool {
        sys::FuncFlags::from_bits_retain(self.db.func_flags(self.address))
            .contains(sys::FuncFlags::THUNK)
    }

    /// Whether this function does not return, e.g. `exit`, `abort`.
    #[must_use]
    #[doc(alias("FUNC_NORET"))]
    pub fn is_noreturn(&self) -> bool {
        sys::FuncFlags::from_bits_retain(self.db.func_flags(self.address))
            .contains(sys::FuncFlags::NORET)
    }

    /// Iterates cross-references targeting this function's entry.
    #[must_use]
    #[doc(alias("xrefblk_t", "first_to"))]
    pub fn xrefs_to(&self) -> Xrefs {
        self.db.xrefs_to(self.address)
    }

    /// Iterates cross-references originating at this function's entry.
    #[must_use]
    #[doc(alias("xrefblk_t", "first_from"))]
    pub fn xrefs_from(&self) -> Xrefs {
        self.db.xrefs_from(self.address)
    }

    /// Decompiles this function.
    ///
    /// # Errors
    /// [`Error::HexRaysInit`] if the decompiler could not be initialized, [`Error::Decompile`]
    /// if Hex-Rays rejected this function, or [`Error::KernelExit`] if decompilation trapped a
    /// fatal exit.
    #[doc(alias("decompile_func"))]
    pub fn decompile(&self) -> Result<DecompiledFunction<'db>> {
        self.db.decompile(self.address)
    }

    /// Decompiles and materializes the ctree in one step.
    ///
    /// [`decompile`](Self::decompile) then [`DecompiledFunction::ctree`]; use the two-step form
    /// when you also need the [`DecompiledFunction`] itself.
    ///
    /// # Errors
    /// Propagates [`decompile`](Self::decompile)'s errors, plus [`Error::Extract`] if the ctree
    /// fails to materialize.
    pub fn ctree(&self) -> Result<Ctree> {
        let cfunc = self.decompile()?;
        cfunc.ctree().map_err(|source| Error::Extract {
            address: self.address.get(),
            source,
        })
    }

    /// Snapshots this function's stack frame, or `Ok(None)` if it has none.
    ///
    /// The disassembly-level stack layout, no decompilation needed; see [`Database::frame`].
    ///
    /// # Errors
    /// [`Error::Extract`] if a stack variable's type could not be structured.
    #[doc(alias("get_func_frame"))]
    pub fn frame(&self) -> Result<Option<StackFrame>> {
        self.db.frame(self.address)
    }

    /// Snapshots this view's scalar facts into an owned [`FunctionSnapshot`] that can leave the
    /// kernel thread.
    #[must_use]
    pub fn snapshot(&self) -> FunctionSnapshot {
        FunctionSnapshot {
            address: self.address,
            name: self.name(),
            prototype: self.prototype(),
        }
    }
}

#[bon::bon]
impl<'db> Function<'db> {
    /// Builds this function's control-flow graph with default options.
    ///
    /// The whole function is covered, tail chunks included. See [`FlowChart`] and
    /// [`flowchart_with`](Self::flowchart_with) for the knobs.
    ///
    /// # Errors
    /// [`Error::NoFunction`] if the entry address no longer resolves to a function.
    #[doc(alias("qflow_chart_t"))]
    pub fn flowchart(&self) -> Result<FlowChart> {
        self.db.flowchart(self.address)
    }

    /// Builds this function's CFG with non-default options.
    ///
    /// `call_ends` splits a block after every call instruction, `externals(false)` drops the
    /// out-of-function [`ExternalExit`](crate::flowchart::ExternalExit) edges (jump/call targets
    /// outside the function), and `predecessors(false)` skips predecessor lists (a cheaper
    /// build when only forward edges are needed).
    ///
    /// # Errors
    /// [`Error::NoFunction`] if the entry address no longer resolves to a function.
    #[builder]
    #[doc(alias("qflow_chart_t"))]
    pub fn flowchart_with(
        &self,
        #[builder(default = false)] call_ends: bool,
        #[builder(default = true)] externals: bool,
        #[builder(default = true)] predecessors: bool,
    ) -> Result<FlowChart> {
        self.db.build_flowchart(
            self.address,
            flowchart_flags(call_ends, externals, predecessors),
        )
    }
}

/// A write cursor for one function, from [`Database::function_mut`].
///
/// Composes a [`LocationMut`] cursor at the function's entry address. Read-capable: the common
/// [`Function`] reads ([`name`](Self::name), [`prototype`](Self::prototype)) are inherent here,
/// delegating to the view, so a read-modify-write stays on one cursor. Not obtainable from a
/// borrowing [`Function`].
///
/// Prototype and name writes evict this function's cached decompilation and its direct callers', so
/// the next [`decompile`](Database::decompile) reflects the change. Eviction is coalesced to when
/// the cursor drops, so a read-modify-write sweeps callers once regardless of how many writes it
/// made; opt out with [`auto_invalidate(false)`](Self::auto_invalidate).
pub struct FunctionEdit<'db> {
    inner: LocationMut<'db>,
}

impl FunctionEdit<'_> {
    /// The function's entry address.
    #[inline]
    #[must_use]
    pub const fn address(&self) -> Address {
        self.inner.address()
    }

    /// The function's name and how IDA assigned it.
    #[must_use]
    #[doc(alias("get_func_name"))]
    pub fn name(&self) -> FunctionName {
        self.inner.db().function(self.inner.address()).name()
    }

    /// The one-line C prototype, or `None` if the kernel has no type info.
    #[must_use]
    #[doc(alias("print_type"))]
    pub fn prototype(&self) -> Option<String> {
        self.inner.db().function(self.inner.address()).prototype()
    }

    /// The function's exclusive end address, or `None` if the entry is no longer a function.
    #[must_use]
    #[doc(alias("end_ea"))]
    pub fn end(&self) -> Option<Address> {
        self.inner.db().function(self.inner.address()).end()
    }

    /// Toggle automatic decompilation-cache invalidation on the writes this cursor performs.
    ///
    /// On by default: this cursor's prototype and name writes evict this function's cached
    /// decompilation and its direct callers' when the cursor drops, so the next
    /// [`decompile`](crate::Database::decompile) reflects the change. Disable it for a bulk edit
    /// where you will invalidate once at the end (see [`Database::clear_decompilation_cache`]).
    #[must_use]
    pub fn auto_invalidate(mut self, on: bool) -> Self {
        self.inner = self.inner.auto_invalidate(on);
        self
    }

    /// Rename the function.
    ///
    /// Renaming keeps [`ctree`](Function::ctree) correct everywhere, since names resolve fresh, but
    /// the cached pseudocode text at call sites is stale until eviction, which this does.
    ///
    /// # Errors
    /// [`Error::WriteRejected`] if the kernel rejects the rename, or [`Error::InteriorNul`] if
    /// `name` contains a NUL byte.
    #[doc(alias("set_name"))]
    pub fn rename(&mut self, name: impl AsRef<str>) -> Result<()> {
        self.inner.rename(name)
    }

    /// Apply a function prototype (or any type) to this function's entry.
    ///
    /// A function-typed declaration (`"int f(int)"`) sets the prototype. The database prototype is
    /// not always what the decompiler renders, since a user-pinned local-variable type can
    /// override it.
    ///
    /// # Errors
    /// [`TypeWriteError::ParseFailed`](crate::types::TypeWriteError::ParseFailed) for an unparseable declaration,
    /// [`TypeWriteError::NoType`](crate::types::TypeWriteError::NoType)
    /// for an unknown named type, [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the
    /// type, or [`Error::InteriorNul`] if the input contains a NUL byte.
    #[doc(alias("apply_tinfo"))]
    pub fn set_type(&mut self, ty: impl Into<TypeExpr>) -> Result<()> {
        self.inner.set_type(ty)
    }

    /// Apply a pre-built [`TypeInfo`] handle to this function's entry.
    ///
    /// The eager-handle counterpart to [`set_type`](Self::set_type): a function-typed handle sets
    /// the prototype, and `ty` is borrowed, so one handle applies to many entries.
    ///
    /// # Errors
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel
    /// rejects the type.
    #[doc(alias("apply_tinfo"))]
    pub fn apply_type(&mut self, ty: &TypeInfo) -> Result<()> {
        self.inner.apply_type(ty)
    }

    /// Remove this function's prototype, clearing the type at its entry.
    ///
    /// Idempotent: a function with no prototype stays that way and still succeeds.
    ///
    /// # Errors
    /// [`Error::WriteRejected`] if the kernel refuses to remove the existing prototype.
    #[doc(alias("del_tinfo"))]
    pub fn clear_type(&mut self) -> Result<()> {
        self.inner.clear_type()
    }

    /// Replace this function's return type, keeping its parameters and calling convention.
    ///
    /// The surgery counterpart to respelling the whole prototype: it reads the current signature,
    /// swaps the return, and re-applies.
    ///
    /// # Errors
    /// [`TypeWriteError::NoPrototype`](crate::types::TypeWriteError::NoPrototype) if the entry has no editable prototype,
    /// [`TypeWriteError::BuildFailed`](crate::types::TypeWriteError::BuildFailed) if `ret` cannot be built,
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the rebuilt signature, or
    /// [`Error::InteriorNul`] if `ret` names a type containing a NUL byte.
    #[doc(alias("get_func_details", "create_func"))]
    pub fn set_return_type(&mut self, ret: impl Into<TypeExpr>) -> Result<()> {
        let entry = self.inner.address();
        let recipe = ret.into().checked_serialize()?;
        let result = self.inner.db_mut().func_set_rettype(entry, &recipe);
        let out = sig_result(result.code, entry, None, &result.reason);
        self.inner.queued(out, PendingInvalidation::Dependents)
    }

    /// Replace the type of parameter `index` (zero-based), keeping its name.
    ///
    /// # Errors
    /// [`TypeWriteError::NoPrototype`](crate::types::TypeWriteError::NoPrototype) if the entry has no editable prototype,
    /// [`TypeWriteError::ArgIndexOutOfRange`](crate::types::TypeWriteError::ArgIndexOutOfRange) if `index` is past the last parameter,
    /// [`TypeWriteError::BuildFailed`](crate::types::TypeWriteError::BuildFailed) if `ty` cannot be built,
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the rebuilt signature, or
    /// [`Error::InteriorNul`] if `ty` names a type containing a NUL byte.
    #[doc(alias("get_func_details", "create_func"))]
    pub fn set_arg_type(&mut self, index: usize, ty: impl Into<TypeExpr>) -> Result<()> {
        let entry = self.inner.address();
        let recipe = ty.into().checked_serialize()?;
        let result = self.inner.db_mut().func_set_argtype(entry, index, &recipe);
        let out = sig_result(
            result.code,
            entry,
            Some((index, result.arity)),
            &result.reason,
        );
        self.inner.queued(out, PendingInvalidation::Dependents)
    }

    /// Rename parameter `index` (zero-based), keeping its type.
    ///
    /// # Errors
    /// [`TypeWriteError::NoPrototype`](crate::types::TypeWriteError::NoPrototype) if the entry has no editable prototype,
    /// [`TypeWriteError::ArgIndexOutOfRange`](crate::types::TypeWriteError::ArgIndexOutOfRange) if `index` is past the last parameter, or
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the rebuilt signature; or
    /// [`Error::InteriorNul`] if `name` contains a NUL byte.
    #[doc(alias("get_func_details", "create_func"))]
    pub fn rename_arg(&mut self, index: usize, name: impl AsRef<str>) -> Result<()> {
        let entry = self.inner.address();
        let name = nul_checked(name.as_ref(), "name")?;
        let result = self.inner.db_mut().func_rename_arg(entry, index, name);
        let out = sig_result(
            result.code,
            entry,
            Some((index, result.arity)),
            &result.reason,
        );
        // A parameter name never appears at call sites, so only this function's own text is stale.
        self.inner.queued(out, PendingInvalidation::SelfOnly)
    }

    /// Set this function's calling convention.
    ///
    /// # Errors
    /// [`TypeWriteError::NoPrototype`](crate::types::TypeWriteError::NoPrototype) if the entry has no editable prototype, or
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the convention (e.g. an x86
    /// convention on a non-x86 target).
    #[doc(alias("set_cc"))]
    pub fn set_calling_convention(&mut self, cc: CallingConvention) -> Result<()> {
        let entry = self.inner.address();
        let result = self
            .inner
            .db_mut()
            .func_set_cc(entry, c_int::from(u8::from(cc)));
        let out = sig_result(result.code, entry, None, &result.reason);
        self.inner.queued(out, PendingInvalidation::Dependents)
    }

    /// Insert an implicit `this` pointer as the first parameter, shifting the rest.
    ///
    /// The idiom for turning a free function into a method: pass the owning type as a pointer
    /// (`expr::named("widget_t").pointer()`). Pair with
    /// [`set_calling_convention`](Self::set_calling_convention) for `__thiscall` where the target
    /// wants it.
    ///
    /// # Errors
    /// [`TypeWriteError::NoPrototype`](crate::types::TypeWriteError::NoPrototype) if the entry has no editable prototype,
    /// [`TypeWriteError::BuildFailed`](crate::types::TypeWriteError::BuildFailed) if `this` cannot be built,
    /// [`TypeWriteError::ApplyRejected`](crate::types::TypeWriteError::ApplyRejected) if the kernel rejects the rebuilt signature, or
    /// [`Error::InteriorNul`] if `this` names a type containing a NUL byte.
    #[doc(alias("get_func_details", "create_func"))]
    pub fn prepend_this(&mut self, this: impl Into<TypeExpr>) -> Result<()> {
        let entry = self.inner.address();
        let recipe = this.into().checked_serialize()?;
        let result = self.inner.db_mut().func_prepend_this(entry, &recipe);
        let out = sig_result(result.code, entry, None, &result.reason);
        self.inner.queued(out, PendingInvalidation::Dependents)
    }
}

impl std::fmt::Debug for FunctionEdit<'_> {
    // Skips the exclusively-held `&mut Database`; only the key is printable.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FunctionEdit")
            .field("address", &self.address())
            .finish_non_exhaustive()
    }
}

/// An owned, `Send` snapshot of a function's scalar facts, detached from the database.
///
/// A [`Function`] borrows the [`Database`], so it is `!Send` and can't leave the kernel's
/// current thread; collect snapshots to carry results across a thread boundary.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct FunctionSnapshot {
    /// Entry address.
    pub address: Address,
    /// Name and how IDA assigned it.
    pub name: FunctionName,
    /// One-line C prototype, if the kernel had type info.
    pub prototype: Option<String>,
}

/// A function's name together with how IDA assigned it, from [`Function::name`].
///
/// Derefs to the name text, so it reads as the `str` it carries; match the variant to branch on
/// provenance. Every function entry has a name, since IDA names even an unnamed one with at
/// least an address-derived placeholder, so `name()` yields this directly, never an `Option`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[doc(alias("FF_NAME", "FF_LABL"))]
pub enum FunctionName {
    /// An explicit name: user-assigned, or an imported/mangled symbol.
    User(String),
    /// A name IDA generated from analysis (a recognized stub, library match, or thunk), e.g.
    /// `nullsub_0` or `j_malloc`.
    Auto(String),
    /// An address-derived placeholder for an otherwise-unnamed function, e.g. `sub_401000`.
    Dummy(String),
}

impl FunctionName {
    /// The name text, whatever its provenance.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::User(s) | Self::Auto(s) | Self::Dummy(s) => s,
        }
    }

    /// Whether this is an explicit name, user-assigned or an imported symbol.
    #[inline]
    #[must_use]
    pub fn is_user(&self) -> bool {
        matches!(self, Self::User(_))
    }

    /// Whether IDA generated this name from analysis.
    #[inline]
    #[must_use]
    pub fn is_auto(&self) -> bool {
        matches!(self, Self::Auto(_))
    }

    /// Whether this is an address-derived placeholder.
    #[inline]
    #[must_use]
    pub fn is_dummy(&self) -> bool {
        matches!(self, Self::Dummy(_))
    }

    /// Classifies from an address's flags and its resolved name text.
    ///
    /// The two name bits partition cleanly: `FF_NAME` alone is an explicit name, both bits an
    /// IDA-generated one, `FF_LABL` alone a placeholder. A function entry always carries one of
    /// the three, so the flag-less case folds to [`Dummy`](Self::Dummy); unreachable in
    /// practice, pinned by the name sweep test. The bit logic mirrors IDA's
    /// `has_user_name`/`has_auto_name`/`has_dummy_name`, held in step by the alignment test.
    fn from_flags(flags: u64, text: String) -> Self {
        let named = flags & sys::FF_NAME != 0;
        let labeled = flags & sys::FF_LABL != 0;
        match (named, labeled) {
            (true, false) => Self::User(text),
            (true, true) => Self::Auto(text),
            _ => Self::Dummy(text),
        }
    }
}

/// Consume the classification into the owned name string it carries.
impl From<FunctionName> for String {
    #[inline]
    fn from(name: FunctionName) -> Self {
        match name {
            FunctionName::User(s) | FunctionName::Auto(s) | FunctionName::Dummy(s) => s,
        }
    }
}

impl std::ops::Deref for FunctionName {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl std::fmt::Display for FunctionName {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::fmt::Debug for Function<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Function")
            .field("address", &self.address)
            .field("name", &self.name())
            .finish()
    }
}

key_identity!(Function, address, ord);

/// A lazy iterator over every function in the database, in kernel order, from
/// [`Database::functions`].
#[doc(alias("getn_func"))]
pub struct Functions<'db> {
    db: &'db Database,
    next: usize,
    count: usize,
}

impl<'db> Functions<'db> {
    #[inline]
    pub(crate) fn new(db: &'db Database) -> Self {
        Self {
            db,
            next: 0,
            count: db.func_qty(),
        }
    }
}

impl<'db> Iterator for Functions<'db> {
    type Item = Function<'db>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while self.next < self.count {
            let raw = self.db.func_ea(self.next);
            self.next += 1;
            if let Some(address) = Address::try_new(raw) {
                return Some(Function::new(address, self.db));
            }
        }
        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.count - self.next))
    }
}

impl std::fmt::Debug for Functions<'_> {
    // Skips the borrowed `&Database`; only cursor position is printable.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Functions")
            .field("next", &self.next)
            .field("count", &self.count)
            .finish_non_exhaustive()
    }
}

/// A contiguous address range belonging to a function: `[start, end)`.
///
/// A function is one chunk when contiguous, or several when the compiler scattered its body
/// into tail chunks placed elsewhere. Yielded by [`Function::chunks`].
///
/// Ordered by `start` then `end`, so a sorted list of chunks reads in address order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[doc(alias("func_tail_iterator_t"))]
pub struct FunctionChunk {
    /// First address of the chunk.
    pub start: Address,
    /// One-past-the-last address of the chunk.
    pub end: Address,
}

/// A lazy iterator over a function's chunks, entry chunk first then tail chunks in address
/// order, from [`Function::chunks`].
///
/// Materializes the chunk ranges once as an owned snapshot on construction, so it holds no
/// database borrow while iterating.
#[doc(alias("func_tail_iterator_t"))]
pub struct FunctionChunks {
    chunks: std::vec::IntoIter<FunctionChunk>,
}

impl FunctionChunks {
    #[inline]
    pub(crate) fn new(address: Address, db: &Database) -> Self {
        Self::from_chunks(
            db.range_all_chunks(address)
                .into_iter()
                .filter_map(|r| {
                    Some(FunctionChunk {
                        start: Address::try_new(r.start)?,
                        end: Address::try_new(r.end)?,
                    })
                })
                .collect(),
        )
    }

    #[inline]
    pub(crate) fn from_chunks(chunks: Vec<FunctionChunk>) -> Self {
        Self {
            chunks: chunks.into_iter(),
        }
    }
}

impl Iterator for FunctionChunks {
    type Item = FunctionChunk;

    #[inline]
    fn next(&mut self) -> Option<FunctionChunk> {
        self.chunks.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.chunks.size_hint()
    }
}

impl ExactSizeIterator for FunctionChunks {}

impl std::fmt::Debug for FunctionChunks {
    // Prints the remaining chunks directly rather than the raw `vec::IntoIter` type name.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FunctionChunks")
            .field("remaining", &self.chunks.as_slice())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use assert2::assert;

    use super::*;

    const fn assert_send<T: Send>() {}

    // Both owned so they can cross the kernel-thread boundary, unlike the borrowed Function view.
    const _: () = assert_send::<FunctionSnapshot>();
    const _: () = assert_send::<FunctionName>();

    #[test]
    fn from_flags_classifies_by_the_two_name_bits() {
        assert!(
            FunctionName::from_flags(sys::FF_NAME, "s".into()) == FunctionName::User("s".into())
        );
        assert!(
            FunctionName::from_flags(sys::FF_NAME | sys::FF_LABL, "s".into())
                == FunctionName::Auto("s".into())
        );
        assert!(
            FunctionName::from_flags(sys::FF_LABL, "s".into()) == FunctionName::Dummy("s".into())
        );
        // No name flag at all folds to a placeholder (unreachable for a function entry).
        assert!(FunctionName::from_flags(0, "s".into()) == FunctionName::Dummy("s".into()));
    }

    #[test]
    fn from_flags_ignores_unrelated_bits() {
        // Bits outside the two name bits (code/data class, etc.) must not perturb it.
        let noise = 0xFFFF_FFFF_FFFF_3FFFu64; // every bit except FF_NAME (0x4000) and FF_LABL (0x8000)
        assert!(
            FunctionName::from_flags(noise | sys::FF_NAME, "x".into())
                == FunctionName::User("x".into())
        );
        assert!(
            FunctionName::from_flags(noise | sys::FF_LABL, "x".into())
                == FunctionName::Dummy("x".into())
        );
    }

    #[test]
    fn accessors_project_text_and_kind() {
        let u = FunctionName::User("main".into());
        assert!(u.as_str() == "main");
        assert!(&*u == "main");
        assert!(format!("{u}") == "main");
        assert!(String::from(u.clone()) == "main");
        assert!(u.is_user() && !u.is_auto() && !u.is_dummy());
        assert!(FunctionName::Dummy("sub_1000".into()).is_dummy());
        assert!(FunctionName::Auto("nullsub_0".into()).is_auto());
    }

    #[test]
    fn from_flags_matches_ida_predicates() {
        // Our FF_NAME/FF_LABL derivation must agree with IDA's own has_*_name predicates for
        // every combination of the two name bits, regardless of surrounding flag bits, so a
        // future SDK that redefines the bits, or a typo in our constants, fails here.
        for extra in [0u64, 0x1234_5678, u64::MAX] {
            let extra = extra & !(sys::FF_NAME | sys::FF_LABL);
            for &bits in &[0, sys::FF_NAME, sys::FF_LABL, sys::FF_NAME | sys::FF_LABL] {
                let flags = extra | bits;
                let ours = FunctionName::from_flags(flags, String::new());
                // has_*_name are pure bit tests over `flags`, requiring no kernel state and no
                // open database.
                let (user, auto, dummy) = (
                    sys::has_user_name(flags),
                    sys::has_auto_name(flags),
                    sys::has_dummy_name(flags),
                );
                assert!(ours.is_user() == user);
                assert!(ours.is_auto() == auto);
                // IDA's dummy always maps to ours; ours additionally absorbs the no-name case.
                assert!(ours.is_dummy() == (!user && !auto));
                if dummy {
                    assert!(ours.is_dummy());
                }
            }
        }
    }

    #[test]
    fn function_chunk_ord_sorts_by_start_then_end() {
        let low = FunctionChunk {
            start: Address::try_new(0x1000).unwrap(),
            end: Address::try_new(0x1010).unwrap(),
        };
        let high = FunctionChunk {
            start: Address::try_new(0x2000).unwrap(),
            end: Address::try_new(0x2010).unwrap(),
        };
        let mut chunks = vec![high, low];
        chunks.sort();
        assert!(chunks == vec![low, high]);
    }

    #[test]
    fn function_name_serde_round_trips() {
        let name = FunctionName::User("main".into());
        let json = serde_json::to_string(&name).unwrap();
        let back: FunctionName = serde_json::from_str(&json).unwrap();
        assert!(back == name);
    }

    #[test]
    fn function_snapshot_serde_round_trips() {
        let snapshot = FunctionSnapshot {
            address: Address::try_new(0x0040_1000).unwrap(),
            name: FunctionName::Auto("nullsub_0".into()),
            prototype: Some("void nullsub_0(void)".into()),
        };
        let json = serde_json::to_string(&snapshot).unwrap();
        let back: FunctionSnapshot = serde_json::from_str(&json).unwrap();
        assert!(back == snapshot);
    }
}