summaryrefslogtreecommitdiffstats
path: root/abi/extract_symbols
blob: a4dba8cf4d6d45795e0fc78fb7843c9fb065bf51 (plain)
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python3
#
# Copyright (C) 2019 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.
#

import argparse
import collections
import functools
import itertools
import os
import re
import subprocess
import sys

_ALWAYS_WHITELISTED = [
    "module_layout",  # is exported even if CONFIG_TRIM_UNUSED_KSYMS is enabled
    "__put_task_struct",  # this allows us to keep `struct task_struct` stable
]

def symbol_sort(symbols):
  # use the method that `sort` uses: case insensitive and ignoring
  # underscores, that keeps symbols with related name close to each other.
  # yeah, that is a bit brute force, but it gets the job done

  def __key(a):
    """Create a key for comparison of symbols."""
    # We want to sort underscore prefixed symbols along with those without, but
    # before them. Hence add a trailing underscore for every missing leading
    # one and strip all others.
    # E.g. __blk_mq_end_request, _blk_mq_end_request, blk_mq_end_request get
    # replaced by blkmqendrequest, blkmqendrequest_, blkmqendrequest__ and
    # compared lexicographically.

    # if the caller passes None or an empty string something is odd, so assert
    # and ignore if asserts are disabled as we do not need to deal with that
    assert (a)
    if not a:
      return a

    tmp = a.lower()
    for idx, c in enumerate(tmp):
      if c != "_":
        break
    return tmp.replace("_", "") + (5 - idx) * "_"

  return sorted(set(symbols), key=__key)


def find_binaries(directory):
  """Locate vmlinux and kernel modules (*.ko)."""
  vmlinux = None
  modules = []
  for root, dirs, files in os.walk(directory):
    for file in files:
      if file.endswith(".ko"):
        modules.append(os.path.join(root, file))
      elif file == "vmlinux":
        vmlinux = os.path.join(root, file)

  return vmlinux, modules


def extract_undefined_symbols(modules):
  """Extract undefined symbols from a list of module files."""

  # yes, we could pass all of them to nm, but I want to avoid hitting shell
  # limits with long lists of modules
  result = {}
  for module in sorted(modules):
    symbols = []
    out = subprocess.check_output(["nm", "--undefined-only", module],
                                  stderr=subprocess.DEVNULL).decode("ascii")
    for line in out.splitlines():
      symbols.append(line.strip().split()[1])

    result[os.path.basename(module)] = symbol_sort(symbols)

  return result


def extract_exported_symbols(binary):
  """Extract the ksymtab exported symbols from a kernel binary."""
  symbols = []
  out = subprocess.check_output(["nm", "--defined-only", binary],
                                stderr=subprocess.DEVNULL).decode("ascii")
  for line in out.splitlines():
    pos = line.find(" __ksymtab_")
    if pos != -1:
      symbols.append(line[pos + len(" __ksymtab_"):])

  return symbol_sort(symbols)

def extract_generic_exports(vmlinux, modules):
  """Extract the ksymtab exported symbols from vmlinux and a set of modules"""
  symbols = extract_exported_symbols(vmlinux)
  for module in modules:
    symbols.extend(extract_exported_symbols(module))
  return symbols

def extract_exported_in_modules(modules):
  """Extract the ksymtab exported symbols for a list of kernel modules."""
  return {module: extract_exported_symbols(module) for module in modules}


def report_missing(module_symbols, exported):
  """Report missing symbols that are undefined, but not know in any binary."""
  for module, symbols in module_symbols.items():
    for symbol in symbols:
      if symbol not in exported:
        print("Symbol {} required by {} but not provided".format(
            symbol, module))


def create_whitelist(whitelist, undefined_symbols, exported,
                     emit_module_whitelists, module_grouping):
  """Create a symbol whitelist for libabigail."""
  symbol_counter = collections.Counter(
      itertools.chain.from_iterable(undefined_symbols.values()))


  with open(whitelist, "w") as wl:

    common_wl_section = symbol_sort([
        symbol for symbol, count in symbol_counter.items()
        if (count > 1 or not module_grouping) and symbol in exported
    ] + _ALWAYS_WHITELISTED)

    # write the header
    wl.write("[abi_whitelist]\n")
    if module_grouping:
      wl.write("# commonly used symbols\n")
    wl.write("  ")
    wl.write("\n  ".join(common_wl_section))
    wl.write("\n")

    for module, symbols in undefined_symbols.items():

      if emit_module_whitelists:
        mod_wl_file = whitelist + "_" + os.path.splitext(module)[0]
        with open(mod_wl_file, "w") as mod_wl:
          # write the header
          mod_wl.write("[abi_whitelist]\n  ")
          mod_wl.write("\n  ".join([s for s in symbols if s in exported]))
          mod_wl.write("\n")

      new_wl_section = symbol_sort([
          symbol for symbol in symbols
          if symbol in exported and symbol not in common_wl_section
      ])

      if not new_wl_section:
        continue

      wl.write("\n# required by {}\n  ".format(module))
      wl.write("\n  ".join(new_wl_section))
      wl.write("\n")


def main():
  """Extract the required symbols for a directory full of kernel modules."""
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "directory",
      nargs="?",
      default=os.getcwd(),
      help="the directory to search for kernel binaries")

  parser.add_argument(
      "--skip-report-missing",
      action="store_false",
      dest="report_missing",
      default=True,
      help="Do not report symbols required by modules, but missing from vmlinux"
  )

  parser.add_argument(
      "--include-module-exports",
      action="store_true",
      default=False,
      help="Include inter-module symbols")

  parser.add_argument(
      "--full-gki-abi",
      action="store_true",
      default=False,
      help="Assume all vmlinux and GKI module symbols are part of the ABI")

  parser.add_argument(
      "--whitelist",
      default=None,
      help="The whitelist to create")

  parser.add_argument(
      "--print-modules",
      action="store_true",
      default=False,
      help="Emit the names of the processed modules")

  parser.add_argument(
      "--emit-module-whitelists",
      action="store_true",
      default=False,
      help="Emit a separate whitelist for each module")

  parser.add_argument(
      "--skip-module-grouping",
      action="store_false",
      dest="module_grouping",
      default=True,
      help="Do not group symbols by module.")

  parser.add_argument(
      "--module-filter",
      action="append",
      dest="module_filters",
      help="Only process modules matching the filter. Can be passed multiple times."
  )

  parser.add_argument(
      "--gki-modules",
      default=None,
      help="List of GKI modules which must be provided when the search directory contains both vendor and GKI modules")

  args = parser.parse_args()

  if not os.path.isdir(args.directory):
    print("Expected a directory to search for binaries, but got %s" %
          args.directory)
    return 1

  if args.emit_module_whitelists and not args.whitelist:
    print("Emitting module whitelists requires the --whitelist parameter.")
    return 1

  if args.whitelist is None:
    args.whitelist = "/dev/stdout"

  # Locate the Kernel Binaries
  vmlinux, modules = find_binaries(args.directory)

  if args.module_filters:
    modules = [
        mod for mod in modules if any(
            [re.search(f, os.path.basename(mod)) for f in args.module_filters])
    ]

  # Partition vendor and GKI modules in two lists
  gki_modules = []
  if args.gki_modules is not None:
    with open(args.gki_modules) as f:
      gki_modules = [ os.path.basename(mod) for mod in f.read().splitlines() ]
    gki_modules = [ mod for mod in modules if os.path.basename(mod) in gki_modules ]
    modules = [ mod for mod in modules if mod not in gki_modules ]


  if vmlinux is None or not os.path.isfile(vmlinux):
    print("Could not find a suitable vmlinux file.")
    return 1

  # Get required symbols of all modules
  undefined_symbols = extract_undefined_symbols(modules)

  # Get the actually defined and exported symbols
  generic_exports = extract_generic_exports(vmlinux, gki_modules)
  local_exports = extract_exported_in_modules(modules)

  # Build the list of all exported symbols (generic and local)
  all_exported = list(
      itertools.chain.from_iterable(local_exports.values()))
  all_exported.extend(generic_exports)
  all_exported = set(all_exported)

  # For sanity, check for inconsistencies between required and exported symbols
  # Do not do this analysis if module_filters are in place as likely
  # inter-module dependencies are broken by this.
  if args.report_missing and not args.module_filters:
    report_missing(undefined_symbols, all_exported)

  # If specified, create the whitelist
  if args.whitelist:
    create_whitelist(
        args.whitelist,
        { "full-gki-abi": generic_exports } if args.full_gki_abi else undefined_symbols,
        all_exported if args.include_module_exports else generic_exports,
        args.emit_module_whitelists,
        args.module_grouping)

  if args.print_modules:
    print("These modules have been considered when creating the whitelist:")
    print("  " +
          "\n  ".join(sorted([os.path.basename(mod) for mod in modules])))


if __name__ == "__main__":
  sys.exit(main())