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
use crate::assembly::{AssemblerConfig, Instructions};
use crate::common::{FromFFI, into_optional};
use crate::{declare_fwd_iterator, declare_lazy_iterator, to_slice};
use bitflags::bitflags;
use lief_ffi as ffi;
use std::pin::Pin;
/// Trait shared by all the symbols in executable formats
pub trait Symbol {
#[doc(hidden)]
fn as_generic(&self) -> &ffi::AbstractSymbol;
#[doc(hidden)]
fn as_pin_mut_generic(&mut self) -> Pin<&mut ffi::AbstractSymbol>;
/// Symbol's name
fn name(&self) -> String {
self.as_generic().name().to_string()
}
/// Symbol's value whose interpretation depends on the symbol's kind.
/// Usually this is the address of the symbol though.
fn value(&self) -> u64 {
self.as_generic().value()
}
/// Size of the symbol (can be 0)
fn size(&self) -> u64 {
self.as_generic().size()
}
fn set_name(&mut self, name: &str) {
cxx::let_cxx_string!(__cxx_s = name.to_string());
self.as_pin_mut_generic().set_name(&__cxx_s);
}
fn set_value(&mut self, value: u64) {
self.as_pin_mut_generic().set_value(value);
}
fn set_size(&mut self, size: u64) {
self.as_pin_mut_generic().set_size(size);
}
}
impl std::fmt::Debug for &dyn Symbol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Symbol")
.field("name", &self.name())
.field("value", &self.value())
.field("size", &self.size())
.finish()
}
}
/// Trait shared by all the sections in executable formats
pub trait Section {
#[doc(hidden)]
fn as_generic(&self) -> &ffi::AbstractSection;
#[doc(hidden)]
fn as_generic_mut(&mut self) -> Pin<&mut ffi::AbstractSection>;
/// Name of the section
fn name(&self) -> String {
self.as_generic().name().to_string()
}
/// Size of the section **in the file**
fn size(&self) -> u64 {
self.as_generic().size()
}
/// Offset of the section **in the file**
fn offset(&self) -> u64 {
self.as_generic().offset()
}
/// Address of the section **in memory**
fn virtual_address(&self) -> u64 {
self.as_generic().virtual_address()
}
/// Content of the section
fn content(&self) -> &[u8] {
to_slice!(self.as_generic().content());
}
/// Change the section's name
fn set_name(&mut self, name: &str) {
cxx::let_cxx_string!(__cxx_s = name.to_string());
self.as_generic_mut().set_name(&__cxx_s);
}
/// Change section content
fn set_content(&mut self, data: &[u8]) {
unsafe {
self.as_generic_mut().set_content(data.as_ptr(), data.len());
}
}
/// Change section size
fn set_size(&mut self, size: u64) {
self.as_generic_mut().set_size(size);
}
}
impl std::fmt::Debug for &dyn Section {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Section")
.field("name", &self.name())
.field("size", &self.size())
.field("offset", &self.offset())
.field("virtual_address", &self.virtual_address())
.finish()
}
}
pub trait Relocation {
#[doc(hidden)]
fn as_generic(&self) -> &ffi::AbstractRelocation;
/// Address where the relocation should take place
fn address(&self) -> u64 {
self.as_generic().address()
}
/// Size of the relocation
fn size(&self) -> u64 {
self.as_generic().size()
}
}
impl std::fmt::Debug for &dyn Relocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Relocation")
.field("address", &self.address())
.field("size", &self.size())
.finish()
}
}
/// Generic interface representing a binary executable.
///
/// This trait provides a unified interface across multiple binary formats
/// such as ELF, PE, Mach-O, and others. It enables users to access binary
/// components like headers, sections, symbols, relocations,
/// and functions in a format-agnostic way.
pub trait Binary {
#[doc(hidden)]
fn as_generic(&self) -> &ffi::AbstractBinary;
#[doc(hidden)]
fn as_pin_mut_generic(&mut self) -> Pin<&mut ffi::AbstractBinary>;
/// Binary's entrypoint
fn entrypoint(&self) -> u64 {
self.as_generic().entrypoint()
}
/// Default base address where the binary should be mapped
fn imagebase(&self) -> u64 {
self.as_generic().imagebase()
}
/// Size of the binary when mapped in memory
fn virtual_size(&self) -> u64 {
self.as_generic().virtual_size()
}
/// Whether the current binary is **an executable** and **position independent**
fn is_pie(&self) -> bool {
self.as_generic().is_pie()
}
/// Whether the binary defines a non-executable stack
fn has_nx(&self) -> bool {
self.as_generic().has_nx()
}
/// Original file size of the binary
fn original_size(&self) -> u64 {
self.as_generic().original_size()
}
/// Return the debug info if present. It can be either a
/// [`crate::pdb::DebugInfo`] or [`crate::dwarf::DebugInfo`].
///
/// For ELF and Mach-O binaries, it returns the given DebugInfo object **only**
/// if the binary embeds the DWARF debug info in the binary itself.
///
/// For PE file, this function tries to find the **external** PDB using
/// the [`crate::pe::debug::CodeViewPDB::filename`] output (if present). One can also
/// use [`crate::pdb::load`] or [`crate::pdb::DebugInfo::from`] to get PDB debug
/// info.
///
/// <div class="warning">
/// This function requires LIEF's extended version otherwise it always return `None`
/// </div>
fn debug_info(&self) -> Option<crate::DebugInfo<'_>> {
into_optional(self.as_generic().debug_info())
}
/// Disassemble code starting at the given virtual address and with the given
/// size.
///
/// ```
/// let insts = binary.disassemble(0xacde, 100);
/// for inst in insts {
/// println!("{}", inst.to_string());
/// }
/// ```
///
/// See also [`crate::assembly::Instruction`] and [`crate::assembly::Instructions`]
fn disassemble(&self, address: u64, size: u64) -> InstructionsIt<'_> {
InstructionsIt::new(self.as_generic().disassemble(address, size))
}
/// Disassemble code for the given symbol name
///
/// ```
/// let insts = binary.disassemble_symbol("__libc_start_main");
/// for inst in insts {
/// println!("{}", inst.to_string());
/// }
/// ```
///
/// See also [`crate::assembly::Instruction`] and [`crate::assembly::Instructions`]
fn disassemble_symbol(&self, name: &str) -> InstructionsIt<'_> {
cxx::let_cxx_string!(__cxx_s = name.to_string());
InstructionsIt::new(self.as_generic().disassemble_function(&__cxx_s))
}
/// Disassemble code at the given virtual address
///
/// ```
/// let insts = binary.disassemble_address(0xacde);
/// for inst in insts {
/// println!("{}", inst.to_string());
/// }
/// ```
///
/// See also [`crate::assembly::Instruction`] and [`crate::assembly::Instructions`]
fn disassemble_address(&self, address: u64) -> InstructionsIt<'_> {
InstructionsIt::new(self.as_generic().disassemble_address(address))
}
/// Disassemble code provided by the given slice at the specified `address` parameter.
///
/// See also [`crate::assembly::Instruction`] and [`crate::assembly::Instructions`]
fn disassemble_slice(&self, slice: &[u8], address: u64) -> InstructionsIt<'_> {
unsafe {
InstructionsIt::new(self.as_generic().disassemble_buffer(
slice.as_ptr(),
slice.len().try_into().unwrap(),
address,
))
}
}
/// Assemble **and patch** the provided assembly code at the specified address.
///
/// The generated assembly is returned by the function
///
/// ```
/// let mut bin = get_binary();
///
/// let Vec<u8> bytes = bin.assemble(0x12000440, r#"
/// xor rax, rbx;
/// mov rcx, rax;
/// "#);
/// ```
fn assemble(&mut self, address: u64, asm: &str) -> Vec<u8> {
cxx::let_cxx_string!(__cxx_s = asm);
Vec::from(
self.as_pin_mut_generic()
.assemble(address, &__cxx_s)
.as_slice(),
)
}
/// Same as [`Binary::assemble`] but this function takes an extra [`AssemblerConfig`] that
/// is used to configure the assembly engine: dialect, symbols definitions.
fn assemble_with_config(
&mut self,
address: u64,
asm: &str,
config: &AssemblerConfig,
) -> Vec<u8> {
let ffi_config = config.into_ffi();
cxx::let_cxx_string!(__cxx_s = asm);
Vec::from(
self.as_pin_mut_generic()
.assemble_with_config(address, &__cxx_s, ffi_config.as_ref())
.as_slice(),
)
}
/// Default memory page size according to the architecture and the format of the
/// current binary
fn page_size(&self) -> u64 {
self.as_generic().page_size()
}
/// Patch the content at virtual address address with patch_value.
fn patch_address(&mut self, address: u64, patch_value: &[u8]) {
unsafe {
self.as_pin_mut_generic().patch_address_bytes(
address,
patch_value.as_ptr(),
patch_value.len().try_into().unwrap(),
);
}
}
/// Patch the address with the given value.
/// You must specify a valid size, MAX: `size_of::<usize>()`
fn patch_address_with_value(&mut self, address: u64, patch_value: u64, size: usize) {
self.as_pin_mut_generic().patch_address_value(
address,
patch_value,
size.try_into().unwrap(),
);
}
/// Convert the given offset into a virtual address.
///
/// If the `slide` parameter is provided (non-zero), it will be used as the base address
/// instead of the binary's imagebase.
fn offset_to_virtual_address(&self, offset: u64, slide: u64) -> Result<u64, crate::Error> {
let mut err: u32 = 0;
let va = self
.as_generic()
.offset_to_virtual_address(offset, slide, Pin::new(&mut err));
if err > 0 {
return Err(crate::Error::from(err));
}
Ok(va)
}
/// Load and associate an external debug file (e.g., DWARF or PDB) with this binary.
///
/// This method attempts to load the debug information from the file located at the given path,
/// and binds it to the current binary instance. If successful, it returns the
/// loaded [`crate::DebugInfo`] object.
///
/// <div class="warning">
/// It is the caller's responsibility to ensure that the debug file is
/// compatible with the binary. Incorrect associations may lead to
/// inconsistent or invalid results.
/// </div>
///
/// <div class="note">
/// This function does not verify that the debug file matches the binary's unique
/// identifier (e.g., build ID, GUID).
/// </div>
fn load_debug_info(&mut self, path: &std::path::Path) -> Option<crate::DebugInfo<'_>> {
cxx::let_cxx_string!(__cxx_s = path.to_str().unwrap());
into_optional(self.as_pin_mut_generic().load_debug_info(&__cxx_s))
}
}
/// This class provides a generic interface for accessing debug information
/// from different formats such as DWARF and PDB.
///
/// Users can use this interface to access high-level debug features like
/// resolving function addresses.
///
/// See: [`crate::pdb::DebugInfo`], [`crate::dwarf::DebugInfo`]
pub trait DebugInfo {
#[doc(hidden)]
fn as_generic(&self) -> &ffi::AbstracDebugInfo;
/// Attempt to resolve the address of the function specified by `name`.
fn find_function_address(&self, name: &str) -> Option<u64> {
cxx::let_cxx_string!(__cxx_s = name);
let mut is_set: u32 = 0;
let value = lief_ffi::AbstracDebugInfo::find_function_address(
self.as_generic(),
&__cxx_s,
std::pin::Pin::new(&mut is_set),
);
if is_set == 0 { None } else { Some(value) }
}
}
bitflags! {
/// Flags used to characterize the semantics of the function
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FunctionFlags: u32 {
const NONE = 0x0;
/// The function acts as constructor.
///
/// Usually this flag is associated with functions
/// that are located in the `.init_array`, `__mod_init_func` or `.tls` sections
const CONSTRUCTOR = 0x1;
/// The function acts as a destructor.
///
/// Usually this flag is associated with functions
/// that are located in the `.fini_array` or `__mod_term_func` sections
const DESTRUCTOR = 0x2;
/// The function is associated with Debug information
const DEBUG_INFO = 0x4;
/// The function is exported by the binary and the [`Function::address`]
/// returns its virtual address in the binary
const EXPORTED = 0x8;
/// The function is **imported** by the binary and the [`Function::address`]
/// should return 0
const IMPORTED = 0x10;
}
}
impl From<u32> for FunctionFlags {
fn from(value: u32) -> Self {
FunctionFlags::from_bits_truncate(value)
}
}
impl From<FunctionFlags> for u32 {
fn from(value: FunctionFlags) -> Self {
value.bits()
}
}
impl std::fmt::Display for FunctionFlags {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
bitflags::parser::to_writer(self, f)
}
}
/// Structure that represents a binary's function
pub struct Function {
ptr: cxx::UniquePtr<ffi::AbstractFunction>,
}
impl FromFFI<ffi::AbstractFunction> for Function {
fn from_ffi(ptr: cxx::UniquePtr<ffi::AbstractFunction>) -> Self {
Self { ptr }
}
}
impl Symbol for Function {
fn as_generic(&self) -> &lief_ffi::AbstractSymbol {
self.ptr.as_ref().unwrap().as_ref()
}
fn as_pin_mut_generic(&mut self) -> Pin<&mut ffi::AbstractSymbol> {
unsafe {
Pin::new_unchecked({
(self.ptr.as_ref().unwrap().as_ref() as *const ffi::AbstractSymbol
as *mut ffi::AbstractSymbol)
.as_mut()
.unwrap()
})
}
}
}
impl Function {
/// Flags characterizing the semantics of the function
pub fn flags(&self) -> FunctionFlags {
FunctionFlags::from(self.ptr.flags())
}
/// Address of the function (if not imported)
pub fn address(&self) -> u64 {
self.ptr.address()
}
}
impl std::fmt::Debug for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Function")
.field("name", &self.name())
.field("address", &self.address())
.field("flags", &self.flags())
.finish()
}
}
declare_fwd_iterator!(
Functions,
Function,
ffi::AbstractFunction,
ffi::AbstractBinary,
ffi::AbstractBinary_it_functions
);
declare_lazy_iterator!(
InstructionsIt,
Instructions,
ffi::asm_Instruction,
ffi::AbstractBinary,
ffi::AbstractBinary_it_instructions
);