"""
Command to print info about makefiles remaining to be converted to soong.
See usage / argument parsing below for commandline options. """
import argparse import csv import itertools import json import os import re import sys
DIRECTORY_PATTERNS = [x.split("/") for x in ( "device/*", "frameworks/*", "hardware/*", "packages/*", "vendor/*", "*",
)]
def match_directory_group(pattern, filename):
match = []
filename = filename.split("/") if len(filename) < len(pattern): returnNone for i in range(len(pattern)):
pattern_segment = pattern[i]
filename_segment = filename[i] if pattern_segment == "*"or pattern_segment == filename_segment:
match.append(filename_segment) else: returnNone if match: return os.path.sep.join(match) else: returnNone
def directory_group(filename): for pattern in DIRECTORY_PATTERNS:
match = match_directory_group(pattern, filename) if match: return match return os.path.dirname(filename)
def analyze_lines(filename, lines, func):
line_matches = [] for i in range(len(lines)):
line = lines[i]
stripped = line.strip() if stripped.startswith("#"): continue if func(stripped):
line_matches.append((i+1, line)) if line_matches: return Analysis(filename, line_matches);
def analyze_has_conditional(line): return (line.startswith("ifeq") or line.startswith("ifneq") or line.startswith("ifdef") or line.startswith("ifndef"))
NORMAL_INCLUDES = [re.compile(pattern) for pattern in (
r"include \$+\(CLEAR_VARS\)", # These are in defines which are tagged separately
r"include \$+\(BUILD_.*\)",
r"include \$\(call first-makefiles-under, *\$\(LOCAL_PATH\)\)",
r"include \$\(call all-subdir-makefiles\)",
r"include \$\(all-subdir-makefiles\)",
r"include \$\(call all-makefiles-under, *\$\(LOCAL_PATH\)\)",
r"include \$\(call all-makefiles-under, *\$\(call my-dir\).*\)",
r"include \$\(BUILD_SYSTEM\)/base_rules.mk", # called out separately
r"include \$\(call all-named-subdir-makefiles,.*\)",
r"include \$\(subdirs\)",
)] def analyze_has_wacky_include(line): ifnot (line.startswith("include") or line.startswith("-include") or line.startswith("sinclude")): returnFalse for matcher in NORMAL_INCLUDES: if matcher.fullmatch(line): returnFalse returnTrue
class Makefile(object): def __init__(self, filename):
self.filename = filename
# Analyze the file with open(filename, "r", errors="ignore") as f: try:
lines = f.readlines() except UnicodeDecodeError as ex:
sys.stderr.write("Filename: %s\n" % filename) raise ex
lines = [line.strip() for line in lines]
self.analyses = dict([(analyzer, analyze_lines(filename, lines, analyzer.func)) for analyzer in ANALYZERS])
def find_android_mk():
cwd = os.getcwd() for root, dirs, files in os.walk(cwd): for filename in files: if filename == "Android.mk": yield os.path.join(root, filename)[len(cwd) + 1:] for ignore in (".git", ".repo"): if ignore in dirs:
dirs.remove(ignore)
def is_aosp(dirname): for d in ("device/sample", "hardware/interfaces", "hardware/libhardware", "hardware/ril"): if dirname.startswith(d): returnTrue for d in ("device/", "hardware/", "vendor/"): if dirname.startswith(d): returnFalse returnTrue
def is_google(dirname): for d in ("device/google", "hardware/google", "test/sts", "vendor/auto", "vendor/google", "vendor/unbundled_google", "vendor/widevine", "vendor/xts"): if dirname.startswith(d): returnTrue returnFalse
def is_clean(makefile): for analysis in makefile.analyses.values(): if analysis: returnFalse returnTrue
def clean_and_only_blocked_by_clean(soong, all_makefiles, makefile): ifnot is_clean(makefile): returnFalse
modules = soong.reverse_makefiles[makefile.filename] for module in modules: for dep in soong.transitive_deps(module): for filename in soong.makefiles.get(dep, []):
m = all_makefiles.get(filename) if m andnot is_clean(m): returnFalse returnTrue
class Annotations(object): def __init__(self):
self.entries = []
self.count = 0
class SoongData(object): def __init__(self, reader): """Read the input file and store the modules and dependency mappings. """
self.problems = dict()
self.deps = dict()
self.reverse_deps = dict()
self.module_types = dict()
self.makefiles = dict()
self.reverse_makefiles = dict()
self.installed = dict()
self.reverse_installed = dict()
self.modules = set()
for (module, module_type, problem, dependencies, makefiles, installed) in reader:
self.modules.add(module)
makefiles = [f for f in makefiles.strip().split(' ') if f != ""]
self.module_types[module] = module_type
self.problems[module] = problem
self.deps[module] = [d for d in dependencies.strip().split(' ') if d != ""] for dep in self.deps[module]: ifnot dep in self.reverse_deps:
self.reverse_deps[dep] = []
self.reverse_deps[dep].append(module)
self.makefiles[module] = makefiles for f in makefiles:
self.reverse_makefiles.setdefault(f, []).append(module) for f in installed.strip().split(' '):
self.installed[f] = module
self.reverse_installed.setdefault(module, []).append(f)
def transitive_deps(self, module):
results = set() def traverse(module): for dep in self.deps.get(module, []): ifnot dep in results:
results.add(dep)
traverse(module)
traverse(module) return results
def contains_unblocked_modules(self, filename): for m in self.reverse_makefiles[filename]: if len(self.deps[m]) == 0: returnTrue returnFalse
def contains_blocked_modules(self, filename): for m in self.reverse_makefiles[filename]: if len(self.deps[m]) > 0: returnTrue returnFalse
def count_deps(depsdb, module, seen): """Based on the depsdb, count the number of transitive dependencies.
You can passin an reversed dependency graph to count the number of
modules that depend on the module."""
count = 0
seen.append(module) if module in depsdb: for dep in depsdb[module]: if dep in seen: continue
count += 1 + count_deps(depsdb, dep, seen) return count
if filename.startswith(host_prefix): return HOST_PARTITON
elif filename.startswith(device_prefix):
index = filename.find("/", len(device_prefix)) if index < 0: return OTHER_PARTITON return filename[len(device_prefix):index]
# get all modules in $(PRODUCT_PACKAGE) and the corresponding deps def get_module_product_packages_plus_deps(initial_modules, result, soong_data): for module in initial_modules: if module in result: continue
result.add(module) if module in soong_data.deps:
get_module_product_packages_plus_deps(soong_data.deps[module], result, soong_data)
def main():
parser = argparse.ArgumentParser(description="Info about remaining Android.mk files.")
parser.add_argument("--device", type=str, required=True,
help="TARGET_DEVICE")
parser.add_argument("--product-packages", type=argparse.FileType('r'),
default=None,
help="PRODUCT_PACKAGES")
parser.add_argument("--title", type=str,
help="page title")
parser.add_argument("--codesearch", type=str,
default="https://cs.android.com/android/platform/superproject/+/master:",
help="page title")
parser.add_argument("--out-dir", type=str,
default=None,
help="Equivalent of $OUT_DIR, which will also be checked if"
+ " --out-dir is unset. If neither is set, default is"
+ " 'out'.")
parser.add_argument("--mode", type=str,
default="html",
help="output format: csv or html")
args = parser.parse_args()
# Guess out directory name ifnot args.out_dir:
args.out_dir = os.getenv("OUT_DIR", "out") while args.out_dir.endswith("/") and len(args.out_dir) > 1:
args.out_dir = args.out_dir[:-1]
TARGET_DEVICE = args.device global HOST_OUT_ROOT
HOST_OUT_ROOT = args.out_dir + "/host" global PRODUCT_OUT
PRODUCT_OUT = args.out_dir + "/target/product/%s" % TARGET_DEVICE
# Read target information # TODO: Pull from configurable location. This is also slightly different because it's # only a single build, where as the tree scanning we do below is all Android.mk files. with open("%s/obj/PACKAGING/soong_conversion_intermediates/soong_conv_data"
% PRODUCT_OUT, "r", errors="ignore") as csvfile:
soong = SoongData(csv.reader(csvfile))
# Read the makefiles
all_makefiles = dict() for filename, modules in soong.reverse_makefiles.items(): if filename.startswith(args.out_dir + "/"): continue
all_makefiles[filename] = Makefile(filename)
# Get all the modules in $(PRODUCT_PACKAGES) and the correspoding deps
product_package_modules_plus_deps = set() if args.product_packages:
product_package_top_modules = args.product_packages.read().strip().split('\n')
get_module_product_packages_plus_deps(product_package_top_modules, product_package_modules_plus_deps, soong)
print("""
<span class='NavSpacer'></span><span class='NavSpacer'> </span>
<a href='#summary'>Overall Summary</a>
</div>
<div id="container">
<div id="tables">
<a name="help"></a>
<div class="Help">
<p>
This page analyzes the remaining Android.mk files in the Android Source tree.
<p>
The modules are first broken down by which of the device filesystem partitions
they are installed to. This also includes host tools and testcases which don't
actually reside in their own partition but convenitely group together.
<p>
The makefiles for each partition are further are grouped into a set of directories
aritrarily picked to break down the problem size by owners.
<ul style="width: 300px">
<li style="background-color: #e6f4ea">AOSP directories are colored green.</li>
<li style="background-color: #e8f0fe">Google directories are colored blue.</li>
<li style="background-color: #fce8e6">Other partner directories are colored red.</li>
</ul>
Each of the makefiles are scanned for issues that are likely to come up during
conversion to soong. Clicking the number in each cell shows additional information,
including the line that triggered the warning.
<p>
<table class="HelpColumns">
<tr>
<th>Total</th>
<td>The total number of makefiles in this each directory.</td>
</tr>
<tr>
<th class="Clean">Easy</th>
<td>The number of makefiles that have no warnings themselves, and also none of their dependencies have warnings either.</td>
</tr>
<tr>
<th class="Clean">Unblocked Clean</th>
<td>The number of makefiles that are both Unblocked and Clean.</td>
</tr>
<tr>
<th class="Unblocked">Unblocked</th>
<td>Makefiles containing one or more modules that don't have any
additional dependencies pending before conversion.</td>
</tr>
<tr>
<th class="Blocked">Blocked</th>
<td>Makefiles containiong one or more modules which <i>do</i> have
additional prerequesite depenedencies that are not yet converted.</td>
</tr>
<tr>
<th class="Clean">Clean</th>
<td>The number of makefiles that have none of the following warnings.</td>
</tr>
<tr>
<th class="Warning">ifeq / ifneq</th>
<td>Makefiles that use <code>ifeq</code> or <code>ifneq</code>. i.e.
conditionals.</td>
</tr>
<tr>
<th class="Warning">Wacky Includes</th>
<td>Makefiles that <code>include</code> files other than the standard build-system
defined template and macros.</td>
</tr>
<tr>
<th class="Warning">Calls base_rules</th>
<td>Makefiles that include base_rules.mk directly.</td>
</tr>
<tr>
<th class="Warning">Calls define</th>
<td>Makefiles that define their own macros. Some of these are easy to convert
to soong <code>defaults</code>, but others are complex.</td>
</tr>
<tr>
<th class="Warning">Has ../</th>
<td>Makefiles containing the string "../" outside of a comment. These likely
access files outside their directories.</td>
</tr>
<tr>
<th class="Warning">dist-for-goals</th>
<td>Makefiles that call <code>dist-for-goals</code> directly.</td>
</tr>
<tr>
<th class="Warning">.PHONY</th>
<td>Makefiles that declare .PHONY targets.</td>
</tr>
<tr>
<th class="Warning">renderscript</th>
<td>Makefiles defining targets that depend on <code>.rscript</code> source files.</td>
</tr>
<tr>
<th class="Warning">vts src</th>
<td>Makefiles defining targets that depend on <code>.vts</code> source files.</td>
</tr>
<tr>
<th class="Warning">COPY_HEADERS</th>
<td>Makefiles using LOCAL_COPY_HEADERS.</td>
</tr>
</table>
<p>
Following the list of directories is a list of the modules that are installed on
each partition. Potential issues from their makefiles are listed, as well as the
total number of dependencies (both blocking that module and blocked by that module) and the list of direct dependencies. Note: The number is the number of all transitive
dependencies and the list of modules is only the direct dependencies.
</div> """)
overall_summary = Summary()
# For each partition for partition in sorted(partitions):
modules = modules_by_partition[partition]
makefiles = set(itertools.chain.from_iterable(
[self.soong.makefiles[module] for module in modules]))
# Read makefiles
summary = Summary() for filename in makefiles:
makefile = self.all_makefiles.get(filename) if makefile:
summary.Add(makefile)
overall_summary.Add(makefile)
# Categorize directories by who is responsible
aosp_dirs = []
google_dirs = []
partner_dirs = [] for dirname in sorted(summary.directories.keys()): if is_aosp(dirname):
aosp_dirs.append(dirname) elif is_google(dirname):
google_dirs.append(dirname) else:
partner_dirs.append(dirname)
for dirgroup, rowclass in [(aosp_dirs, "AospDir"),
(google_dirs, "GoogleDir"),
(partner_dirs, "PartnerDir"),]: for dirname in dirgroup:
self.print_analysis_row(summary, modules,
dirname, rowclass, summary.directories[dirname])
module_details = [(count_deps(self.soong.deps, m, []),
-count_deps(self.soong.reverse_deps, m, []), m) for m in modules]
module_details.sort()
module_details = [m[2] for m in module_details]
print("""
<table class="ModuleDetails">""")
print("<tr>")
print(" <th>Module Name</th>")
print(" <th>Issues</th>")
print(" <th colspan='2'>Blocked By</th>")
print(" <th colspan='2'>Blocking</th>")
print("</tr>")
altRow = True for module in module_details:
analyses = set() for filename in self.soong.makefiles[module]:
makefile = summary.makefiles.get(filename) if makefile: for analyzer, analysis in makefile.analyses.items(): if analysis:
analyses.add(analyzer.title)
var ANALYSIS = [ """ % { "codesearch": self.args.codesearch,
}) for entry, mods in self.annotations.entries:
print(" [") for analysis in entry:
print(" new Analysis('%(filename)s', %(modules)s, [%(line_matches)s])," % { "filename": analysis.filename, #"modules": json.dumps([m for m in mods if m in filename in self.soong.makefiles[m]]), "modules": json.dumps(
[m for m in self.soong.reverse_makefiles[analysis.filename] if m in mods]), "line_matches": ", ".join([ "new LineMatch(%d, %s)" % (lineno, json.dumps(text)) for lineno, text in analysis.line_matches]),
})
print(" ],")
print("""
];
var MODULE_DATA = { """) for module in self.soong.modules:
print(" '%(name)s': new Module(%(deps)s)," % { "name": module, "deps": json.dumps(self.soong.deps[module]),
})
print("""
};
</script>
def traverse_ready_makefiles(self, summary, makefiles): return [Analysis(makefile.filename, []) for makefile in makefiles if clean_and_only_blocked_by_clean(self.soong, self.all_makefiles, makefile)]
def print_analysis_row(self, summary, modules, rowtitle, rowclass, makefiles):
all_makefiles = [Analysis(makefile.filename, []) for makefile in makefiles]
clean_makefiles = [Analysis(makefile.filename, []) for makefile in makefiles if is_clean(makefile)]
easy_makefiles = self.traverse_ready_makefiles(summary, makefiles)
unblocked_clean_makefiles = [Analysis(makefile.filename, []) for makefile in makefiles if (self.soong.contains_unblocked_modules(makefile.filename) and is_clean(makefile))]
unblocked_makefiles = [Analysis(makefile.filename, []) for makefile in makefiles if self.soong.contains_unblocked_modules(makefile.filename)]
blocked_makefiles = [Analysis(makefile.filename, []) for makefile in makefiles if self.soong.contains_blocked_modules(makefile.filename)]
for analyzer in ANALYZERS:
analyses = [m.analyses.get(analyzer) for m in makefiles if m.analyses.get(analyzer)]
print("""<td class="Count">%s</td>"""
% self.make_annotation_link(analyses, modules))
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.