AAPT2: Automatic Static Library Namespacing.

Introduces a link flag --auto-namespace-static-lib for use when linking
static libraries.

When linking a static library with compiled sources that have references
to resources in provided libraries without an explicit package name,
the flag enables automatic inference of the package.

If a resource is present in the package that is being compiled, that is
used, otherwise the reference is rewritten to the highest precedence
resource with matching name and type.

Test: m out/host/linux-x86/nativetest64/aapt2_tests/aapt2_tests && \
      $ANDROID_HOST_OUT/nativetest64/aapt2_tests/aapt2_tests
Test: m frameworks/base/tools/aapt2/integration-tests
Change-Id: I6c6017e054654d1f60782d0a428a7a2a47f8952b
diff --git a/tools/aapt2/process/SymbolTable.cpp b/tools/aapt2/process/SymbolTable.cpp
index 2e97a2f..f6f0a50 100644
--- a/tools/aapt2/process/SymbolTable.cpp
+++ b/tools/aapt2/process/SymbolTable.cpp
@@ -114,6 +114,16 @@
   return shared_symbol.get();
 }
 
+const SymbolTable::Symbol* SymbolTable::FindByNameInAnyPackage(const ResourceName& name) {
+  for (auto& source : sources_) {
+    std::string package = source->GetPackageForSymbol(name);
+    if (!package.empty()) {
+      return FindByName(ResourceName(package, name.type, name.entry));
+    }
+  }
+  return {};
+}
+
 const SymbolTable::Symbol* SymbolTable::FindById(const ResourceId& id) {
   if (const std::shared_ptr<Symbol>& s = id_cache_.get(id)) {
     return s.get();
@@ -211,6 +221,25 @@
   return symbol;
 }
 
+std::string ResourceTableSymbolSource::GetPackageForSymbol(const ResourceName& name) {
+  for (auto& package : table_->packages) {
+    ResourceTableType* type = package->FindType(name.type);
+    if (type == nullptr) {
+      continue;
+    }
+    ResourceEntry* entry = type->FindEntry(name.entry);
+    if (entry == nullptr) {
+      continue;
+    }
+    return package->name;
+  }
+  if (name.type == ResourceType::kAttr) {
+    // Recurse and try looking up a private attribute.
+    return GetPackageForSymbol(ResourceName(name.package, ResourceType::kAttrPrivate, name.entry));
+  }
+  return {};
+}
+
 bool AssetManagerSymbolSource::AddAssetPath(const StringPiece& path) {
   int32_t cookie = 0;
   return assets_.addAssetPath(android::String8(path.data(), path.size()), &cookie);