Skip to content

Adding data to existing segment may fail depending on how segment was previously created #53

Description

@projms-intive

Hello,

depending on how data was added to a bincopy.BinFile(), the stored data may be mutable or immutable, causing modifying data operations to fail.

Example:

binaryFileElf = bincopy.BinFile()
binaryFileElf.add_elf_file(pathElf)
binaryFileElf.add_binary(data, address=0, overwrite=True)

In this case the data provided by .elf file pathElf and the data inserted afterwards overlaps, therefore overwrite=True was used.

Observed:

  File "/usr/lib/python3/dist-packages/bincopy.py", line 1107, in add_binary
    self._segments.add(Segment(address,
  File "/usr/lib/python3/dist-packages/bincopy.py", line 605, in add
    s.add_data(segment.minimum_address,
  File "/usr/lib/python3/dist-packages/bincopy.py", line 444, in add_data
    self.data[self_data_offset:self_data_offset + len(data)] = data
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'bytes' object does not support item assignment

Expectation:
Data was successfully replaced/overwritten/modified.

Analysis:
Specifically, in the following line during reading the elf file, a new segment is created while using a bytes type instead of a bytearray. Therefore causing segment to take over the type and making the data immutable: https://github.com/eerimoq/bincopy/blob/d7a55099a54dee3f3b6781c488b0a1000969b0ce/bincopy.py#L1145C21-L1145C45

add_binary for initial data creation is not affected as it creates a segment based on a bytearray:

binaryFile = bincopy.BinFile()
binaryFile.add_binary(binaryFileElf.as_binary())
binaryFile.add_binary(data, address=0, overwrite=True) # This works as add_binary uses a bytearray

Suggestion: potentially specifying self.data of class Segment to always be a mutable bytearray could be an option if there is no need for immutable segments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions