File: build_symbol_db.py

package info (click to toggle)
android-platform-development 8.1.0%2Br23-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 37,780 kB
  • sloc: ansic: 166,133; xml: 75,737; java: 19,329; python: 11,511; cpp: 8,221; sh: 2,075; lisp: 261; ruby: 183; asm: 132; perl: 129; makefile: 18
file content (150 lines) | stat: -rwxr-xr-x 4,614 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/usr/bin/env python
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Builds a database of symbol version introductions."""
import argparse
import json
import logging
import os


THIS_DIR = os.path.realpath(os.path.dirname(__file__))


ALL_ARCHITECTURES = (
    'arm',
    'arm64',
    'mips',
    'mips64',
    'x86',
    'x86_64',
)


def logger():
    """Returns the default logger for this module."""
    return logging.getLogger(__name__)


def get_platform_versions():
    """Returns a list of the platform versions we have data for."""
    versions = []
    platforms_dir = os.path.join(THIS_DIR, 'platforms')
    logger().debug('Getting platform versions from %s', platforms_dir)
    for name in os.listdir(platforms_dir):
        if name.startswith('android-'):
            versions.append(int(name.split('-')[1]))
    return versions


def add_symbols(symbols, symbol_file_path, version, arch, is_var):
    """Adds symbols from a file to the symbol dict."""
    with open(symbol_file_path) as symbol_file:
        names = symbol_file.readlines()

    for name in names:
        name = name.strip()
        if not name:
            continue
        introduced_tag = 'introduced-' + arch
        if name in symbols:
            assert symbols[name]['is_var'] == is_var
            if introduced_tag in symbols[name]:
                continue
            symbols[name][introduced_tag] = version
        else:
            symbols[name] = {}
            symbols[name]['is_var'] = is_var
            symbols[name][introduced_tag] = version


def build_symbol_db(lib_name):
    """Returns a dict of symbols and their version information.

    Args:
        lib_name: Name of the library to return file mapping for.

    Returns: dict of symbol information in the following format:
        {
            "symbol_name": {
                "is_var": "true",
                "introduced-arm": 9,
                "introduced-x86": 14,
                "introduced-mips": 16,
                "introduced-arm64": 21,
                "introduced-mips64": 21,
                "introduced-x86_64": 21,
            },
            ...
        }
    """
    symbols = {}
    versions = sorted(get_platform_versions())
    for version in versions:
        for arch in ALL_ARCHITECTURES:
            symbols_dir = os.path.join(
                THIS_DIR, 'platforms', 'android-' + str(version),
                'arch-' + arch, 'symbols')
            if not os.path.exists(symbols_dir):
                logger().debug('Skipping non-existent %s', symbols_dir)
                continue

            logger().info('Processing android-%d arch-%s', version, arch)

            funcs_file_name = lib_name + '.so.functions.txt'
            funcs_file = os.path.join(symbols_dir, funcs_file_name)
            if os.path.exists(funcs_file):
                add_symbols(symbols, funcs_file, version, arch, is_var='false')

            vars_file_name = lib_name + '.so.variables.txt'
            vars_file = os.path.join(symbols_dir, vars_file_name)
            if os.path.exists(vars_file):
                add_symbols(symbols, vars_file, version, arch, is_var='true')
    return symbols


def parse_args():
    """Returns parsed command line arguments."""
    parser = argparse.ArgumentParser()

    parser.add_argument('-v', '--verbose', action='count', default=0)

    parser.add_argument(
        'library_name', metavar='LIBRARY_NAME',
        help='Name of the library to create a database for.')

    return parser.parse_args()


def main():
    """Program entry point."""
    args = parse_args()
    os.chdir(THIS_DIR)

    verbose_map = (logging.WARNING, logging.INFO, logging.DEBUG)
    verbosity = args.verbose
    if verbosity > 2:
        verbosity = 2
    logging.basicConfig(level=verbose_map[verbosity])

    symbol_db = build_symbol_db(args.library_name)
    with open(args.library_name + '.so.json', 'w') as db_file:
        json.dump(symbol_db, db_file, indent=4, separators=(',', ': '),
                  sort_keys=True)


if __name__ == '__main__':
    main()