Get NDK python script tests running.

Imports weren't working in tests because the package had been created.
The Python "binaries" built by Soong don't seem to take their own
pkg_path into account, so I split the separate pieces of code here out
into their own packages.

Note that the ndk_api_coverage_parser tests do not actually pass
before or after this change (seems like it might be a
non-deterministic ordering issue in the attributes of the generated
output?), but they can at least be run now.

Test: pytest ndkstubgen
Test: pytest symbolfile
Test: pytest ndk_api_coverage_parser
Test: out/host/linux-x86/nativetest64/test_ndkstubgen/test_ndkstubgen
Test: out/host/linux-x86/nativetest64/test_symbolfile/test_symbolfile
Test: out/host/linux-x86/nativetest64/test_ndk_api_coverage_parser/test_ndk_api_coverage_parser
Bug: None
Change-Id: I2ac22f7ced7566e4808070f2f72fd04355846e0b
diff --git a/cc/ndk_api_coverage_parser/.gitignore b/cc/ndk_api_coverage_parser/.gitignore
new file mode 100644
index 0000000..fd94eac
--- /dev/null
+++ b/cc/ndk_api_coverage_parser/.gitignore
@@ -0,0 +1,140 @@
+# From https://github.com/github/gitignore/blob/master/Python.gitignore
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+#   For a library or package, you might want to ignore these files since the code is
+#   intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+#   However, in case of collaboration, if having platform-specific dependencies or dependencies
+#   having no cross-platform support, pipenv may install dependencies that don't work, or not
+#   install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
diff --git a/cc/ndk_api_coverage_parser/Android.bp b/cc/ndk_api_coverage_parser/Android.bp
new file mode 100644
index 0000000..8d9827c
--- /dev/null
+++ b/cc/ndk_api_coverage_parser/Android.bp
@@ -0,0 +1,46 @@
+//
+// Copyright (C) 2020 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.
+//
+
+python_library_host {
+    name: "ndk_api_coverage_parser_lib",
+    pkg_path: "ndk_api_coverage_parser",
+    srcs: [
+        "__init__.py",
+    ],
+}
+
+python_test_host {
+    name: "test_ndk_api_coverage_parser",
+    main: "test_ndk_api_coverage_parser.py",
+    srcs: [
+        "test_ndk_api_coverage_parser.py",
+    ],
+    libs: [
+        "ndk_api_coverage_parser_lib",
+        "symbolfile",
+    ],
+}
+
+python_binary_host {
+    name: "ndk_api_coverage_parser",
+    main: "__init__.py",
+    srcs: [
+        "__init__.py",
+    ],
+    libs: [
+        "symbolfile",
+    ],
+}
diff --git a/cc/ndk_api_coverage_parser/OWNERS b/cc/ndk_api_coverage_parser/OWNERS
new file mode 100644
index 0000000..a90c48c
--- /dev/null
+++ b/cc/ndk_api_coverage_parser/OWNERS
@@ -0,0 +1 @@
+sophiez@google.com
diff --git a/cc/ndk_api_coverage_parser/__init__.py b/cc/ndk_api_coverage_parser/__init__.py
new file mode 100755
index 0000000..7817c78
--- /dev/null
+++ b/cc/ndk_api_coverage_parser/__init__.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2020 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.
+#
+"""Generates xml of NDK libraries used for API coverage analysis."""
+import argparse
+import json
+import os
+import sys
+
+from xml.etree.ElementTree import Element, SubElement, tostring
+from symbolfile import ALL_ARCHITECTURES, FUTURE_API_LEVEL, MultiplyDefinedSymbolError, SymbolFileParser
+
+
+ROOT_ELEMENT_TAG = 'ndk-library'
+SYMBOL_ELEMENT_TAG = 'symbol'
+ARCHITECTURE_ATTRIBUTE_KEY = 'arch'
+DEPRECATED_ATTRIBUTE_KEY = 'is_deprecated'
+PLATFORM_ATTRIBUTE_KEY = 'is_platform'
+NAME_ATTRIBUTE_KEY = 'name'
+VARIABLE_TAG = 'var'
+EXPOSED_TARGET_TAGS = (
+    'vndk',
+    'apex',
+    'llndk',
+)
+API_LEVEL_TAG_PREFIXES = (
+    'introduced=',
+    'introduced-',
+)
+
+
+def parse_tags(tags):
+    """Parses tags and save needed tags in the created attributes.
+
+    Return attributes dictionary.
+    """
+    attributes = {}
+    arch = []
+    for tag in tags:
+        if tag.startswith(tuple(API_LEVEL_TAG_PREFIXES)):
+            key, _, value = tag.partition('=')
+            attributes.update({key: value})
+        elif tag in ALL_ARCHITECTURES:
+            arch.append(tag)
+        elif tag in EXPOSED_TARGET_TAGS:
+            attributes.update({tag: 'True'})
+    attributes.update({ARCHITECTURE_ATTRIBUTE_KEY: ','.join(arch)})
+    return attributes
+
+
+class XmlGenerator(object):
+    """Output generator that writes parsed symbol file to a xml file."""
+    def __init__(self, output_file):
+        self.output_file = output_file
+
+    def convertToXml(self, versions):
+        """Writes all symbol data to the output file."""
+        root = Element(ROOT_ELEMENT_TAG)
+        for version in versions:
+            if VARIABLE_TAG in version.tags:
+                continue
+            version_attributes = parse_tags(version.tags)
+            _, _, postfix = version.name.partition('_')
+            is_platform = postfix == 'PRIVATE' or postfix == 'PLATFORM'
+            is_deprecated = postfix == 'DEPRECATED'
+            version_attributes.update({PLATFORM_ATTRIBUTE_KEY: str(is_platform)})
+            version_attributes.update({DEPRECATED_ATTRIBUTE_KEY: str(is_deprecated)})
+            for symbol in version.symbols:
+                if VARIABLE_TAG in symbol.tags:
+                    continue
+                attributes = {NAME_ATTRIBUTE_KEY: symbol.name}
+                attributes.update(version_attributes)
+                # If same version tags already exist, it will be overwrite here.
+                attributes.update(parse_tags(symbol.tags))
+                SubElement(root, SYMBOL_ELEMENT_TAG, attributes)
+        return root
+
+    def write_xml_to_file(self, root):
+        """Write xml element root to output_file."""
+        parsed_data = tostring(root)
+        output_file = open(self.output_file, "wb")
+        output_file.write(parsed_data)
+
+    def write(self, versions):
+        root = self.convertToXml(versions)
+        self.write_xml_to_file(root)
+
+
+def parse_args():
+    """Parses and returns command line arguments."""
+    parser = argparse.ArgumentParser()
+
+    parser.add_argument('symbol_file', type=os.path.realpath, help='Path to symbol file.')
+    parser.add_argument(
+        'output_file', type=os.path.realpath,
+        help='The output parsed api coverage file.')
+    parser.add_argument(
+        '--api-map', type=os.path.realpath, required=True,
+        help='Path to the API level map JSON file.')
+    return parser.parse_args()
+
+
+def main():
+    """Program entry point."""
+    args = parse_args()
+
+    with open(args.api_map) as map_file:
+        api_map = json.load(map_file)
+
+    with open(args.symbol_file) as symbol_file:
+        try:
+            versions = SymbolFileParser(symbol_file, api_map, "", FUTURE_API_LEVEL,
+                                        True, True).parse()
+        except MultiplyDefinedSymbolError as ex:
+            sys.exit('{}: error: {}'.format(args.symbol_file, ex))
+
+    generator = XmlGenerator(args.output_file)
+    generator.write(versions)
+
+if __name__ == '__main__':
+    main()
diff --git a/cc/ndk_api_coverage_parser/test_ndk_api_coverage_parser.py b/cc/ndk_api_coverage_parser/test_ndk_api_coverage_parser.py
new file mode 100644
index 0000000..f1c925c
--- /dev/null
+++ b/cc/ndk_api_coverage_parser/test_ndk_api_coverage_parser.py
@@ -0,0 +1,66 @@
+#!/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.
+#
+"""Tests for ndk_api_coverage_parser.py."""
+import io
+import textwrap
+import unittest
+
+from xml.etree.ElementTree import tostring
+from symbolfile import FUTURE_API_LEVEL, SymbolFileParser
+import ndk_api_coverage_parser as nparser
+
+
+# pylint: disable=missing-docstring
+
+
+class ApiCoverageSymbolFileParserTest(unittest.TestCase):
+    def test_parse(self):
+        input_file = io.StringIO(textwrap.dedent(u"""\
+            LIBLOG { # introduced-arm64=24 introduced-x86=24 introduced-x86_64=24
+              global:
+                android_name_to_log_id; # apex llndk introduced=23
+                android_log_id_to_name; # llndk arm
+                __android_log_assert; # introduced-x86=23
+                __android_log_buf_print; # var
+                __android_log_buf_write;
+              local:
+                *;
+            };
+            
+            LIBLOG_PLATFORM {
+                android_fdtrack; # llndk
+                android_net; # introduced=23
+            };
+            
+            LIBLOG_FOO { # var
+                android_var;
+            };
+        """))
+        parser = SymbolFileParser(input_file, {}, "", FUTURE_API_LEVEL, True, True)
+        generator = nparser.XmlGenerator(io.StringIO())
+        result = tostring(generator.convertToXml(parser.parse())).decode()
+        expected = '<ndk-library><symbol apex="True" arch="" introduced="23" introduced-arm64="24" introduced-x86="24" introduced-x86_64="24" is_deprecated="False" is_platform="False" llndk="True" name="android_name_to_log_id" /><symbol arch="arm" introduced-arm64="24" introduced-x86="24" introduced-x86_64="24" is_deprecated="False" is_platform="False" llndk="True" name="android_log_id_to_name" /><symbol arch="" introduced-arm64="24" introduced-x86="23" introduced-x86_64="24" is_deprecated="False" is_platform="False" name="__android_log_assert" /><symbol arch="" introduced-arm64="24" introduced-x86="24" introduced-x86_64="24" is_deprecated="False" is_platform="False" name="__android_log_buf_write" /><symbol arch="" is_deprecated="False" is_platform="True" llndk="True" name="android_fdtrack" /><symbol arch="" introduced="23" is_deprecated="False" is_platform="True" name="android_net" /></ndk-library>'
+        self.assertEqual(expected, result)
+
+
+def main():
+    suite = unittest.TestLoader().loadTestsFromName(__name__)
+    unittest.TextTestRunner(verbosity=3).run(suite)
+
+
+if __name__ == '__main__':
+    main()