Skip to content

Commit 4318c63

Browse files
committed
Add mapped memory regions to replace user segment editing.
1 parent f32bb49 commit 4318c63

6 files changed

Lines changed: 142 additions & 11 deletions

File tree

‎binaryninjaapi.h‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8067,6 +8067,8 @@ namespace BinaryNinja {
80678067

80688068
/*! Creates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space
80698069

8070+
\deprecated User segments are deprecated in favor of mapped memory regions; use MemoryMap::AddMappedMemoryRegion (since 5.4)
8071+
80708072
\param start Starting virtual address
80718073
\param length Length within the virtual address space
80728074
\param dataOffset Data offset in the raw file
@@ -8077,12 +8079,16 @@ namespace BinaryNinja {
80778079

80788080
/*! Creates user-defined segments that specify how data from the raw file is mapped into a virtual address space
80798081

8082+
\deprecated User segments are deprecated in favor of mapped memory regions; use MemoryMap::AddMappedMemoryRegion (since 5.4)
8083+
80808084
\param segments Segments to add to the BinaryView
80818085
*/
80828086
void AddUserSegments(const std::vector<BNSegmentInfo>& segments);
80838087

80848088
/*! Removes a user-defined segment from th current segment mapping
80858089

8090+
\deprecated User segments are deprecated in favor of mapped memory regions; use MemoryMap::RemoveMemoryRegion (since 5.4)
8091+
80868092
\param start Virtual address of the start of the segment
80878093
\param length Length of the segment
80888094
*/
@@ -8490,6 +8496,8 @@ namespace BinaryNinja {
84908496
bool hasTarget;
84918497
bool absoluteAddressMode;
84928498
bool local;
8499+
uint64_t dataOffset;
8500+
BNMemoryRegionKind kind;
84938501
};
84948502

84958503
struct ResolvedMemoryRange
@@ -8558,6 +8566,11 @@ namespace BinaryNinja {
85588566
return BNAddUnbackedMemoryRegion(m_object, name.c_str(), start, length, flags, fill);
85598567
}
85608568

8569+
bool AddMappedMemoryRegion(const std::string& name, uint64_t start, uint64_t length, uint64_t fileOffset, uint32_t flags = 0)
8570+
{
8571+
return BNAddMappedMemoryRegion(m_object, name.c_str(), start, length, fileOffset, flags);
8572+
}
8573+
85618574
bool RemoveMemoryRegion(const std::string& name)
85628575
{
85638576
return BNRemoveMemoryRegion(m_object, name.c_str());
@@ -8636,7 +8649,7 @@ namespace BinaryNinja {
86368649
return std::nullopt;
86378650
MemoryRegionInfo result {info.name, info.displayName, info.start, info.length,
86388651
info.flags, info.enabled, info.rebaseable, info.fill,
8639-
info.hasTarget, info.absoluteAddressMode, info.local};
8652+
info.hasTarget, info.absoluteAddressMode, info.local, info.dataOffset, info.kind};
86408653
BNFreeMemoryRegionInfo(&info);
86418654
return result;
86428655
}
@@ -8648,7 +8661,7 @@ namespace BinaryNinja {
86488661
return std::nullopt;
86498662
MemoryRegionInfo result {info.name, info.displayName, info.start, info.length,
86508663
info.flags, info.enabled, info.rebaseable, info.fill,
8651-
info.hasTarget, info.absoluteAddressMode, info.local};
8664+
info.hasTarget, info.absoluteAddressMode, info.local, info.dataOffset, info.kind};
86528665
BNFreeMemoryRegionInfo(&info);
86538666
return result;
86548667
}
@@ -8667,7 +8680,7 @@ namespace BinaryNinja {
86678680
auto& r = raw.regions[j];
86688681
result.regions.push_back({r.name, r.displayName, r.start, r.length,
86698682
r.flags, r.enabled, r.rebaseable, r.fill,
8670-
r.hasTarget, r.absoluteAddressMode, r.local});
8683+
r.hasTarget, r.absoluteAddressMode, r.local, r.dataOffset, r.kind});
86718684
}
86728685
BNFreeResolvedMemoryRange(&raw);
86738686
return result;
@@ -8693,6 +8706,8 @@ namespace BinaryNinja {
86938706
regions[i].hasTarget,
86948707
regions[i].absoluteAddressMode,
86958708
regions[i].local,
8709+
regions[i].dataOffset,
8710+
regions[i].kind,
86968711
});
86978712
}
86988713
BNFreeMemoryRegions(regions, count);
@@ -8717,7 +8732,7 @@ namespace BinaryNinja {
87178732
range.regions.push_back({
87188733
r.name, r.displayName, r.start, r.length,
87198734
r.flags, r.enabled, r.rebaseable, r.fill,
8720-
r.hasTarget, r.absoluteAddressMode, r.local,
8735+
r.hasTarget, r.absoluteAddressMode, r.local, r.dataOffset, r.kind,
87218736
});
87228737
}
87238738
result.push_back(std::move(range));

‎binaryninjacore.h‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@
3737
// Current ABI version for linking to the core. This is incremented any time
3838
// there are changes to the API that affect linking, including new functions,
3939
// new types, or modifications to existing functions or types.
40-
#define BN_CURRENT_CORE_ABI_VERSION 195
40+
#define BN_CURRENT_CORE_ABI_VERSION 196
4141

4242
// Minimum ABI version that is supported for loading of plugins. Plugins that
4343
// are linked to an ABI version less than this will not be able to load and
4444
// will require rebuilding. The minimum version is increased when there are
4545
// incompatible changes that break binary compatibility, such as changes to
4646
// existing types or functions.
47-
#define BN_MINIMUM_CORE_ABI_VERSION 195
47+
#define BN_MINIMUM_CORE_ABI_VERSION 196
4848

4949
#define BN_DEMANGLER_MSVC "MS"
5050
#define BN_DEMANGLER_GNU3 "GNU3"
@@ -4267,6 +4267,17 @@ extern "C"
42674267
uint64_t infoData;
42684268
} BNSectionInfo;
42694269

4270+
// Classification of a memory region by its backing. Display/diagnostic only.
4271+
BN_ENUM(uint8_t, BNMemoryRegionKind)
4272+
{
4273+
LoadSegmentMemoryRegion, // projection of an auto/user Segment (the loaded image)
4274+
MappedMemoryRegion, // maps a range of the parent file (see BNAddMappedMemoryRegion)
4275+
DataMemoryRegion, // backed by an in-memory data buffer
4276+
UnbackedMemoryRegion, // no backing; reads return the fill byte
4277+
RemoteMemoryRegion, // backed by an external FileAccessor or foreign BinaryView (ephemeral)
4278+
LogicalMemoryRegion // backed by another MemoryMap (logical view)
4279+
};
4280+
42704281
typedef struct BNMemoryRegionInfo {
42714282
char* name;
42724283
char* displayName;
@@ -4279,6 +4290,8 @@ extern "C"
42794290
bool hasTarget;
42804291
bool absoluteAddressMode;
42814292
bool local;
4293+
uint64_t dataOffset;
4294+
BNMemoryRegionKind kind;
42824295
} BNMemoryRegionInfo;
42834296

42844297
typedef struct BNResolvedMemoryRange {
@@ -5428,6 +5441,7 @@ extern "C"
54285441
BINARYNINJACOREAPI bool BNAddBinaryMemoryRegion(BNBinaryView* view, const char* name, uint64_t start, BNBinaryView* data, uint32_t flags);
54295442
BINARYNINJACOREAPI bool BNAddDataMemoryRegion(BNBinaryView* view, const char* name, uint64_t start, BNDataBuffer* data, uint32_t flags);
54305443
BINARYNINJACOREAPI bool BNAddUnbackedMemoryRegion(BNBinaryView* view, const char* name, uint64_t start, uint64_t length, uint32_t flags, uint8_t fill);
5444+
BINARYNINJACOREAPI bool BNAddMappedMemoryRegion(BNBinaryView* view, const char* name, uint64_t start, uint64_t length, uint64_t fileOffset, uint32_t flags);
54315445
BINARYNINJACOREAPI bool BNAddRemoteMemoryRegion(BNBinaryView* view, const char* name, uint64_t start, BNFileAccessor* accessor, uint32_t flags);
54325446
BINARYNINJACOREAPI bool BNRemoveMemoryRegion(BNBinaryView* view, const char* name);
54335447
BINARYNINJACOREAPI char* BNGetActiveMemoryRegionAt(BNBinaryView* view, uint64_t addr);
@@ -5590,8 +5604,11 @@ extern "C"
55905604
BINARYNINJACOREAPI void BNAddAutoSegment(BNBinaryView* view, uint64_t start, uint64_t length, uint64_t dataOffset, uint64_t dataLength, uint32_t flags);
55915605
BINARYNINJACOREAPI void BNAddAutoSegments(BNBinaryView* view, const BNSegmentInfo* segmentInfo, size_t count);
55925606
BINARYNINJACOREAPI void BNRemoveAutoSegment(BNBinaryView* view, uint64_t start, uint64_t length);
5607+
// Deprecated: user segments are superseded by mapped memory regions; use BNAddMappedMemoryRegion
55935608
BINARYNINJACOREAPI void BNAddUserSegment(BNBinaryView* view, uint64_t start, uint64_t length, uint64_t dataOffset, uint64_t dataLength, uint32_t flags);
5609+
// Deprecated: user segments are superseded by mapped memory regions; use BNAddMappedMemoryRegion
55945610
BINARYNINJACOREAPI void BNAddUserSegments(BNBinaryView* view, const BNSegmentInfo* segmentInfo, size_t count);
5611+
// Deprecated: user segments are superseded by mapped memory regions; use BNRemoveMemoryRegion
55955612
BINARYNINJACOREAPI void BNRemoveUserSegment(BNBinaryView* view, uint64_t start, uint64_t length);
55965613
BINARYNINJACOREAPI BNSegment** BNGetSegments(BNBinaryView* view, size_t* count);
55975614
BINARYNINJACOREAPI void BNFreeSegmentList(BNSegment** segments, size_t count);

‎python/binaryview.py‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
from .enums import (
4646
AnalysisState, SymbolType, Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag,
4747
TypeClass, BinaryViewEventType, FunctionGraphType, TagReferenceType, TagTypeType, RegisterValueType, DisassemblyOption,
48-
RelocationType, DerivedStringLocationType, MetadataStoreFlag
48+
RelocationType, DerivedStringLocationType, MetadataStoreFlag, MemoryRegionKind
4949
)
5050
from .exceptions import RelocationWriteException, ExternalLinkException
5151

@@ -2711,6 +2711,8 @@ class MemoryRegionInfo:
27112711
has_target: bool
27122712
absolute_address_mode: bool
27132713
local: bool
2714+
data_offset: int
2715+
kind: MemoryRegionKind
27142716

27152717
@staticmethod
27162718
def _from_core_struct(r) -> 'MemoryRegionInfo':
@@ -2724,6 +2726,8 @@ def _from_core_struct(r) -> 'MemoryRegionInfo':
27242726
has_target=r.hasTarget,
27252727
absolute_address_mode=r.absoluteAddressMode,
27262728
local=r.local,
2729+
data_offset=r.dataOffset,
2730+
kind=MemoryRegionKind(r.kind),
27272731
)
27282732

27292733
@property
@@ -3124,6 +3128,28 @@ def add_memory_region(self, name: str, start: int, source: Optional[Union['os.Pa
31243128
else:
31253129
raise NotImplementedError(f"Unsupported memory region source type: {type(source)}")
31263130

3131+
def add_mapped_memory_region(self, name: str, start: int, length: int, file_offset: int, flags: SegmentFlag = SegmentFlag(0)) -> bool:
3132+
"""
3133+
Adds a persistent memory region that maps ``[start, start + length)`` to the current file,
3134+
fully backed by ``length`` bytes starting at ``file_offset``. Fails if the mapping runs past the
3135+
end of the parent file; add a separate unbacked region (:py:func:`add_memory_region` with
3136+
``source=None``) for any additional virtual span.
3137+
3138+
This is the memory-region replacement for :py:func:`~BinaryView.add_user_segment`: the region is
3139+
identified by its stable ``name`` (usable with the flag/enable/rebase/remove/display-name methods).
3140+
3141+
Parameters:
3142+
name (str): A unique name for the memory region.
3143+
start (int): Starting virtual address.
3144+
length (int): Number of bytes mapped (both the virtual span and the file-backed length).
3145+
file_offset (int): Offset into the current file where the backing bytes begin.
3146+
flags (SegmentFlag): Flags to apply to the memory region. Defaults to 0 (no flags).
3147+
3148+
Returns:
3149+
bool: ``True`` if the memory region was successfully added, ``False`` otherwise.
3150+
"""
3151+
return core.BNAddMappedMemoryRegion(self.handle, name, start, length, file_offset, flags)
3152+
31273153
def remove_memory_region(self, name: str) -> bool:
31283154
"""Remove a memory region by name. Returns True on success."""
31293155
return core.BNRemoveMemoryRegion(self.handle, name)
@@ -10772,6 +10798,8 @@ def add_user_segment(self, start: int, length: int, data_offset: int, data_lengt
1077210798
"""
1077310799
``add_user_segment`` creates a user-defined segment that specifies how data from the raw file is mapped into a virtual address space.
1077410800
10801+
.. note:: User segments are deprecated in favor of mapped memory regions. Use :py:func:`MemoryMap.add_mapped_memory_region` instead. User segments remain supported for cases the memory-region API does not yet cover (e.g. a segment whose virtual length exceeds its file-backed data).
10802+
1077510803
:param int start: virtual address of the start of the segment
1077610804
:param int length: length of the segment (may be larger than the source data)
1077710805
:param int data_offset: offset from the parent view
@@ -10785,6 +10813,8 @@ def add_user_segments(self, segments: Union[List[SegmentInfo], List[core.BNSegme
1078510813
"""
1078610814
``add_user_segments`` Adds user-defined segments that specify how data from the raw file is mapped into a virtual address space
1078710815
10816+
.. note:: User segments are deprecated in favor of mapped memory regions. Use :py:func:`MemoryMap.add_mapped_memory_region` instead.
10817+
1078810818
:param List[core.BNSegmentInfo] segments: list of segments to add
1078910819
:rtype: None
1079010820
"""
@@ -10795,6 +10825,8 @@ def remove_user_segment(self, start: int, length: int = 0) -> None:
1079510825
"""
1079610826
``remove_user_segment`` Removes a user-defined segment from the current segment mapping. This method removes the most recently added 'user' segment that either matches the specified start address or contains it.
1079710827
10828+
.. note:: User segments are deprecated in favor of mapped memory regions. Use :py:func:`MemoryMap.remove_memory_region` instead.
10829+
1079810830
:param int start: virtual address of the start of the segment
1079910831
:param int length: length of the segment (unused)
1080010832
:rtype: None

‎rust/src/binary_view/memory_map.rs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,37 @@ use crate::segment::SegmentFlags;
66
use crate::string::{raw_to_string, BnString, IntoCStr};
77
use binaryninjacore_sys::*;
88

9+
/// Classification of a memory region by its backing (display/diagnostic only).
10+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
11+
pub enum MemoryRegionKind {
12+
/// Projection of an auto/user segment (the loaded image).
13+
LoadSegment,
14+
/// Maps a range of the parent file.
15+
Mapped,
16+
/// Backed by an in-memory data buffer.
17+
Data,
18+
/// No backing; reads return the fill byte.
19+
Unbacked,
20+
/// Backed by an external FileAccessor or foreign BinaryView (ephemeral).
21+
Remote,
22+
/// Backed by another MemoryMap (logical view).
23+
Logical,
24+
}
25+
26+
impl From<BNMemoryRegionKind> for MemoryRegionKind {
27+
fn from(kind: BNMemoryRegionKind) -> Self {
28+
use BNMemoryRegionKind::*;
29+
match kind {
30+
LoadSegmentMemoryRegion => Self::LoadSegment,
31+
MappedMemoryRegion => Self::Mapped,
32+
DataMemoryRegion => Self::Data,
33+
UnbackedMemoryRegion => Self::Unbacked,
34+
RemoteMemoryRegion => Self::Remote,
35+
LogicalMemoryRegion => Self::Logical,
36+
}
37+
}
38+
}
39+
940
/// Snapshot of a memory region's properties at the time of query.
1041
///
1142
/// This is a value type — modifying the memory map will not update existing
@@ -24,6 +55,8 @@ pub struct MemoryRegionInfo {
2455
pub has_target: bool,
2556
pub absolute_address_mode: bool,
2657
pub local: bool,
58+
pub data_offset: u64,
59+
pub kind: MemoryRegionKind,
2760
}
2861

2962
impl MemoryRegionInfo {
@@ -44,6 +77,8 @@ impl MemoryRegionInfo {
4477
has_target: region.hasTarget,
4578
absolute_address_mode: region.absoluteAddressMode,
4679
local: region.local,
80+
data_offset: region.dataOffset,
81+
kind: region.kind.into(),
4782
}
4883
}
4984
}
@@ -356,6 +391,33 @@ impl MemoryMap {
356391
}
357392
}
358393

394+
/// Adds a persistent memory region mapping `[start, start + length)` to the current file,
395+
/// fully backed by `length` bytes at `file_offset`. Fails if the mapping runs past the end of
396+
/// the parent file; add a separate unbacked region for any additional virtual span.
397+
///
398+
/// This is the memory-region replacement for user segments: the region is identified by its
399+
/// stable `name`.
400+
pub fn add_mapped_memory_region(
401+
&mut self,
402+
name: &str,
403+
start: u64,
404+
length: u64,
405+
file_offset: u64,
406+
segment_flags: Option<SegmentFlags>,
407+
) -> bool {
408+
let name_raw = name.to_cstr();
409+
unsafe {
410+
BNAddMappedMemoryRegion(
411+
self.view.handle,
412+
name_raw.as_ptr(),
413+
start,
414+
length,
415+
file_offset,
416+
segment_flags.unwrap_or_default().into_raw(),
417+
)
418+
}
419+
}
420+
359421
pub fn remove_memory_region(&mut self, name: &str) -> bool {
360422
let name_raw = name.to_cstr();
361423
unsafe { BNRemoveMemoryRegion(self.view.handle, name_raw.as_ptr()) }

‎ui/memorymap.h‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,17 @@ class BINARYNINJAUIAPI MemoryRegionDialog : public QDialog
6868
SegmentRef m_segment;
6969
std::optional<std::string> m_filePath;
7070
bool m_nameManuallyEdited = false;
71+
bool m_editExisting = false;
72+
std::string m_editName;
73+
BNMemoryRegionKind m_editKind = MappedMemoryRegion;
74+
// The full definition of the region being edited, looked up by name: the selected row is only one resolved
75+
// fragment of it when other regions overlap
76+
std::optional<BinaryNinja::MemoryRegionInfo> m_editDefinition;
7177

7278
void SelectFile();
7379
void Submit();
7480
public:
75-
MemoryRegionDialog(QWidget* parent, BinaryViewRef data, SegmentRef associatedSegment = nullptr);
81+
MemoryRegionDialog(QWidget* parent, BinaryViewRef data, SegmentRef associatedSegment = nullptr, bool editExisting = false);
7682
};
7783

7884
/*!
@@ -184,7 +190,6 @@ class BINARYNINJAUIAPI SegmentWidget : public QWidget
184190
void restoreDefaults();
185191

186192
void addMemoryRegion(SegmentRef segment);
187-
void addSegment();
188193
void editSegment(SegmentRef segment);
189194
void disableSegment(SegmentRef segment);
190195
void enableSegment(const std::string& regionName);

‎ui/uitypes.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
// there are changes to the API that affect linking, including new functions,
77
// new types, modifications to existing functions or types, or new versions
88
// of the Qt libraries.
9-
#define BN_CURRENT_UI_ABI_VERSION 22
9+
#define BN_CURRENT_UI_ABI_VERSION 23
1010

1111
// Minimum ABI version that is supported for loading of plugins. Plugins that
1212
// are linked to an ABI version less than this will not be able to load and
1313
// will require rebuilding. The minimum version is increased when there are
1414
// incompatible changes that break binary compatibility, such as changes to
1515
// existing types or functions, or a new version of Qt.
16-
#define BN_MINIMUM_UI_ABI_VERSION 22
16+
#define BN_MINIMUM_UI_ABI_VERSION 23
1717

1818
#ifdef __GNUC__
1919
#ifdef BINARYNINJAUI_LIBRARY

0 commit comments

Comments
 (0)