1#!/usr/bin/env python3
2#
3# Copyright (c) 2021 Intel Corporation
4#
5# SPDX-License-Identifier: Apache-2.0
6
7"""
8Utilities for Dictionary-based Logging Parser
9"""
10
11import binascii
12
13
14def convert_hex_file_to_bin(hexfile):
15    """This converts a file in hexadecimal to binary"""
16    bin_data = b''
17
18    with open(hexfile, "r", encoding="iso-8859-1") as hfile:
19        for line in hfile.readlines():
20            hex_str = line.strip()
21
22            bin_str = binascii.unhexlify(hex_str)
23            bin_data += bin_str
24
25    return bin_data
26
27
28def extract_one_string_in_section(section, str_ptr):
29    """Extract one string in an ELF section"""
30    data = section['data']
31    max_offset = section['size']
32    offset = str_ptr - section['start']
33
34    if offset < 0 or offset >= max_offset:
35        return None
36
37    ret_str = ""
38
39    while (offset < max_offset) and (data[offset] != 0):
40        ret_str += chr(data[offset])
41        offset += 1
42
43    return ret_str
44
45
46def find_string_in_mappings(string_mappings, str_ptr):
47    """
48    Find string pointed by string_ptr in the string mapping
49    list. Return None if not found.
50    """
51    if string_mappings is None:
52        return None
53
54    if len(string_mappings) == 0:
55        return None
56
57    if str_ptr in string_mappings:
58        return string_mappings[str_ptr]
59
60    # No direct match on pointer value.
61    # This may be a combined string. So check for that.
62    for ptr, string in string_mappings.items():
63        if ptr <= str_ptr < (ptr + len(string)):
64            whole_str = string_mappings[ptr]
65            return whole_str[str_ptr - ptr:]
66
67    return None
68