Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 30781C433F5 for ; Tue, 8 Feb 2022 18:52:19 +0000 (UTC) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id AA34583DCF; Tue, 8 Feb 2022 19:51:01 +0100 (CET) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=chromium.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (1024-bit key; unprotected) header.d=chromium.org header.i=@chromium.org header.b="efKusshH"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 429C583DB5; Tue, 8 Feb 2022 19:50:43 +0100 (CET) Received: from mail-io1-xd33.google.com (mail-io1-xd33.google.com [IPv6:2607:f8b0:4864:20::d33]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id D111183D8E for ; Tue, 8 Feb 2022 19:50:36 +0100 (CET) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=chromium.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=sjg@chromium.org Received: by mail-io1-xd33.google.com with SMTP id 9so260873iou.2 for ; Tue, 08 Feb 2022 10:50:36 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=UEU9MooiLExtXqu0R9qrft/1TuuZqc1pDYq/CXLqN0I=; b=efKusshHo0aF+om8TFPGJg512EfKefskXSPbaLtfKu0pooH38ZLGYljxPuHxpt6jyQ HOG4/AfdNbosRB39XjSiORf7XPWicNm2pVtMhclCGL8GU883042Y84J8w1N1dKx8DB9f l86T+zhNNkQhnxWq9jLzEguLOtH+13Mh7yIhc= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=UEU9MooiLExtXqu0R9qrft/1TuuZqc1pDYq/CXLqN0I=; b=KbD42HjyNi8ObQMDep1xnncS2ImOdxjI248yWIlFhFlz0VBO/xQEpBu6+rq6kMPLoR DYKJM/wrt02kCJab/7Z+4BtImLIBKokj4fvPdVrRVO1krWzxu9qi/bXZjSDA7RD946tJ XgKKwk5ADCbVCL+k6X27SEr+DW0QNy9k9lMPOxVDFT9iC89ObnrlCZ+RlYzGBLtxzVDj +YQwrfgEtOgkqmH7Mck4vYpHMQwZk8TzIBiiC5ygghzBMtmIDd1IcO+hus16MbSo4Cbe 4rKw9w2pd2he0vPl/pCPxQ7Gv6iMuwVTC3hxnME7lcC/3iWaxywZSrlAmYNxxHTK8sbs mM8Q== X-Gm-Message-State: AOAM532rC3ctrBXz0PeYhwiwSyTBD7y1HSTxPWEpt9WjtG4x0eF41Sb1 OWxAqBQYhb34/EsNjmrL1e59ejcttdNvyw== X-Google-Smtp-Source: ABdhPJxHoPaPGHgQPKT1FexzhLoZP7H+3GSPpYIVa935lCNFU13g/OM/VRsyl/XdrJOYReFoMnekew== X-Received: by 2002:a05:6638:130f:: with SMTP id r15mr411745jad.114.1644346235534; Tue, 08 Feb 2022 10:50:35 -0800 (PST) Received: from kiwi.bld.corp.google.com (c-67-190-101-114.hsd1.co.comcast.net. [67.190.101.114]) by smtp.gmail.com with ESMTPSA id q2sm2911844ilt.33.2022.02.08.10.50.34 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 08 Feb 2022 10:50:35 -0800 (PST) From: Simon Glass To: U-Boot Mailing List Cc: huang lin , Jeffy Chen , Simon Glass , Kever Yang , Philipp Tomsich , Alper Nebi Yasak , Tom Rini , Roger Quadros , Philippe Reynes , Ivan Mikhaylov Subject: [PATCH 11/24] elf: Add a way to read segment information from an ELF file Date: Tue, 8 Feb 2022 11:49:55 -0700 Message-Id: <20220208185008.35843-10-sjg@chromium.org> X-Mailer: git-send-email 2.35.0.263.gb82422642f-goog In-Reply-To: <20220208185008.35843-1-sjg@chromium.org> References: <20220208185008.35843-1-sjg@chromium.org> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.39 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.103.5 at phobos.denx.de X-Virus-Status: Clean 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 --- 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 + """ + if not ELF_TOOLS: + raise ValueError('Python elftools package is not available') + with io.BytesIO(data) as inf: + try: + elf = ELFFile(inf) + except ELFError as err: + raise ValueError(err) + 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']: + 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() -- 2.35.0.263.gb82422642f-goog