Per Åstrand | 43a8409 | 2021-03-26 09:01:38 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # |
| 4 | # Copyright (c) 2021 Arm Limited. All rights reserved. |
| 5 | # |
| 6 | # SPDX-License-Identifier: Apache-2.0 |
| 7 | # |
| 8 | # Licensed under the Apache License, Version 2.0 (the License); you may |
| 9 | # not use this file except in compliance with the License. |
| 10 | # You may obtain a copy of the License at |
| 11 | # |
| 12 | # www.apache.org/licenses/LICENSE-2.0 |
| 13 | # |
| 14 | # Unless required by applicable law or agreed to in writing, software |
| 15 | # distributed under the License is distributed on an AS IS BASIS, WITHOUT |
| 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | # See the License for the specific language governing permissions and |
| 18 | # limitations under the License. |
| 19 | # |
| 20 | |
| 21 | import argparse |
| 22 | import os |
| 23 | import re |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import elftools.elf.elffile as elffile |
| 27 | |
| 28 | def generate_binaries(args): |
Kristofer Jonsson | 8948704 | 2021-11-16 16:26:41 +0100 | [diff] [blame] | 29 | outfiles = [] |
| 30 | |
Per Åstrand | 43a8409 | 2021-03-26 09:01:38 +0100 | [diff] [blame] | 31 | with open(args.input, 'rb') as f: |
| 32 | elf = elffile.ELFFile(f) |
| 33 | for segment in elf.iter_segments(): |
| 34 | if segment['p_type'] == 'PT_LOAD' and segment['p_filesz'] > 0: |
Per Åstrand | b47ec63 | 2021-05-07 08:55:10 +0200 | [diff] [blame] | 35 | os.makedirs(args.output, exist_ok=True) |
Per Åstrand | 43a8409 | 2021-03-26 09:01:38 +0100 | [diff] [blame] | 36 | out = os.path.join( |
| 37 | args.output, |
| 38 | '%s_0x%08x.bin' % (os.path.basename(args.input), segment['p_paddr'])) |
| 39 | with open(out, 'wb') as of: |
| 40 | of.write(segment.data()) |
| 41 | |
Kristofer Jonsson | 8948704 | 2021-11-16 16:26:41 +0100 | [diff] [blame] | 42 | outfiles.append(out) |
| 43 | |
| 44 | if args.d: |
| 45 | with open(args.d, 'w') as f: |
| 46 | f.writelines(outfiles) |
| 47 | |
Per Åstrand | 43a8409 | 2021-03-26 09:01:38 +0100 | [diff] [blame] | 48 | if __name__ == '__main__': |
| 49 | parser = argparse.ArgumentParser(description='Generate binaries from ELF file') |
| 50 | parser.add_argument('-o', '--output', default='.', required=False, help='Output directory for binaries') |
Kristofer Jonsson | 8948704 | 2021-11-16 16:26:41 +0100 | [diff] [blame] | 51 | parser.add_argument('-d', help='Dependency file') |
Per Åstrand | 43a8409 | 2021-03-26 09:01:38 +0100 | [diff] [blame] | 52 | parser.add_argument('input', metavar='inputfile', type=str, help='ELF file to extract binaries from') |
| 53 | |
| 54 | args = parser.parse_args() |
| 55 | |
| 56 | generate_binaries(args) |