summaryrefslogtreecommitdiff
path: root/python/firmwareninja.py
blob: 834cdd801f9e2d50f7027af3e638d92b9ceba86f (plain)
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
# coding=utf-8
# Copyright (c) 2015-2024 Vector 35 Inc
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

import ctypes
from dataclasses import dataclass
from typing import Callable, Union, Optional
from .binaryview import BinaryView, Section, DataVariable
from .variable import RegisterValue
from .enums import (
    FirmwareNinjaMemoryHeuristic,
    FirmwareNinjaMemoryAccessType,
    FirmwareNinjaSectionAnalysisMode,
    FirmwareNinjaSectionType,
)
from .function import Function
from . import _binaryninjacore as core


class FirmwareNinjaReferenceNode:
    """
    ``class FirmwareNinjaReferenceNode`` is a class for building reference trees for functions, data variables, and
    memory regions.
    """

    def __init__(self, handle=None, view=None):
        assert handle is not None, "Cannot create reference node directly, run `FirmwareNinja.get_reference_tree`"
        self._handle = handle
        self._view = view

    def __del__(self):
        if core is not None:
            core.BNFreeFirmwareNinjaReferenceNode(self._handle)

    def is_function(self) -> bool:
        """
        ``is_function`` determines if the reference tree node is for a function

        :return: True if the reference tree node is for a function, False otherwise
        :rtype: bool
        """

        return core.BNFirmwareNinjaReferenceNodeIsFunction(self._handle)

    def is_data_variable(self) -> bool:
        """
        ``is_data_variable`` determines if the reference tree node is for a data variable

        :return: True if the reference tree node is for a data variable, False otherwise
        :rtype: bool
        """

        return core.BNFirmwareNinjaReferenceNodeIsDataVariable(self._handle)

    def has_children(self) -> bool:
        """
        ``has_children`` determines if the reference tree node contains child reference tree nodes

        :return: True if the reference tree node contains children, False otherwise
        :rtype: bool
        """

        return core.BNFirmwareNinjaReferenceNodeHasChildren(self._handle)

    @property
    def function(self) -> Function:
        """
        ``function`` query the function from the reference tree node

        :return: Function contained in the reference tree node
        :rtype: Function
        """

        bn_function = core.BNFirmwareNinjaReferenceNodeGetFunction(self._handle)
        if not bn_function:
            return None

        return Function(handle=bn_function)

    @property
    def data_variable(self) -> DataVariable:
        """
        ``data_variable`` query the data variable from the reference tree node

        :return: Data variable contained in the reference tree node
        :rtype: DataVariable
        """

        try:
            bn_data_var = core.BNFirmwareNinjaReferenceNodeGetDataVariable(
                self._handle)
            if not bn_data_var:
                return None

            data_var = DataVariable.from_core_struct(bn_data_var.contents, self._view)
        finally:
            core.BNFreeDataVariable(bn_data_var)
        return data_var

    @property
    def children(self) -> list['FirmwareNinjaReferenceNode']:
        """
        ``children`` query the child reference tree nodes

        :return: Child nodes contained in the reference tree node
        :rtype: list[FirmwareNinjaReferenceNode]
        """

        count = ctypes.c_ulonglong(0)
        nodes = []
        try:
            bn_nodes = core.BNFirmwareNinjaReferenceNodeGetChildren(
                self._handle, count)
            for i in range(count.value):
                nodes.append(
                    FirmwareNinjaReferenceNode(
                        core.BNNewFirmwareNinjaReferenceNodeReference(
                            bn_nodes[i]), self._view))
        finally:
            core.BNFreeFirmwareNinjaReferenceNodes(bn_nodes, count.value)

        return nodes


@dataclass
class FirmwareNinjaDevice:
    """
    ``class FirmwareNinjaDevice`` is a class that stores information about a hardware device, including the device
    name, start address, size, and information about the device.
    """

    name: str
    start: int
    size: int
    info: str


@dataclass
class FirmwareNinjaSection:
    """
    ``class FirmwareNinjaSection`` is a class that stores information about a section identified with Firmware Ninja
    analysis, including the section type, start address, size, and entropy of the section.
    """

    type: FirmwareNinjaSectionType
    start: int
    size: int
    entropy: float


@dataclass
class FirmwareNinjaMemoryAccess:
    """
    ``class FirmwareNinjaMemoryAccess`` is a class that stores information on instructions that access regions of
    memory that are not file-backed, such as memory-mapped I/O and RAM.
    """

    instr_address: int
    mem_address: RegisterValue
    heuristic: FirmwareNinjaMemoryHeuristic
    type: FirmwareNinjaMemoryAccessType
    value: RegisterValue

    @classmethod
    def from_BNFirmwareNinjaMemoryAccess(
        cls, access: core.BNFirmwareNinjaMemoryAccess
    ) -> "FirmwareNinjaMemoryAccess":
        return cls(
            instr_address=access.instrAddress,
            mem_address=RegisterValue.from_BNRegisterValue(access.memAddress),
            heuristic=FirmwareNinjaMemoryHeuristic(access.heuristic),
            type=FirmwareNinjaMemoryAccessType(access.type),
            value=RegisterValue.from_BNRegisterValue(access.value),
        )

    @classmethod
    def to_BNFirmwareNinjaMemoryAccess(
        cls, access: "FirmwareNinjaMemoryAccess"
    ) -> core.BNFirmwareNinjaMemoryAccess:
        return core.BNFirmwareNinjaMemoryAccess(
            instrAddress=access.instr_address,
            memAddress=RegisterValue.to_BNRegisterValue(access.mem_address),
            heuristic=access.heuristic,
            type=access.type,
            value=RegisterValue.to_BNRegisterValue(access.value),
        )


@dataclass
class FirmwareNinjaFunctionMemoryAccesses:
    """
    ``class FirmwareNinjaFunctionMemoryAccesses`` is a class that stores information on accesses made by a function
    to memory regions that are not file-backed, such as memory-mapped I/O and RAM.
    """

    function: Function
    accesses: list[FirmwareNinjaMemoryAccess]

    @classmethod
    def from_BNFirmwareNinjaFunctionMemoryAccesses(
        cls,
        info: core.BNFirmwareNinjaFunctionMemoryAccesses,
        view: BinaryView,
    ) -> "FirmwareNinjaFunctionMemoryAccesses":
        accesses = []
        for i in range(info.count):
            access = info.accesses[i]
            accesses.append(
                FirmwareNinjaMemoryAccess.from_BNFirmwareNinjaMemoryAccess(
                    access.contents))

        return cls(
            function=view.get_function_at(info.start),
            accesses=accesses,
        )


@dataclass
class FirmwareNinjaDeviceAccesses:
    """
    ``class FirmwareNinjaDeviceAccesses`` is a class that stores information on the number of accesses to hardware
    devices for each board that is compatible with the current architecture. This information can be used to identify
    a board based on the number of accesses to hardware devices.
    """

    board_name: str
    total: int
    unique: int


class FirmwareNinja:
    """
    ``class FirmwareNinja`` is a class that aids in analysis of embedded firmware images. This class is only available
    in the Ultimate Edition of Binary Ninja.

    :Example:

        >>> from binaryninja import *
        >>> view = load("path/to/firmware.bin", options={"loader.imageBase": 0x100000})
        >>> fwn = FirmwareNinja(view)
        >>> fwn.get_function_memory_accesses()[0].accesses[0].mem_address
        <const ptr 0x40090028>
    """

    def __init__(self, view: BinaryView) -> None:
        self._view = view
        self._handle = core.BNCreateFirmwareNinja(view.handle)

    def __del__(self):
        if core is not None:
            core.BNFreeFirmwareNinja(self._handle)

    def store_custom_device(self, name: str, start: int, size: int,
                            info: str) -> bool:
        """
        ``store_custom_device`` stores a user-defined Firmware Ninja device in the binary view metadata

        :param str name: Name of the device
        :param int start: Start address of the device
        :param int size: Size of the device memory region
        :param str info: Information about the device
        :return: True on success, False on failure
        :rtype: bool
        """

        return core.BNFirmwareNinjaStoreCustomDevice(self._handle, name, start,
                                                     start + size, info)

    def remove_custom_device(self, name: str) -> bool:
        """
        ``remove_custom_device`` removes a user-defined Firmware Ninja device from the binary view metadata by device
        name

        :param str name: Name of the device
        :return: True on success, False on failure
        :rtype: bool
        """

        return core.BNFirmwareNinjaRemoveCustomDevice(self._handle, name)

    def query_custom_devices(self) -> list[FirmwareNinjaDevice]:
        """
        ``query_custom_devices`` queries user-defined Firmware Ninja devices from the binary view metadata

        :return: List of Firmware Ninja devices
        :rtype: list[FirmwareNinjaDevice]
        """

        devices = ctypes.POINTER(core.BNFirmwareNinjaDevice)()
        count = core.BNFirmwareNinjaQueryCustomDevices(self._handle,
                                                       ctypes.byref(devices))
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaQueryCustomDevices")

        try:
            device_list = []
            for i in range(count):
                device_list.append(
                    FirmwareNinjaDevice(
                        name=devices[i].name,
                        start=devices[i].start,
                        size=devices[i].end - devices[i].start,
                        info=devices[i].info,
                    ))

            return device_list
        finally:
            core.BNFirmwareNinjaFreeDevices(devices, count)

    def query_board_names(self) -> list[str]:
        """
        ``query_board_names`` queries the name of all boards that are compatible with the current architecture

        :return: List of board names
        :rtype: list[str]
        """

        boards = ctypes.POINTER(ctypes.c_char_p)()
        count = core.BNFirmwareNinjaQueryBoardNamesForArchitecture(
            self._handle, self._view.arch.handle, ctypes.byref(boards))
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaQueryBoardNamesForArchitecture")

        try:
            board_list = []
            for i in range(count):
                board_list.append(boards[i].decode("utf-8"))

            return board_list
        finally:
            core.BNFirmwareNinjaFreeBoardNames(boards, count)

    def query_devices_by_board_name(self,
                                    name: str) -> list[FirmwareNinjaDevice]:
        """
        ``query_devices_by_board_name`` queries the hardware device information for a specific board

        :Example:

            >>> fwn = FirmwareNinja(bv)
            >>> fwn.query_devices_by_board_name(fwn.query_board_names()[0])[0]
            FirmwareNinjaDevice(name='nand@12f', start=303, size=1024, info='marvell,orion-nand')

        :param str name: Name of the board
        :return: List of Firmware Ninja devices
        :rtype: list[FirmwareNinjaDevice]
        """

        devices = ctypes.POINTER(core.BNFirmwareNinjaDevice)()
        count = core.BNFirmwareNinjaQueryBoardDevices(self._handle,
                                                      self._view.arch.handle,
                                                      name,
                                                      ctypes.byref(devices))
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaQueryBoardDevices")

        try:
            device_list = []
            for i in range(count):
                device_list.append(
                    FirmwareNinjaDevice(
                        name=devices[i].name,
                        start=devices[i].start,
                        size=devices[i].end - devices[i].start,
                        info=devices[i].info,
                    ))

            return device_list
        finally:
            core.BNFirmwareNinjaFreeDevices(devices, count)

    def find_sections(
        self,
        high_code_entropy_threshold: float = 0.910,
        low_code_entropy_threshold: float = 0.500,
        block_size: int = 4096,
        mode: FirmwareNinjaSectionAnalysisMode = FirmwareNinjaSectionAnalysisMode
        .DetectStringsSectionAnalysisMode,
    ) -> list[FirmwareNinjaSection]:
        """
        ``find_sections`` finds sections with Firmware Ninja entropy analysis and heuristics

        :Example:

            >>> fwn = FirmwareNinja(bv)
            >>> fwn.find_sections(block_size=2048)[0].entropy
            0.48716872930526733
            >>> fwn.find_sections(block_size=2048)[0].type
            <FirmwareNinjaSectionType.DataSectionType: 1>

        :param float high_code_entropy_threshold: High code entropy threshold
        :param float low_code_entropy_threshold: Low code entropy threshold
        :param int block_size: Block size
        :param str mode: Analysis mode
        :return: List of sections
        :rtype: list[FirmwareNinjaSection]
        """

        sections = ctypes.POINTER(core.BNFirmwareNinjaSection)()
        count = core.BNFirmwareNinjaFindSectionsWithEntropy(
            self._handle,
            ctypes.byref(sections),
            high_code_entropy_threshold,
            low_code_entropy_threshold,
            block_size,
            mode,
        )
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaFindSectionsWithEntropy")

        try:
            section_list = []
            for i in range(count):
                section_list.append(
                    FirmwareNinjaSection(
                        type=FirmwareNinjaSectionType(sections[i].type),
                        start=sections[i].start,
                        size=sections[i].end - sections[i].start,
                        entropy=sections[i].entropy,
                    ))

            return section_list
        finally:
            core.BNFirmwareNinjaFreeSections(sections, count)

    def get_function_memory_accesses(
        self,
        progress_func: Callable = None
    ) -> list[FirmwareNinjaFunctionMemoryAccesses]:
        """
        ``get_function_memory_accesses`` runs analysis to find accesses to memory regions that are not file-backed, such
        as memory-mapped I/O and RAM

        :param callback progress_func: optional function to be called with the current progress and total count.
        :return: List of function memory accesses
        :rtype: list[FirmwareNinjaFunctionMemoryAccesses]
        """

        fma_info = ctypes.POINTER(
            (ctypes.POINTER(core.BNFirmwareNinjaFunctionMemoryAccesses)))()
        if progress_func is None:
            progress_cfunc = ctypes.CFUNCTYPE(
                ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
                ctypes.c_ulonglong)(lambda ctxt, cur, total: True)
        else:
            progress_cfunc = ctypes.CFUNCTYPE(
                ctypes.c_bool, ctypes.c_void_p, ctypes.c_ulonglong,
                ctypes.c_ulonglong)(
                    lambda ctxt, cur, total: progress_func(cur, total))

        count = core.BNFirmwareNinjaGetFunctionMemoryAccesses(
            self._handle, ctypes.byref(fma_info), progress_cfunc, None)
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaGetFunctionMemoryAccesses")

        try:
            fma_info_list = []
            for i in range(count):
                fma_info_list.append(
                    FirmwareNinjaFunctionMemoryAccesses.
                    from_BNFirmwareNinjaFunctionMemoryAccesses(
                        fma_info[i].contents, self._view))

            return fma_info_list
        finally:
            core.BNFirmwareNinjaFreeFunctionMemoryAccesses(fma_info, count)

    def _fma_info_list_to_array(
            self,
            fma: list[FirmwareNinjaFunctionMemoryAccesses]) -> ctypes.POINTER:
        fma_info_ptr_array = (
            ctypes.POINTER(core.BNFirmwareNinjaFunctionMemoryAccesses) *
            len(fma))()
        for i, info in enumerate(fma):
            accesses_ptr_array = (
                ctypes.POINTER(core.BNFirmwareNinjaMemoryAccess) *
                len(info.accesses))()
            for j, access in enumerate(info.accesses):
                accesses_ptr_array[j] = ctypes.pointer(
                    FirmwareNinjaMemoryAccess.to_BNFirmwareNinjaMemoryAccess(
                        access))

            fma_info_struct = core.BNFirmwareNinjaFunctionMemoryAccesses(
                start=info.function.start,
                count=len(info.accesses),
                accesses=accesses_ptr_array,
            )

            fma_info_ptr_array[i] = ctypes.pointer(fma_info_struct)

        return fma_info_ptr_array

    def store_function_memory_accesses(
            self, fma: list[FirmwareNinjaFunctionMemoryAccesses]) -> None:
        """
        ``store_function_memory_accesses`` saves information on function memory accesses to binary view metadata

        :Example:

            >>> fwn = FirmwareNinja(bv)
            >>> fma = fwn.get_function_memory_accesses()
            >>> fwn.store_function_memory_accesses(fma)

        :param list[FirmwareNinjaFunctionMemoryAccesses] fma: List of function memory accesses
        :return: None
        :rtype: None
        """

        fma_info_ptr_array = self._fma_info_list_to_array(fma)
        core.BNFirmwareNinjaStoreFunctionMemoryAccessesToMetadata(
            self._handle, fma_info_ptr_array, len(fma))

    def query_function_memory_accesses(
            self) -> list[FirmwareNinjaFunctionMemoryAccesses]:
        """
        ``query_function_memory_accesses`` queries information on function memory accesses from binary view metadata

        :return: List of function memory accesses
        :rtype: list[FirmwareNinjaFunctionMemoryAccesses]
        """

        fma = ctypes.POINTER(
            (ctypes.POINTER(core.BNFirmwareNinjaFunctionMemoryAccesses)))()
        count = core.BNFirmwareNinjaQueryFunctionMemoryAccessesFromMetadata(
            self._handle, ctypes.byref(fma))
        if count == -1:
            return None

        try:
            fma_info_list = []
            for i in range(count):
                fma_info_list.append(
                    FirmwareNinjaFunctionMemoryAccesses.
                    from_BNFirmwareNinjaFunctionMemoryAccesses(
                        fma[i].contents, self._view))

            return fma_info_list
        finally:
            core.BNFirmwareNinjaFreeFunctionMemoryAccesses(fma, count)

    def get_board_device_accesses(
        self, fma: list[FirmwareNinjaFunctionMemoryAccesses]
    ) -> list[FirmwareNinjaDeviceAccesses]:
        """
        ``get_board_device_accesses`` counts accesses made to memory-mapped hardware devices for each board that is
        compatible with the current architecture. This function can be used to help identify a board.

        :Example:

            >>> fwn = FirmwareNinja(bv)
            >>> fma = fwn.get_function_memory_accesses()
            >>> fwn.get_board_device_accesses(fma)[0]
            FirmwareNinjaDeviceAccesses(board_name='stm32mp157c-dhcom-picoitx', total=414, unique=2)

        :param list[FirmwareNinjaFunctionMemoryAccesses] fma: List of function memory accesses
        :return: List of device accesses
        :rtype: list[FirmwareNinjaDeviceAccesses]
        """

        fma_info_ptr_array = self._fma_info_list_to_array(fma)
        device_accesses = ctypes.POINTER(core.BNFirmwareNinjaDeviceAccesses)()
        count = core.BNFirmwareNinjaGetBoardDeviceAccesses(
            self._handle, fma_info_ptr_array, len(fma),
            ctypes.byref(device_accesses), self._view.arch.handle)
        if count == -1:
            raise RuntimeError("BNFirmwareNinjaGetBoardDeviceAccesses")

        try:
            device_accesses_list = []
            for i in range(count):
                device_accesses_list.append(
                    FirmwareNinjaDeviceAccesses(
                        board_name=device_accesses[i].name,
                        total=device_accesses[i].total,
                        unique=device_accesses[i].unique,
                    ))

            return device_accesses_list
        finally:
            core.BNFirmwareNinjaFreeBoardDeviceAccesses(device_accesses, count)

    def get_reference_tree(
            self,
            location: Union[Section, FirmwareNinjaDevice, Function, DataVariable, int],
            fma: list[FirmwareNinjaFunctionMemoryAccesses],
            value: Optional[int] = None) -> FirmwareNinjaReferenceNode:
        """
        ``get_reference_tree`` returns a tree of references for a memory region, function, or data location

        :param Union[Section, FirmwareNinjaDevice, DataVariable, Function, int] location: Memory location to build the
        reference tree for
        :param list[FirmwareNinjaFunctionMemoryAccesses] fma: List of function memory accesses or None to use cross
        references. None should only be supplied if location is a Function, DataVariable, or address.
        :param Optional[int] value: Only include the node in the tree if this value is written to the location
        :return: Root reference node containing the reference tree
        :rtype: FirmwareNinjaReferenceNode
        """

        if fma is None and (isinstance(location, Section) or isinstance(location, FirmwareNinjaDevice)):
            raise ValueError("Function memory accesses cannot be None for location type Section or FirmwareNinjaDevice")

        value = ctypes.pointer(
            ctypes.c_uint64(value)) if value is not None else None

        fma_info_ptr_array = None
        if fma is not None and len(fma) > 0:
            fma_info_ptr_array = self._fma_info_list_to_array(fma)

        if isinstance(location, FirmwareNinjaDevice):
            bn_node = core.BNFirmwareNinjaGetMemoryRegionReferenceTree(
                self._handle, location.start, location.start + location.size,
                fma_info_ptr_array, len(fma), value)
        elif isinstance(location, Function):
            bn_node = core.BNFirmwareNinjaGetAddressReferenceTree(
                self._handle, location.start, fma_info_ptr_array, len(fma),
                value)
        elif isinstance(location, Section):
            bn_node = core.BNFirmwareNinjaGetMemoryRegionReferenceTree(
                self._handle, location.start, location.start + location.length,
                fma_info_ptr_array, len(fma), value)
        elif isinstance(location, DataVariable):
            bn_node = core.BNFirmwareNinjaGetAddressReferenceTree(
                self._handle, location.address, fma_info_ptr_array, len(fma),
                value)
        elif isinstance(location, int):
            bn_node = core.BNFirmwareNinjaGetAddressReferenceTree(
                self._handle, location, fma_info_ptr_array, len(fma), value)
        else:
            raise ValueError("Invalid location type")

        if not bn_node:
            return None

        return FirmwareNinjaReferenceNode(handle=bn_node, view=self._view)