public inbox for u-boot@lists.denx.de
 help / color / mirror / Atom feed
From: Alper Nebi Yasak <alpernebiyasak@gmail.com>
To: Simon Glass <sjg@chromium.org>,
	U-Boot Mailing List <u-boot@lists.denx.de>
Cc: huang lin <hl@rock-chips.com>,
	Jeffy Chen <jeffy.chen@rock-chips.com>,
	Kever Yang <kever.yang@rock-chips.com>,
	Tom Rini <trini@konsulko.com>,
	Philippe Reynes <philippe.reynes@softathome.com>,
	Ivan Mikhaylov <ivan.mikhaylov@siemens.com>
Subject: Re: [PATCH 11/24] elf: Add a way to read segment information from an ELF file
Date: Tue, 15 Feb 2022 14:44:19 +0300	[thread overview]
Message-ID: <9854f0a5-18e6-71c2-e60a-80280b736d76@gmail.com> (raw)
In-Reply-To: <20220208185008.35843-10-sjg@chromium.org>

On 08/02/2022 21:49, Simon Glass wrote:
> Add a function which reads the segments and the entry address.
> 
> Also fix a comment nit in the tests while we are here.
> 
> Signed-off-by: Simon Glass <sjg@chromium.org>
> ---
> 
>  tools/binman/elf.py      | 37 +++++++++++++++++++++++++++++++++++++
>  tools/binman/elf_test.py | 31 +++++++++++++++++++++++++++++--
>  2 files changed, 66 insertions(+), 2 deletions(-)
> 
> diff --git a/tools/binman/elf.py b/tools/binman/elf.py
> index de2bb4651f..2b83ac1876 100644
> --- a/tools/binman/elf.py
> +++ b/tools/binman/elf.py
> @@ -20,6 +20,7 @@ from patman import tout
>  ELF_TOOLS = True
>  try:
>      from elftools.elf.elffile import ELFFile
> +    from elftools.elf.elffile import ELFError
>      from elftools.elf.sections import SymbolTableSection
>  except:  # pragma: no cover
>      ELF_TOOLS = False
> @@ -369,3 +370,39 @@ def UpdateFile(infile, outfile, start_sym, end_sym, insert):
>      newdata += data[syms[end_sym].offset:]
>      tools.WriteFile(outfile, newdata)
>      tout.Info('Written to offset %#x' % syms[start_sym].offset)
> +
> +def read_segments(data):
> +    """Read segments from an ELF file
> +
> +    Args:
> +        data (bytes): Contents of file
> +
> +    Returns:
> +        tuple:
> +            list of segments, each:
> +                int: Segment number (0 = first)
> +                int: Start address of segment in memory
> +                bytes: Contents of segment
> +            int: entry address for image
> +
> +    Raises:
> +        ValueError: elftools is not available

... or input data is not a correct ELF file?

> +    """
> +    if not ELF_TOOLS:
> +        raise ValueError('Python elftools package is not available')

I see something like ModuleNotFoundError("No module named 'elftools'")
when I try to import an unavailable module, so maybe this could match that.

> +    with io.BytesIO(data) as inf:
> +        try:
> +            elf = ELFFile(inf)
> +        except ELFError as err:
> +            raise ValueError(err)

Could also be: raise ValueError("Not an ELF file") from err

But I guess you want err's message here to match on it in tests. (It's
also possible but slightly inconvenient with __cause__ when using
raise-from)

> +        entry = elf.header['e_entry']
> +        segments = []
> +        for i in range(elf.num_segments()):
> +            segment = elf.get_segment(i)
> +            if segment['p_type'] != 'PT_LOAD' or not segment['p_memsz']:

I can't say I fully understand ELF details, is it obvious in context
that a function named read_segments() would only return these segments,
or should the name be explicit about it e.g. read_loadable_segments()?

> +                skipped = 1  # To make code-coverage see this line
> +                continue
> +            start = segment['p_offset']
> +            rend = start + segment['p_filesz']
> +            segments.append((i, segment['p_paddr'], data[start:rend]))
> +    return segments, entry
> diff --git a/tools/binman/elf_test.py b/tools/binman/elf_test.py
> index f727258487..369260c17a 100644
> --- a/tools/binman/elf_test.py
> +++ b/tools/binman/elf_test.py
> @@ -56,8 +56,8 @@ class FakeSection:
>  def BuildElfTestFiles(target_dir):
>      """Build ELF files used for testing in binman
>  
> -    This compiles and links the test files into the specified directory. It the
> -    Makefile and source files in the binman test/ directory.
> +    This compiles and links the test files into the specified directory. It uses
> +    the Makefile and source files in the binman test/ directory.
>  
>      Args:
>          target_dir: Directory to put the files into
> @@ -258,6 +258,33 @@ class TestElf(unittest.TestCase):
>          offset = elf.GetSymbolFileOffset(fname, ['missing_sym'])
>          self.assertEqual({}, offset)
>  
> +    def test_read_segments(self):
> +        """Test for read_segments()"""
> +        if not elf.ELF_TOOLS:
> +            self.skipTest('Python elftools not available')
> +        fname = self.ElfTestFile('embed_data')
> +        segments, entry = elf.read_segments(tools.ReadFile(fname))
> +
> +    def test_read_segments_fail(self):
> +        """Test for read_segments() without elftools"""
> +        try:
> +            old_val = elf.ELF_TOOLS
> +            elf.ELF_TOOLS = False
> +            fname = self.ElfTestFile('embed_data')
> +            with self.assertRaises(ValueError) as e:
> +                elf.read_segments(tools.ReadFile(fname))
> +            self.assertIn('Python elftools package is not available',
> +                          str(e.exception))
> +        finally:
> +            elf.ELF_TOOLS = old_val
> +
> +    def test_read_segments_bad_data(self):
> +        """Test for read_segments() with an invalid ELF file"""
> +        fname = self.ElfTestFile('embed_data')
> +        with self.assertRaises(ValueError) as e:
> +            elf.read_segments(tools.GetBytes(100, 100))
> +        self.assertIn('Magic number does not match', str(e.exception))
> +
>  
>  if __name__ == '__main__':
>      unittest.main()

  reply	other threads:[~2022-02-15 11:53 UTC|newest]

Thread overview: 69+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-02-08 18:49 [PATCH 00/24] binman: rockchip: Migrate from rockchip SPL_FIT_GENERATOR script Simon Glass
2022-02-08 18:49 ` [PATCH 01/24] moveconfig: Show the config name rather than the defconfig Simon Glass
2022-02-15 11:40   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-23  2:43       ` Simon Glass
2022-02-08 18:49 ` [PATCH 02/24] moveconfig: Allow regex matches when finding combinations Simon Glass
2022-02-15 11:41   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-08 18:49 ` [PATCH 03/24] spl: x86: Correct the binman symbols for SPL Simon Glass
2022-02-15 11:42   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-23 22:58     ` Simon Glass
2022-03-03 21:06       ` Alper Nebi Yasak
2022-03-06  3:07         ` Simon Glass
2022-02-08 18:49 ` [PATCH 04/24] spl: Allow disabling binman symbols in SPL Simon Glass
2022-02-15 11:42   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-08 18:49 ` [PATCH 05/24] rockchip: evb-rk3288: Drop raw-image support Simon Glass
2022-02-08 18:49 ` [PATCH 06/24] dtoc: Support adding a string list to a device tree Simon Glass
2022-02-15 11:43   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-23 22:58     ` Simon Glass
2022-03-03 21:07       ` Alper Nebi Yasak
2022-03-06  3:07         ` Simon Glass
2022-02-08 18:49 ` [PATCH 07/24] dtoc: Support deleting a node Simon Glass
2022-02-08 18:49 ` [PATCH 08/24] dtoc: Allow deleting nodes and adding them in the same sync Simon Glass
2022-02-08 18:49 ` [PATCH 09/24] dtoc: Support reading a list of arguments Simon Glass
2022-02-15 11:43   ` Alper Nebi Yasak
2022-02-23  2:35     ` Simon Glass
2022-02-23 22:58     ` Simon Glass
2022-03-03 21:07       ` Alper Nebi Yasak
2022-02-08 18:49 ` [PATCH 10/24] binman: Update docs to indicate mkimage is supported Simon Glass
2022-02-23  2:35   ` Simon Glass
2022-02-08 18:49 ` [PATCH 11/24] elf: Add a way to read segment information from an ELF file Simon Glass
2022-02-15 11:44   ` Alper Nebi Yasak [this message]
2022-02-23  2:35     ` Simon Glass
2022-02-23 22:58     ` Simon Glass
2022-02-08 18:49 ` [PATCH 12/24] WIP: binman: Add support for OP-TEE Simon Glass
2022-02-08 18:49 ` [PATCH 13/24] binman: Add to the TODO Simon Glass
2022-02-08 18:49 ` [PATCH 14/24] binman: Support a list of strings with the mkimage etype Simon Glass
2022-02-15 11:45   ` Alper Nebi Yasak
2022-02-23  2:34     ` Simon Glass
2022-02-23 22:59     ` Simon Glass
2022-02-08 18:49 ` [PATCH 15/24] binman: Add a ELF test file with disjoint text sections Simon Glass
2022-02-08 18:50 ` [PATCH 16/24] binman: Move entry-data collection into a Entry method Simon Glass
2022-02-15 11:45   ` Alper Nebi Yasak
2022-02-23  2:34     ` Simon Glass
2022-02-08 18:50 ` [PATCH 17/24] binman: fit: Refactor to reduce function size Simon Glass
2022-02-15 11:45   ` Alper Nebi Yasak
2022-02-23  2:34     ` Simon Glass
2022-02-23 22:59     ` Simon Glass
2022-02-08 18:50 ` [PATCH 18/24] binman: Tidy up the docs a little with fit Simon Glass
2022-02-08 18:50 ` [PATCH 19/24] binman: Allow different operations in FIT generator nodes Simon Glass
2022-02-23  2:34   ` Simon Glass
2022-02-08 18:50 ` [PATCH 20/24] binman: Support splitting an ELF file into multiple nodes Simon Glass
2022-02-15 11:46   ` Alper Nebi Yasak
2022-02-23 22:59     ` Simon Glass
2022-03-03 21:07       ` Alper Nebi Yasak
2022-03-06  3:07         ` Simon Glass
2022-02-08 18:50 ` [PATCH 21/24] rockchip: Include binman script in 64-bit boards Simon Glass
2022-02-08 18:50 ` [PATCH 22/24] rockchip: Support building the all output files in binman Simon Glass
2022-02-10 15:03   ` Peter Geis
2022-02-10 18:57     ` Simon Glass
2022-02-10 19:32       ` Peter Geis
2022-02-14  1:28         ` Peter Geis
2022-02-15 11:48   ` Alper Nebi Yasak
2022-02-08 18:50 ` [PATCH 23/24] rockchip: Convert all boards to use binman Simon Glass
2022-02-08 18:50 ` [PATCH 24/24] rockchip: Drop the FIT generator script Simon Glass
2022-02-11 15:22 ` [PATCH 00/24] binman: rockchip: Migrate from rockchip SPL_FIT_GENERATOR script Alper Nebi Yasak

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=9854f0a5-18e6-71c2-e60a-80280b736d76@gmail.com \
    --to=alpernebiyasak@gmail.com \
    --cc=hl@rock-chips.com \
    --cc=ivan.mikhaylov@siemens.com \
    --cc=jeffy.chen@rock-chips.com \
    --cc=kever.yang@rock-chips.com \
    --cc=philippe.reynes@softathome.com \
    --cc=sjg@chromium.org \
    --cc=trini@konsulko.com \
    --cc=u-boot@lists.denx.de \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox