AAPT2: Share split functionality between link and optimize

Generating splits should be possible to do from the optimize command.
This means that a lot of infrastructure around split APKs can be
shared by both the optimize and link phase.

Bug: 35925830
Change-Id: Ia88b9e4bff300a56353b2f7a4a2547c8eb43a299
Test: manual
diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp
new file mode 100644
index 0000000..578a8fb
--- /dev/null
+++ b/tools/aapt2/cmd/Compile.cpp
@@ -0,0 +1,740 @@
+/*
+ * Copyright (C) 2015 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.
+ */
+
+#include <dirent.h>
+
+#include <fstream>
+#include <string>
+
+#include "android-base/errors.h"
+#include "android-base/file.h"
+#include "androidfw/StringPiece.h"
+#include "google/protobuf/io/coded_stream.h"
+#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
+
+#include "ConfigDescription.h"
+#include "Diagnostics.h"
+#include "Flags.h"
+#include "ResourceParser.h"
+#include "ResourceTable.h"
+#include "compile/IdAssigner.h"
+#include "compile/InlineXmlFormatParser.h"
+#include "compile/Png.h"
+#include "compile/PseudolocaleGenerator.h"
+#include "compile/XmlIdCollector.h"
+#include "flatten/Archive.h"
+#include "flatten/XmlFlattener.h"
+#include "io/BigBufferOutputStream.h"
+#include "io/Util.h"
+#include "proto/ProtoSerialize.h"
+#include "util/Files.h"
+#include "util/Maybe.h"
+#include "util/Util.h"
+#include "xml/XmlDom.h"
+#include "xml/XmlPullParser.h"
+
+using android::StringPiece;
+using google::protobuf::io::CopyingOutputStreamAdaptor;
+
+namespace aapt {
+
+struct ResourcePathData {
+  Source source;
+  std::string resource_dir;
+  std::string name;
+  std::string extension;
+
+  // Original config str. We keep this because when we parse the config, we may
+  // add on
+  // version qualifiers. We want to preserve the original input so the output is
+  // easily
+  // computed before hand.
+  std::string config_str;
+  ConfigDescription config;
+};
+
+/**
+ * Resource file paths are expected to look like:
+ * [--/res/]type[-config]/name
+ */
+static Maybe<ResourcePathData> ExtractResourcePathData(const std::string& path,
+                                                       std::string* out_error) {
+  std::vector<std::string> parts = util::Split(path, file::sDirSep);
+  if (parts.size() < 2) {
+    if (out_error) *out_error = "bad resource path";
+    return {};
+  }
+
+  std::string& dir = parts[parts.size() - 2];
+  StringPiece dir_str = dir;
+
+  StringPiece config_str;
+  ConfigDescription config;
+  size_t dash_pos = dir.find('-');
+  if (dash_pos != std::string::npos) {
+    config_str = dir_str.substr(dash_pos + 1, dir.size() - (dash_pos + 1));
+    if (!ConfigDescription::Parse(config_str, &config)) {
+      if (out_error) {
+        std::stringstream err_str;
+        err_str << "invalid configuration '" << config_str << "'";
+        *out_error = err_str.str();
+      }
+      return {};
+    }
+    dir_str = dir_str.substr(0, dash_pos);
+  }
+
+  std::string& filename = parts[parts.size() - 1];
+  StringPiece name = filename;
+  StringPiece extension;
+  size_t dot_pos = filename.find('.');
+  if (dot_pos != std::string::npos) {
+    extension = name.substr(dot_pos + 1, filename.size() - (dot_pos + 1));
+    name = name.substr(0, dot_pos);
+  }
+
+  return ResourcePathData{Source(path),          dir_str.to_string(),    name.to_string(),
+                          extension.to_string(), config_str.to_string(), config};
+}
+
+struct CompileOptions {
+  std::string output_path;
+  Maybe<std::string> res_dir;
+  bool pseudolocalize = false;
+  bool legacy_mode = false;
+  bool verbose = false;
+};
+
+static std::string BuildIntermediateFilename(const ResourcePathData& data) {
+  std::stringstream name;
+  name << data.resource_dir;
+  if (!data.config_str.empty()) {
+    name << "-" << data.config_str;
+  }
+  name << "_" << data.name;
+  if (!data.extension.empty()) {
+    name << "." << data.extension;
+  }
+  name << ".flat";
+  return name.str();
+}
+
+static bool IsHidden(const StringPiece& filename) {
+  return util::StartsWith(filename, ".");
+}
+
+/**
+ * Walks the res directory structure, looking for resource files.
+ */
+static bool LoadInputFilesFromDir(IAaptContext* context, const CompileOptions& options,
+                                  std::vector<ResourcePathData>* out_path_data) {
+  const std::string& root_dir = options.res_dir.value();
+  std::unique_ptr<DIR, decltype(closedir)*> d(opendir(root_dir.data()), closedir);
+  if (!d) {
+    context->GetDiagnostics()->Error(DiagMessage()
+                                     << android::base::SystemErrorCodeToString(errno));
+    return false;
+  }
+
+  while (struct dirent* entry = readdir(d.get())) {
+    if (IsHidden(entry->d_name)) {
+      continue;
+    }
+
+    std::string prefix_path = root_dir;
+    file::AppendPath(&prefix_path, entry->d_name);
+
+    if (file::GetFileType(prefix_path) != file::FileType::kDirectory) {
+      continue;
+    }
+
+    std::unique_ptr<DIR, decltype(closedir)*> subdir(opendir(prefix_path.data()), closedir);
+    if (!subdir) {
+      context->GetDiagnostics()->Error(DiagMessage()
+                                       << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    while (struct dirent* leaf_entry = readdir(subdir.get())) {
+      if (IsHidden(leaf_entry->d_name)) {
+        continue;
+      }
+
+      std::string full_path = prefix_path;
+      file::AppendPath(&full_path, leaf_entry->d_name);
+
+      std::string err_str;
+      Maybe<ResourcePathData> path_data = ExtractResourcePathData(full_path, &err_str);
+      if (!path_data) {
+        context->GetDiagnostics()->Error(DiagMessage() << err_str);
+        return false;
+      }
+
+      out_path_data->push_back(std::move(path_data.value()));
+    }
+  }
+  return true;
+}
+
+static bool CompileTable(IAaptContext* context, const CompileOptions& options,
+                         const ResourcePathData& path_data, IArchiveWriter* writer,
+                         const std::string& output_path) {
+  ResourceTable table;
+  {
+    std::ifstream fin(path_data.source.path, std::ifstream::binary);
+    if (!fin) {
+      context->GetDiagnostics()->Error(DiagMessage(path_data.source)
+                                       << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    // Parse the values file from XML.
+    xml::XmlPullParser xml_parser(fin);
+
+    ResourceParserOptions parser_options;
+    parser_options.error_on_positional_arguments = !options.legacy_mode;
+
+    // If the filename includes donottranslate, then the default translatable is
+    // false.
+    parser_options.translatable = path_data.name.find("donottranslate") == std::string::npos;
+
+    ResourceParser res_parser(context->GetDiagnostics(), &table, path_data.source, path_data.config,
+                              parser_options);
+    if (!res_parser.Parse(&xml_parser)) {
+      return false;
+    }
+
+    fin.close();
+  }
+
+  if (options.pseudolocalize) {
+    // Generate pseudo-localized strings (en-XA and ar-XB).
+    // These are created as weak symbols, and are only generated from default
+    // configuration
+    // strings and plurals.
+    PseudolocaleGenerator pseudolocale_generator;
+    if (!pseudolocale_generator.Consume(context, &table)) {
+      return false;
+    }
+  }
+
+  // Ensure we have the compilation package at least.
+  table.CreatePackage(context->GetCompilationPackage());
+
+  // Assign an ID to any package that has resources.
+  for (auto& pkg : table.packages) {
+    if (!pkg->id) {
+      // If no package ID was set while parsing (public identifiers), auto
+      // assign an ID.
+      pkg->id = context->GetPackageId();
+    }
+  }
+
+  // Create the file/zip entry.
+  if (!writer->StartEntry(output_path, 0)) {
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to open");
+    return false;
+  }
+
+  // Make sure CopyingOutputStreamAdaptor is deleted before we call
+  // writer->FinishEntry().
+  {
+    // Wrap our IArchiveWriter with an adaptor that implements the
+    // ZeroCopyOutputStream interface.
+    CopyingOutputStreamAdaptor copying_adaptor(writer);
+
+    std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(&table);
+    if (!pb_table->SerializeToZeroCopyStream(&copying_adaptor)) {
+      context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to write");
+      return false;
+    }
+  }
+
+  if (!writer->FinishEntry()) {
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to finish entry");
+    return false;
+  }
+  return true;
+}
+
+static bool WriteHeaderAndBufferToWriter(const StringPiece& output_path, const ResourceFile& file,
+                                         const BigBuffer& buffer, IArchiveWriter* writer,
+                                         IDiagnostics* diag) {
+  // Start the entry so we can write the header.
+  if (!writer->StartEntry(output_path, 0)) {
+    diag->Error(DiagMessage(output_path) << "failed to open file");
+    return false;
+  }
+
+  // Make sure CopyingOutputStreamAdaptor is deleted before we call
+  // writer->FinishEntry().
+  {
+    // Wrap our IArchiveWriter with an adaptor that implements the
+    // ZeroCopyOutputStream interface.
+    CopyingOutputStreamAdaptor copying_adaptor(writer);
+    CompiledFileOutputStream output_stream(&copying_adaptor);
+
+    // Number of CompiledFiles.
+    output_stream.WriteLittleEndian32(1);
+
+    std::unique_ptr<pb::CompiledFile> compiled_file = SerializeCompiledFileToPb(file);
+    output_stream.WriteCompiledFile(compiled_file.get());
+    output_stream.WriteData(&buffer);
+
+    if (output_stream.HadError()) {
+      diag->Error(DiagMessage(output_path) << "failed to write data");
+      return false;
+    }
+  }
+
+  if (!writer->FinishEntry()) {
+    diag->Error(DiagMessage(output_path) << "failed to finish writing data");
+    return false;
+  }
+  return true;
+}
+
+static bool WriteHeaderAndMmapToWriter(const StringPiece& output_path, const ResourceFile& file,
+                                       const android::FileMap& map, IArchiveWriter* writer,
+                                       IDiagnostics* diag) {
+  // Start the entry so we can write the header.
+  if (!writer->StartEntry(output_path, 0)) {
+    diag->Error(DiagMessage(output_path) << "failed to open file");
+    return false;
+  }
+
+  // Make sure CopyingOutputStreamAdaptor is deleted before we call
+  // writer->FinishEntry().
+  {
+    // Wrap our IArchiveWriter with an adaptor that implements the
+    // ZeroCopyOutputStream interface.
+    CopyingOutputStreamAdaptor copying_adaptor(writer);
+    CompiledFileOutputStream output_stream(&copying_adaptor);
+
+    // Number of CompiledFiles.
+    output_stream.WriteLittleEndian32(1);
+
+    std::unique_ptr<pb::CompiledFile> compiled_file = SerializeCompiledFileToPb(file);
+    output_stream.WriteCompiledFile(compiled_file.get());
+    output_stream.WriteData(map.getDataPtr(), map.getDataLength());
+
+    if (output_stream.HadError()) {
+      diag->Error(DiagMessage(output_path) << "failed to write data");
+      return false;
+    }
+  }
+
+  if (!writer->FinishEntry()) {
+    diag->Error(DiagMessage(output_path) << "failed to finish writing data");
+    return false;
+  }
+  return true;
+}
+
+static bool FlattenXmlToOutStream(IAaptContext* context, const StringPiece& output_path,
+                                  xml::XmlResource* xmlres, CompiledFileOutputStream* out) {
+  BigBuffer buffer(1024);
+  XmlFlattenerOptions xml_flattener_options;
+  xml_flattener_options.keep_raw_values = true;
+  XmlFlattener flattener(&buffer, xml_flattener_options);
+  if (!flattener.Consume(context, xmlres)) {
+    return false;
+  }
+
+  std::unique_ptr<pb::CompiledFile> pb_compiled_file = SerializeCompiledFileToPb(xmlres->file);
+  out->WriteCompiledFile(pb_compiled_file.get());
+  out->WriteData(&buffer);
+
+  if (out->HadError()) {
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to write data");
+    return false;
+  }
+  return true;
+}
+
+static bool CompileXml(IAaptContext* context, const CompileOptions& options,
+                       const ResourcePathData& path_data, IArchiveWriter* writer,
+                       const std::string& output_path) {
+  if (context->IsVerbose()) {
+    context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling XML");
+  }
+
+  std::unique_ptr<xml::XmlResource> xmlres;
+  {
+    std::ifstream fin(path_data.source.path, std::ifstream::binary);
+    if (!fin) {
+      context->GetDiagnostics()->Error(DiagMessage(path_data.source)
+                                       << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    xmlres = xml::Inflate(&fin, context->GetDiagnostics(), path_data.source);
+
+    fin.close();
+  }
+
+  if (!xmlres) {
+    return false;
+  }
+
+  xmlres->file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
+  xmlres->file.config = path_data.config;
+  xmlres->file.source = path_data.source;
+
+  // Collect IDs that are defined here.
+  XmlIdCollector collector;
+  if (!collector.Consume(context, xmlres.get())) {
+    return false;
+  }
+
+  // Look for and process any <aapt:attr> tags and create sub-documents.
+  InlineXmlFormatParser inline_xml_format_parser;
+  if (!inline_xml_format_parser.Consume(context, xmlres.get())) {
+    return false;
+  }
+
+  // Start the entry so we can write the header.
+  if (!writer->StartEntry(output_path, 0)) {
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to open file");
+    return false;
+  }
+
+  // Make sure CopyingOutputStreamAdaptor is deleted before we call
+  // writer->FinishEntry().
+  {
+    // Wrap our IArchiveWriter with an adaptor that implements the
+    // ZeroCopyOutputStream
+    // interface.
+    CopyingOutputStreamAdaptor copying_adaptor(writer);
+    CompiledFileOutputStream output_stream(&copying_adaptor);
+
+    std::vector<std::unique_ptr<xml::XmlResource>>& inline_documents =
+        inline_xml_format_parser.GetExtractedInlineXmlDocuments();
+
+    // Number of CompiledFiles.
+    output_stream.WriteLittleEndian32(1 + inline_documents.size());
+
+    if (!FlattenXmlToOutStream(context, output_path, xmlres.get(), &output_stream)) {
+      return false;
+    }
+
+    for (auto& inline_xml_doc : inline_documents) {
+      if (!FlattenXmlToOutStream(context, output_path, inline_xml_doc.get(), &output_stream)) {
+        return false;
+      }
+    }
+  }
+
+  if (!writer->FinishEntry()) {
+    context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to finish writing data");
+    return false;
+  }
+  return true;
+}
+
+static bool CompilePng(IAaptContext* context, const CompileOptions& options,
+                       const ResourcePathData& path_data, IArchiveWriter* writer,
+                       const std::string& output_path) {
+  if (context->IsVerbose()) {
+    context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling PNG");
+  }
+
+  BigBuffer buffer(4096);
+  ResourceFile res_file;
+  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
+  res_file.config = path_data.config;
+  res_file.source = path_data.source;
+
+  {
+    std::string content;
+    if (!android::base::ReadFileToString(path_data.source.path, &content)) {
+      context->GetDiagnostics()->Error(DiagMessage(path_data.source)
+                                       << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    BigBuffer crunched_png_buffer(4096);
+    io::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer);
+
+    // Ensure that we only keep the chunks we care about if we end up
+    // using the original PNG instead of the crunched one.
+    PngChunkFilter png_chunk_filter(content);
+    std::unique_ptr<Image> image = ReadPng(context, &png_chunk_filter);
+    if (!image) {
+      return false;
+    }
+
+    std::unique_ptr<NinePatch> nine_patch;
+    if (path_data.extension == "9.png") {
+      std::string err;
+      nine_patch = NinePatch::Create(image->rows.get(), image->width, image->height, &err);
+      if (!nine_patch) {
+        context->GetDiagnostics()->Error(DiagMessage() << err);
+        return false;
+      }
+
+      // Remove the 1px border around the NinePatch.
+      // Basically the row array is shifted up by 1, and the length is treated
+      // as height - 2.
+      // For each row, shift the array to the left by 1, and treat the length as
+      // width - 2.
+      image->width -= 2;
+      image->height -= 2;
+      memmove(image->rows.get(), image->rows.get() + 1, image->height * sizeof(uint8_t**));
+      for (int32_t h = 0; h < image->height; h++) {
+        memmove(image->rows[h], image->rows[h] + 4, image->width * 4);
+      }
+
+      if (context->IsVerbose()) {
+        context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "9-patch: "
+                                                                      << *nine_patch);
+      }
+    }
+
+    // Write the crunched PNG.
+    if (!WritePng(context, image.get(), nine_patch.get(), &crunched_png_buffer_out, {})) {
+      return false;
+    }
+
+    if (nine_patch != nullptr ||
+        crunched_png_buffer_out.ByteCount() <= png_chunk_filter.ByteCount()) {
+      // No matter what, we must use the re-encoded PNG, even if it is larger.
+      // 9-patch images must be re-encoded since their borders are stripped.
+      buffer.AppendBuffer(std::move(crunched_png_buffer));
+    } else {
+      // The re-encoded PNG is larger than the original, and there is
+      // no mandatory transformation. Use the original.
+      if (context->IsVerbose()) {
+        context->GetDiagnostics()->Note(DiagMessage(path_data.source)
+                                        << "original PNG is smaller than crunched PNG"
+                                        << ", using original");
+      }
+
+      png_chunk_filter.Rewind();
+      BigBuffer filtered_png_buffer(4096);
+      io::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer);
+      io::Copy(&filtered_png_buffer_out, &png_chunk_filter);
+      buffer.AppendBuffer(std::move(filtered_png_buffer));
+    }
+
+    if (context->IsVerbose()) {
+      // For debugging only, use the legacy PNG cruncher and compare the resulting file sizes.
+      // This will help catch exotic cases where the new code may generate larger PNGs.
+      std::stringstream legacy_stream(content);
+      BigBuffer legacy_buffer(4096);
+      Png png(context->GetDiagnostics());
+      if (!png.process(path_data.source, &legacy_stream, &legacy_buffer, {})) {
+        return false;
+      }
+
+      context->GetDiagnostics()->Note(DiagMessage(path_data.source)
+                                      << "legacy=" << legacy_buffer.size()
+                                      << " new=" << buffer.size());
+    }
+  }
+
+  if (!WriteHeaderAndBufferToWriter(output_path, res_file, buffer, writer,
+                                    context->GetDiagnostics())) {
+    return false;
+  }
+  return true;
+}
+
+static bool CompileFile(IAaptContext* context, const CompileOptions& options,
+                        const ResourcePathData& path_data, IArchiveWriter* writer,
+                        const std::string& output_path) {
+  if (context->IsVerbose()) {
+    context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling file");
+  }
+
+  BigBuffer buffer(256);
+  ResourceFile res_file;
+  res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
+  res_file.config = path_data.config;
+  res_file.source = path_data.source;
+
+  std::string error_str;
+  Maybe<android::FileMap> f = file::MmapPath(path_data.source.path, &error_str);
+  if (!f) {
+    context->GetDiagnostics()->Error(DiagMessage(path_data.source) << error_str);
+    return false;
+  }
+
+  if (!WriteHeaderAndMmapToWriter(output_path, res_file, f.value(), writer,
+                                  context->GetDiagnostics())) {
+    return false;
+  }
+  return true;
+}
+
+class CompileContext : public IAaptContext {
+ public:
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
+
+  bool IsVerbose() override {
+    return verbose_;
+  }
+
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    abort();
+    return nullptr;
+  }
+
+  const std::string& GetCompilationPackage() override {
+    static std::string empty;
+    return empty;
+  }
+
+  uint8_t GetPackageId() override {
+    return 0x0;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    abort();
+    return nullptr;
+  }
+
+  int GetMinSdkVersion() override {
+    return 0;
+  }
+
+ private:
+  StdErrDiagnostics diagnostics_;
+  bool verbose_ = false;
+};
+
+/**
+ * Entry point for compilation phase. Parses arguments and dispatches to the
+ * correct steps.
+ */
+int Compile(const std::vector<StringPiece>& args) {
+  CompileContext context;
+  CompileOptions options;
+
+  bool verbose = false;
+  Flags flags =
+      Flags()
+          .RequiredFlag("-o", "Output path", &options.output_path)
+          .OptionalFlag("--dir", "Directory to scan for resources", &options.res_dir)
+          .OptionalSwitch("--pseudo-localize",
+                          "Generate resources for pseudo-locales "
+                          "(en-XA and ar-XB)",
+                          &options.pseudolocalize)
+          .OptionalSwitch("--legacy", "Treat errors that used to be valid in AAPT as warnings",
+                          &options.legacy_mode)
+          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
+  if (!flags.Parse("aapt2 compile", args, &std::cerr)) {
+    return 1;
+  }
+
+  context.SetVerbose(verbose);
+
+  std::unique_ptr<IArchiveWriter> archive_writer;
+
+  std::vector<ResourcePathData> input_data;
+  if (options.res_dir) {
+    if (!flags.GetArgs().empty()) {
+      // Can't have both files and a resource directory.
+      context.GetDiagnostics()->Error(DiagMessage() << "files given but --dir specified");
+      flags.Usage("aapt2 compile", &std::cerr);
+      return 1;
+    }
+
+    if (!LoadInputFilesFromDir(&context, options, &input_data)) {
+      return 1;
+    }
+
+    archive_writer = CreateZipFileArchiveWriter(context.GetDiagnostics(), options.output_path);
+
+  } else {
+    input_data.reserve(flags.GetArgs().size());
+
+    // Collect data from the path for each input file.
+    for (const std::string& arg : flags.GetArgs()) {
+      std::string error_str;
+      if (Maybe<ResourcePathData> path_data = ExtractResourcePathData(arg, &error_str)) {
+        input_data.push_back(std::move(path_data.value()));
+      } else {
+        context.GetDiagnostics()->Error(DiagMessage() << error_str << " (" << arg << ")");
+        return 1;
+      }
+    }
+
+    archive_writer = CreateDirectoryArchiveWriter(context.GetDiagnostics(), options.output_path);
+  }
+
+  if (!archive_writer) {
+    return 1;
+  }
+
+  bool error = false;
+  for (ResourcePathData& path_data : input_data) {
+    if (options.verbose) {
+      context.GetDiagnostics()->Note(DiagMessage(path_data.source) << "processing");
+    }
+
+    if (path_data.resource_dir == "values") {
+      // Overwrite the extension.
+      path_data.extension = "arsc";
+
+      const std::string output_filename = BuildIntermediateFilename(path_data);
+      if (!CompileTable(&context, options, path_data, archive_writer.get(), output_filename)) {
+        error = true;
+      }
+
+    } else {
+      const std::string output_filename = BuildIntermediateFilename(path_data);
+      if (const ResourceType* type = ParseResourceType(path_data.resource_dir)) {
+        if (*type != ResourceType::kRaw) {
+          if (path_data.extension == "xml") {
+            if (!CompileXml(&context, options, path_data, archive_writer.get(), output_filename)) {
+              error = true;
+            }
+          } else if (path_data.extension == "png" || path_data.extension == "9.png") {
+            if (!CompilePng(&context, options, path_data, archive_writer.get(), output_filename)) {
+              error = true;
+            }
+          } else {
+            if (!CompileFile(&context, options, path_data, archive_writer.get(), output_filename)) {
+              error = true;
+            }
+          }
+        } else {
+          if (!CompileFile(&context, options, path_data, archive_writer.get(), output_filename)) {
+            error = true;
+          }
+        }
+      } else {
+        context.GetDiagnostics()->Error(DiagMessage() << "invalid file path '" << path_data.source
+                                                      << "'");
+        error = true;
+      }
+    }
+  }
+
+  if (error) {
+    return 1;
+  }
+  return 0;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Diff.cpp b/tools/aapt2/cmd/Diff.cpp
new file mode 100644
index 0000000..fdc89b2
--- /dev/null
+++ b/tools/aapt2/cmd/Diff.cpp
@@ -0,0 +1,372 @@
+/*
+ * 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.
+ */
+
+#include "android-base/macros.h"
+
+#include "Flags.h"
+#include "LoadedApk.h"
+#include "ValueVisitor.h"
+#include "process/IResourceTableConsumer.h"
+#include "process/SymbolTable.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+class DiffContext : public IAaptContext {
+ public:
+  DiffContext() : name_mangler_({}), symbol_table_(&name_mangler_) {
+  }
+
+  const std::string& GetCompilationPackage() override {
+    return empty_;
+  }
+
+  uint8_t GetPackageId() override {
+    return 0x0;
+  }
+
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    return &name_mangler_;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    return &symbol_table_;
+  }
+
+  bool IsVerbose() override {
+    return false;
+  }
+
+  int GetMinSdkVersion() override {
+    return 0;
+  }
+
+ private:
+  std::string empty_;
+  StdErrDiagnostics diagnostics_;
+  NameMangler name_mangler_;
+  SymbolTable symbol_table_;
+};
+
+static void EmitDiffLine(const Source& source, const StringPiece& message) {
+  std::cerr << source << ": " << message << "\n";
+}
+
+static bool IsSymbolVisibilityDifferent(const Symbol& symbol_a, const Symbol& symbol_b) {
+  return symbol_a.state != symbol_b.state;
+}
+
+template <typename Id>
+static bool IsIdDiff(const Symbol& symbol_a, const Maybe<Id>& id_a, const Symbol& symbol_b,
+                     const Maybe<Id>& id_b) {
+  if (symbol_a.state == SymbolState::kPublic || symbol_b.state == SymbolState::kPublic) {
+    return id_a != id_b;
+  }
+  return false;
+}
+
+static bool EmitResourceConfigValueDiff(IAaptContext* context, LoadedApk* apk_a,
+                                        ResourceTablePackage* pkg_a, ResourceTableType* type_a,
+                                        ResourceEntry* entry_a, ResourceConfigValue* config_value_a,
+                                        LoadedApk* apk_b, ResourceTablePackage* pkg_b,
+                                        ResourceTableType* type_b, ResourceEntry* entry_b,
+                                        ResourceConfigValue* config_value_b) {
+  Value* value_a = config_value_a->value.get();
+  Value* value_b = config_value_b->value.get();
+  if (!value_a->Equals(value_b)) {
+    std::stringstream str_stream;
+    str_stream << "value " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+               << " config=" << config_value_a->config << " does not match:\n";
+    value_a->Print(&str_stream);
+    str_stream << "\n vs \n";
+    value_b->Print(&str_stream);
+    EmitDiffLine(apk_b->GetSource(), str_stream.str());
+    return true;
+  }
+  return false;
+}
+
+static bool EmitResourceEntryDiff(IAaptContext* context, LoadedApk* apk_a,
+                                  ResourceTablePackage* pkg_a, ResourceTableType* type_a,
+                                  ResourceEntry* entry_a, LoadedApk* apk_b,
+                                  ResourceTablePackage* pkg_b, ResourceTableType* type_b,
+                                  ResourceEntry* entry_b) {
+  bool diff = false;
+  for (std::unique_ptr<ResourceConfigValue>& config_value_a : entry_a->values) {
+    ResourceConfigValue* config_value_b = entry_b->FindValue(config_value_a->config);
+    if (!config_value_b) {
+      std::stringstream str_stream;
+      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+                 << " config=" << config_value_a->config;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    } else {
+      diff |=
+          EmitResourceConfigValueDiff(context, apk_a, pkg_a, type_a, entry_a, config_value_a.get(),
+                                      apk_b, pkg_b, type_b, entry_b, config_value_b);
+    }
+  }
+
+  // Check for any newly added config values.
+  for (std::unique_ptr<ResourceConfigValue>& config_value_b : entry_b->values) {
+    ResourceConfigValue* config_value_a = entry_a->FindValue(config_value_b->config);
+    if (!config_value_a) {
+      std::stringstream str_stream;
+      str_stream << "new config " << pkg_b->name << ":" << type_b->type << "/" << entry_b->name
+                 << " config=" << config_value_b->config;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    }
+  }
+  return false;
+}
+
+static bool EmitResourceTypeDiff(IAaptContext* context, LoadedApk* apk_a,
+                                 ResourceTablePackage* pkg_a, ResourceTableType* type_a,
+                                 LoadedApk* apk_b, ResourceTablePackage* pkg_b,
+                                 ResourceTableType* type_b) {
+  bool diff = false;
+  for (std::unique_ptr<ResourceEntry>& entry_a : type_a->entries) {
+    ResourceEntry* entry_b = type_b->FindEntry(entry_a->name);
+    if (!entry_b) {
+      std::stringstream str_stream;
+      str_stream << "missing " << pkg_a->name << ":" << type_a->type << "/" << entry_a->name;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    } else {
+      if (IsSymbolVisibilityDifferent(entry_a->symbol_status, entry_b->symbol_status)) {
+        std::stringstream str_stream;
+        str_stream << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+                   << " has different visibility (";
+        if (entry_b->symbol_status.state == SymbolState::kPublic) {
+          str_stream << "PUBLIC";
+        } else {
+          str_stream << "PRIVATE";
+        }
+        str_stream << " vs ";
+        if (entry_a->symbol_status.state == SymbolState::kPublic) {
+          str_stream << "PUBLIC";
+        } else {
+          str_stream << "PRIVATE";
+        }
+        str_stream << ")";
+        EmitDiffLine(apk_b->GetSource(), str_stream.str());
+        diff = true;
+      } else if (IsIdDiff(entry_a->symbol_status, entry_a->id, entry_b->symbol_status,
+                          entry_b->id)) {
+        std::stringstream str_stream;
+        str_stream << pkg_a->name << ":" << type_a->type << "/" << entry_a->name
+                   << " has different public ID (";
+        if (entry_b->id) {
+          str_stream << "0x" << std::hex << entry_b->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << " vs ";
+        if (entry_a->id) {
+          str_stream << "0x " << std::hex << entry_a->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << ")";
+        EmitDiffLine(apk_b->GetSource(), str_stream.str());
+        diff = true;
+      }
+      diff |= EmitResourceEntryDiff(context, apk_a, pkg_a, type_a, entry_a.get(), apk_b, pkg_b,
+                                    type_b, entry_b);
+    }
+  }
+
+  // Check for any newly added entries.
+  for (std::unique_ptr<ResourceEntry>& entry_b : type_b->entries) {
+    ResourceEntry* entry_a = type_a->FindEntry(entry_b->name);
+    if (!entry_a) {
+      std::stringstream str_stream;
+      str_stream << "new entry " << pkg_b->name << ":" << type_b->type << "/" << entry_b->name;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    }
+  }
+  return diff;
+}
+
+static bool EmitResourcePackageDiff(IAaptContext* context, LoadedApk* apk_a,
+                                    ResourceTablePackage* pkg_a, LoadedApk* apk_b,
+                                    ResourceTablePackage* pkg_b) {
+  bool diff = false;
+  for (std::unique_ptr<ResourceTableType>& type_a : pkg_a->types) {
+    ResourceTableType* type_b = pkg_b->FindType(type_a->type);
+    if (!type_b) {
+      std::stringstream str_stream;
+      str_stream << "missing " << pkg_a->name << ":" << type_a->type;
+      EmitDiffLine(apk_a->GetSource(), str_stream.str());
+      diff = true;
+    } else {
+      if (IsSymbolVisibilityDifferent(type_a->symbol_status, type_b->symbol_status)) {
+        std::stringstream str_stream;
+        str_stream << pkg_a->name << ":" << type_a->type << " has different visibility (";
+        if (type_b->symbol_status.state == SymbolState::kPublic) {
+          str_stream << "PUBLIC";
+        } else {
+          str_stream << "PRIVATE";
+        }
+        str_stream << " vs ";
+        if (type_a->symbol_status.state == SymbolState::kPublic) {
+          str_stream << "PUBLIC";
+        } else {
+          str_stream << "PRIVATE";
+        }
+        str_stream << ")";
+        EmitDiffLine(apk_b->GetSource(), str_stream.str());
+        diff = true;
+      } else if (IsIdDiff(type_a->symbol_status, type_a->id, type_b->symbol_status, type_b->id)) {
+        std::stringstream str_stream;
+        str_stream << pkg_a->name << ":" << type_a->type << " has different public ID (";
+        if (type_b->id) {
+          str_stream << "0x" << std::hex << type_b->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << " vs ";
+        if (type_a->id) {
+          str_stream << "0x " << std::hex << type_a->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << ")";
+        EmitDiffLine(apk_b->GetSource(), str_stream.str());
+        diff = true;
+      }
+      diff |= EmitResourceTypeDiff(context, apk_a, pkg_a, type_a.get(), apk_b, pkg_b, type_b);
+    }
+  }
+
+  // Check for any newly added types.
+  for (std::unique_ptr<ResourceTableType>& type_b : pkg_b->types) {
+    ResourceTableType* type_a = pkg_a->FindType(type_b->type);
+    if (!type_a) {
+      std::stringstream str_stream;
+      str_stream << "new type " << pkg_b->name << ":" << type_b->type;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    }
+  }
+  return diff;
+}
+
+static bool EmitResourceTableDiff(IAaptContext* context, LoadedApk* apk_a, LoadedApk* apk_b) {
+  ResourceTable* table_a = apk_a->GetResourceTable();
+  ResourceTable* table_b = apk_b->GetResourceTable();
+
+  bool diff = false;
+  for (std::unique_ptr<ResourceTablePackage>& pkg_a : table_a->packages) {
+    ResourceTablePackage* pkg_b = table_b->FindPackage(pkg_a->name);
+    if (!pkg_b) {
+      std::stringstream str_stream;
+      str_stream << "missing package " << pkg_a->name;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    } else {
+      if (pkg_a->id != pkg_b->id) {
+        std::stringstream str_stream;
+        str_stream << "package '" << pkg_a->name << "' has different id (";
+        if (pkg_b->id) {
+          str_stream << "0x" << std::hex << pkg_b->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << " vs ";
+        if (pkg_a->id) {
+          str_stream << "0x" << std::hex << pkg_a->id.value();
+        } else {
+          str_stream << "none";
+        }
+        str_stream << ")";
+        EmitDiffLine(apk_b->GetSource(), str_stream.str());
+        diff = true;
+      }
+      diff |= EmitResourcePackageDiff(context, apk_a, pkg_a.get(), apk_b, pkg_b);
+    }
+  }
+
+  // Check for any newly added packages.
+  for (std::unique_ptr<ResourceTablePackage>& pkg_b : table_b->packages) {
+    ResourceTablePackage* pkg_a = table_a->FindPackage(pkg_b->name);
+    if (!pkg_a) {
+      std::stringstream str_stream;
+      str_stream << "new package " << pkg_b->name;
+      EmitDiffLine(apk_b->GetSource(), str_stream.str());
+      diff = true;
+    }
+  }
+  return diff;
+}
+
+class ZeroingReferenceVisitor : public ValueVisitor {
+ public:
+  using ValueVisitor::Visit;
+
+  void Visit(Reference* ref) override {
+    if (ref->name && ref->id) {
+      if (ref->id.value().package_id() == kAppPackageId) {
+        ref->id = {};
+      }
+    }
+  }
+};
+
+static void ZeroOutAppReferences(ResourceTable* table) {
+  ZeroingReferenceVisitor visitor;
+  VisitAllValuesInTable(table, &visitor);
+}
+
+int Diff(const std::vector<StringPiece>& args) {
+  DiffContext context;
+
+  Flags flags;
+  if (!flags.Parse("aapt2 diff", args, &std::cerr)) {
+    return 1;
+  }
+
+  if (flags.GetArgs().size() != 2u) {
+    std::cerr << "must have two apks as arguments.\n\n";
+    flags.Usage("aapt2 diff", &std::cerr);
+    return 1;
+  }
+
+  std::unique_ptr<LoadedApk> apk_a = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
+  std::unique_ptr<LoadedApk> apk_b = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[1]);
+  if (!apk_a || !apk_b) {
+    return 1;
+  }
+
+  // Zero out Application IDs in references.
+  ZeroOutAppReferences(apk_a->GetResourceTable());
+  ZeroOutAppReferences(apk_b->GetResourceTable());
+
+  if (EmitResourceTableDiff(&context, apk_a.get(), apk_b.get())) {
+    // We emitted a diff, so return 1 (failure).
+    return 1;
+  }
+  return 0;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Dump.cpp b/tools/aapt2/cmd/Dump.cpp
new file mode 100644
index 0000000..1bbfb28
--- /dev/null
+++ b/tools/aapt2/cmd/Dump.cpp
@@ -0,0 +1,206 @@
+/*
+ * 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.
+ */
+
+#include <vector>
+
+#include "androidfw/StringPiece.h"
+
+#include "Debug.h"
+#include "Diagnostics.h"
+#include "Flags.h"
+#include "io/ZipArchive.h"
+#include "process/IResourceTableConsumer.h"
+#include "proto/ProtoSerialize.h"
+#include "unflatten/BinaryResourceParser.h"
+#include "util/Files.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+void DumpCompiledFile(const pb::CompiledFile& pb_file, const void* data, size_t len,
+                      const Source& source, IAaptContext* context) {
+  std::unique_ptr<ResourceFile> file =
+      DeserializeCompiledFileFromPb(pb_file, source, context->GetDiagnostics());
+  if (!file) {
+    context->GetDiagnostics()->Warn(DiagMessage() << "failed to read compiled file");
+    return;
+  }
+
+  std::cout << "Resource: " << file->name << "\n"
+            << "Config:   " << file->config << "\n"
+            << "Source:   " << file->source << "\n";
+}
+
+void TryDumpFile(IAaptContext* context, const std::string& file_path) {
+  std::unique_ptr<ResourceTable> table;
+
+  std::string err;
+  std::unique_ptr<io::ZipFileCollection> zip = io::ZipFileCollection::Create(file_path, &err);
+  if (zip) {
+    io::IFile* file = zip->FindFile("resources.arsc.flat");
+    if (file) {
+      std::unique_ptr<io::IData> data = file->OpenAsData();
+      if (!data) {
+        context->GetDiagnostics()->Error(DiagMessage(file_path)
+                                         << "failed to open resources.arsc.flat");
+        return;
+      }
+
+      pb::ResourceTable pb_table;
+      if (!pb_table.ParseFromArray(data->data(), data->size())) {
+        context->GetDiagnostics()->Error(DiagMessage(file_path) << "invalid resources.arsc.flat");
+        return;
+      }
+
+      table = DeserializeTableFromPb(pb_table, Source(file_path), context->GetDiagnostics());
+      if (!table) {
+        return;
+      }
+    }
+
+    if (!table) {
+      file = zip->FindFile("resources.arsc");
+      if (file) {
+        std::unique_ptr<io::IData> data = file->OpenAsData();
+        if (!data) {
+          context->GetDiagnostics()->Error(DiagMessage(file_path)
+                                           << "failed to open resources.arsc");
+          return;
+        }
+
+        table = util::make_unique<ResourceTable>();
+        BinaryResourceParser parser(context, table.get(), Source(file_path), data->data(),
+                                    data->size());
+        if (!parser.Parse()) {
+          return;
+        }
+      }
+    }
+  }
+
+  if (!table) {
+    Maybe<android::FileMap> file = file::MmapPath(file_path, &err);
+    if (!file) {
+      context->GetDiagnostics()->Error(DiagMessage(file_path) << err);
+      return;
+    }
+
+    android::FileMap* file_map = &file.value();
+
+    // Try as a compiled table.
+    pb::ResourceTable pb_table;
+    if (pb_table.ParseFromArray(file_map->getDataPtr(), file_map->getDataLength())) {
+      table = DeserializeTableFromPb(pb_table, Source(file_path), context->GetDiagnostics());
+    }
+
+    if (!table) {
+      // Try as a compiled file.
+      CompiledFileInputStream input(file_map->getDataPtr(), file_map->getDataLength());
+
+      uint32_t num_files = 0;
+      if (!input.ReadLittleEndian32(&num_files)) {
+        return;
+      }
+
+      for (uint32_t i = 0; i < num_files; i++) {
+        pb::CompiledFile compiled_file;
+        if (!input.ReadCompiledFile(&compiled_file)) {
+          context->GetDiagnostics()->Warn(DiagMessage() << "failed to read compiled file");
+          return;
+        }
+
+        uint64_t offset, len;
+        if (!input.ReadDataMetaData(&offset, &len)) {
+          context->GetDiagnostics()->Warn(DiagMessage() << "failed to read meta data");
+          return;
+        }
+
+        const void* data = static_cast<const uint8_t*>(file_map->getDataPtr()) + offset;
+        DumpCompiledFile(compiled_file, data, len, Source(file_path), context);
+      }
+    }
+  }
+
+  if (table) {
+    DebugPrintTableOptions options;
+    options.show_sources = true;
+    Debug::PrintTable(table.get(), options);
+  }
+}
+
+class DumpContext : public IAaptContext {
+ public:
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    abort();
+    return nullptr;
+  }
+
+  const std::string& GetCompilationPackage() override {
+    static std::string empty;
+    return empty;
+  }
+
+  uint8_t GetPackageId() override {
+    return 0;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    abort();
+    return nullptr;
+  }
+
+  bool IsVerbose() override {
+    return verbose_;
+  }
+
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
+
+  int GetMinSdkVersion() override {
+    return 0;
+  }
+
+ private:
+  StdErrDiagnostics diagnostics_;
+  bool verbose_ = false;
+};
+
+/**
+ * Entry point for dump command.
+ */
+int Dump(const std::vector<StringPiece>& args) {
+  bool verbose = false;
+  Flags flags = Flags().OptionalSwitch("-v", "increase verbosity of output", &verbose);
+  if (!flags.Parse("aapt2 dump", args, &std::cerr)) {
+    return 1;
+  }
+
+  DumpContext context;
+  context.SetVerbose(verbose);
+
+  for (const std::string& arg : flags.GetArgs()) {
+    TryDumpFile(&context, arg);
+  }
+  return 0;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp
new file mode 100644
index 0000000..6e0809e
--- /dev/null
+++ b/tools/aapt2/cmd/Link.cpp
@@ -0,0 +1,2009 @@
+/*
+ * Copyright (C) 2015 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.
+ */
+
+#include <sys/stat.h>
+
+#include <fstream>
+#include <queue>
+#include <unordered_map>
+#include <vector>
+
+#include "android-base/errors.h"
+#include "android-base/file.h"
+#include "android-base/stringprintf.h"
+#include "androidfw/StringPiece.h"
+#include "google/protobuf/io/coded_stream.h"
+
+#include "AppInfo.h"
+#include "Debug.h"
+#include "Flags.h"
+#include "Locale.h"
+#include "NameMangler.h"
+#include "ResourceUtils.h"
+#include "cmd/Util.h"
+#include "compile/IdAssigner.h"
+#include "filter/ConfigFilter.h"
+#include "flatten/Archive.h"
+#include "flatten/TableFlattener.h"
+#include "flatten/XmlFlattener.h"
+#include "io/BigBufferInputStream.h"
+#include "io/FileSystem.h"
+#include "io/Util.h"
+#include "io/ZipArchive.h"
+#include "java/JavaClassGenerator.h"
+#include "java/ManifestClassGenerator.h"
+#include "java/ProguardRules.h"
+#include "link/Linkers.h"
+#include "link/ManifestFixer.h"
+#include "link/ReferenceLinker.h"
+#include "link/TableMerger.h"
+#include "optimize/ResourceDeduper.h"
+#include "optimize/VersionCollapser.h"
+#include "process/IResourceTableConsumer.h"
+#include "process/SymbolTable.h"
+#include "proto/ProtoSerialize.h"
+#include "split/TableSplitter.h"
+#include "unflatten/BinaryResourceParser.h"
+#include "util/Files.h"
+#include "xml/XmlDom.h"
+
+using android::StringPiece;
+using android::base::StringPrintf;
+
+namespace aapt {
+
+// The type of package to build.
+enum class PackageType {
+  kApp,
+  kSharedLib,
+  kStaticLib,
+};
+
+struct LinkOptions {
+  PackageType package_type = PackageType::kApp;
+
+  std::string output_path;
+  std::string manifest_path;
+  std::vector<std::string> include_paths;
+  std::vector<std::string> overlay_files;
+  std::vector<std::string> assets_dirs;
+  bool output_to_directory = false;
+  bool auto_add_overlay = false;
+
+  // Java/Proguard options.
+  Maybe<std::string> generate_java_class_path;
+  Maybe<std::string> custom_java_package;
+  std::set<std::string> extra_java_packages;
+  Maybe<std::string> generate_proguard_rules_path;
+  Maybe<std::string> generate_main_dex_proguard_rules_path;
+  bool generate_non_final_ids = false;
+  std::vector<std::string> javadoc_annotations;
+  Maybe<std::string> private_symbols;
+
+  // Optimizations/features.
+  bool no_auto_version = false;
+  bool no_version_vectors = false;
+  bool no_version_transitions = false;
+  bool no_resource_deduping = false;
+  bool no_xml_namespaces = false;
+  bool do_not_compress_anything = false;
+  std::unordered_set<std::string> extensions_to_not_compress;
+
+  // Static lib options.
+  bool no_static_lib_packages = false;
+
+  // AndroidManifest.xml massaging options.
+  ManifestFixerOptions manifest_fixer_options;
+
+  // Products to use/filter on.
+  std::unordered_set<std::string> products;
+
+  // Flattening options.
+  TableFlattenerOptions table_flattener_options;
+
+  // Split APK options.
+  TableSplitterOptions table_splitter_options;
+  std::vector<SplitConstraints> split_constraints;
+  std::vector<std::string> split_paths;
+
+  // Stable ID options.
+  std::unordered_map<ResourceName, ResourceId> stable_id_map;
+  Maybe<std::string> resource_id_map_path;
+};
+
+class LinkContext : public IAaptContext {
+ public:
+  LinkContext() : name_mangler_({}), symbols_(&name_mangler_) {
+  }
+
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    return &name_mangler_;
+  }
+
+  void SetNameManglerPolicy(const NameManglerPolicy& policy) {
+    name_mangler_ = NameMangler(policy);
+  }
+
+  const std::string& GetCompilationPackage() override {
+    return compilation_package_;
+  }
+
+  void SetCompilationPackage(const StringPiece& package_name) {
+    compilation_package_ = package_name.to_string();
+  }
+
+  uint8_t GetPackageId() override {
+    return package_id_;
+  }
+
+  void SetPackageId(uint8_t id) {
+    package_id_ = id;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    return &symbols_;
+  }
+
+  bool IsVerbose() override {
+    return verbose_;
+  }
+
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
+
+  int GetMinSdkVersion() override {
+    return min_sdk_version_;
+  }
+
+  void SetMinSdkVersion(int minSdk) {
+    min_sdk_version_ = minSdk;
+  }
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(LinkContext);
+
+  StdErrDiagnostics diagnostics_;
+  NameMangler name_mangler_;
+  std::string compilation_package_;
+  uint8_t package_id_ = 0x0;
+  SymbolTable symbols_;
+  bool verbose_ = false;
+  int min_sdk_version_ = 0;
+};
+
+static bool FlattenXml(xml::XmlResource* xml_res, const StringPiece& path,
+                       Maybe<size_t> max_sdk_level, bool keep_raw_values, IArchiveWriter* writer,
+                       IAaptContext* context) {
+  BigBuffer buffer(1024);
+  XmlFlattenerOptions options = {};
+  options.keep_raw_values = keep_raw_values;
+  options.max_sdk_level = max_sdk_level;
+  XmlFlattener flattener(&buffer, options);
+  if (!flattener.Consume(context, xml_res)) {
+    return false;
+  }
+
+  if (context->IsVerbose()) {
+    DiagMessage msg;
+    msg << "writing " << path << " to archive";
+    if (max_sdk_level) {
+      msg << " maxSdkLevel=" << max_sdk_level.value() << " keepRawValues=" << keep_raw_values;
+    }
+    context->GetDiagnostics()->Note(msg);
+  }
+
+  io::BigBufferInputStream input_stream(&buffer);
+  return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
+                                      ArchiveEntry::kCompress, writer);
+}
+
+static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
+                                                      size_t len, IDiagnostics* diag) {
+  pb::ResourceTable pb_table;
+  if (!pb_table.ParseFromArray(data, len)) {
+    diag->Error(DiagMessage(source) << "invalid compiled table");
+    return {};
+  }
+
+  std::unique_ptr<ResourceTable> table = DeserializeTableFromPb(pb_table, source, diag);
+  if (!table) {
+    return {};
+  }
+  return table;
+}
+
+/**
+ * Inflates an XML file from the source path.
+ */
+static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
+  std::ifstream fin(path, std::ifstream::binary);
+  if (!fin) {
+    diag->Error(DiagMessage(path) << strerror(errno));
+    return {};
+  }
+  return xml::Inflate(&fin, diag, Source(path));
+}
+
+struct ResourceFileFlattenerOptions {
+  bool no_auto_version = false;
+  bool no_version_vectors = false;
+  bool no_version_transitions = false;
+  bool no_xml_namespaces = false;
+  bool keep_raw_values = false;
+  bool do_not_compress_anything = false;
+  bool update_proguard_spec = false;
+  std::unordered_set<std::string> extensions_to_not_compress;
+};
+
+class ResourceFileFlattener {
+ public:
+  ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
+                        proguard::KeepSet* keep_set)
+      : options_(options), context_(context), keep_set_(keep_set) {
+  }
+
+  bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
+
+ private:
+  struct FileOperation {
+    ConfigDescription config;
+
+    // The entry this file came from.
+    const ResourceEntry* entry;
+
+    // The file to copy as-is.
+    io::IFile* file_to_copy;
+
+    // The XML to process and flatten.
+    std::unique_ptr<xml::XmlResource> xml_to_flatten;
+
+    // The destination to write this file to.
+    std::string dst_path;
+    bool skip_version = false;
+  };
+
+  uint32_t GetCompressionFlags(const StringPiece& str);
+
+  bool LinkAndVersionXmlFile(ResourceTable* table, FileOperation* file_op,
+                             std::queue<FileOperation>* out_file_op_queue);
+
+  ResourceFileFlattenerOptions options_;
+  IAaptContext* context_;
+  proguard::KeepSet* keep_set_;
+};
+
+uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
+  if (options_.do_not_compress_anything) {
+    return 0;
+  }
+
+  for (const std::string& extension : options_.extensions_to_not_compress) {
+    if (util::EndsWith(str, extension)) {
+      return 0;
+    }
+  }
+  return ArchiveEntry::kCompress;
+}
+
+static bool IsTransitionElement(const std::string& name) {
+  return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
+         name == "changeImageTransform" || name == "changeTransform" ||
+         name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
+         name == "changeScroll" || name == "transitionSet" || name == "transition" ||
+         name == "transitionManager";
+}
+
+bool ResourceFileFlattener::LinkAndVersionXmlFile(ResourceTable* table, FileOperation* file_op,
+                                                  std::queue<FileOperation>* out_file_op_queue) {
+  xml::XmlResource* doc = file_op->xml_to_flatten.get();
+  const Source& src = doc->file.source;
+
+  if (context_->IsVerbose()) {
+    context_->GetDiagnostics()->Note(DiagMessage() << "linking " << src.path);
+  }
+
+  XmlReferenceLinker xml_linker;
+  if (!xml_linker.Consume(context_, doc)) {
+    return false;
+  }
+
+  if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
+    return false;
+  }
+
+  if (options_.no_xml_namespaces) {
+    XmlNamespaceRemover namespace_remover;
+    if (!namespace_remover.Consume(context_, doc)) {
+      return false;
+    }
+  }
+
+  if (!options_.no_auto_version) {
+    if (options_.no_version_vectors) {
+      // Skip this if it is a vector or animated-vector.
+      xml::Element* el = xml::FindRootElement(doc);
+      if (el && el->namespace_uri.empty()) {
+        if (el->name == "vector" || el->name == "animated-vector") {
+          // We are NOT going to version this file.
+          file_op->skip_version = true;
+          return true;
+        }
+      }
+    }
+    if (options_.no_version_transitions) {
+      // Skip this if it is a transition resource.
+      xml::Element* el = xml::FindRootElement(doc);
+      if (el && el->namespace_uri.empty()) {
+        if (IsTransitionElement(el->name)) {
+          // We are NOT going to version this file.
+          file_op->skip_version = true;
+          return true;
+        }
+      }
+    }
+
+    const ConfigDescription& config = file_op->config;
+
+    // Find the first SDK level used that is higher than this defined config and
+    // not superseded by a lower or equal SDK level resource.
+    const int min_sdk_version = context_->GetMinSdkVersion();
+    for (int sdk_level : xml_linker.sdk_levels()) {
+      if (sdk_level > min_sdk_version && sdk_level > config.sdkVersion) {
+        if (!ShouldGenerateVersionedResource(file_op->entry, config, sdk_level)) {
+          // If we shouldn't generate a versioned resource, stop checking.
+          break;
+        }
+
+        ResourceFile versioned_file_desc = doc->file;
+        versioned_file_desc.config.sdkVersion = (uint16_t)sdk_level;
+
+        FileOperation new_file_op;
+        new_file_op.xml_to_flatten =
+            util::make_unique<xml::XmlResource>(versioned_file_desc, doc->root->Clone());
+        new_file_op.config = versioned_file_desc.config;
+        new_file_op.entry = file_op->entry;
+        new_file_op.dst_path =
+            ResourceUtils::BuildResourceFileName(versioned_file_desc, context_->GetNameMangler());
+
+        if (context_->IsVerbose()) {
+          context_->GetDiagnostics()->Note(DiagMessage(versioned_file_desc.source)
+                                           << "auto-versioning resource from config '" << config
+                                           << "' -> '" << versioned_file_desc.config << "'");
+        }
+
+        bool added = table->AddFileReferenceAllowMangled(
+            versioned_file_desc.name, versioned_file_desc.config, versioned_file_desc.source,
+            new_file_op.dst_path, nullptr, context_->GetDiagnostics());
+        if (!added) {
+          return false;
+        }
+
+        out_file_op_queue->push(std::move(new_file_op));
+        break;
+      }
+    }
+  }
+  return true;
+}
+
+/**
+ * Do not insert or remove any resources while executing in this function. It
+ * will
+ * corrupt the iteration order.
+ */
+bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
+  bool error = false;
+  std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
+
+  for (auto& pkg : table->packages) {
+    for (auto& type : pkg->types) {
+      // Sort by config and name, so that we get better locality in the zip
+      // file.
+      config_sorted_files.clear();
+      std::queue<FileOperation> file_operations;
+
+      // Populate the queue with all files in the ResourceTable.
+      for (auto& entry : type->entries) {
+        for (auto& config_value : entry->values) {
+          FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
+          if (!file_ref) {
+            continue;
+          }
+
+          io::IFile* file = file_ref->file;
+          if (!file) {
+            context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
+                                              << "file not found");
+            return false;
+          }
+
+          FileOperation file_op;
+          file_op.entry = entry.get();
+          file_op.dst_path = *file_ref->path;
+          file_op.config = config_value->config;
+
+          const StringPiece src_path = file->GetSource().path;
+          if (type->type != ResourceType::kRaw &&
+              (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
+            std::unique_ptr<io::IData> data = file->OpenAsData();
+            if (!data) {
+              context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
+                                                << "failed to open file");
+              return false;
+            }
+
+            file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
+                                                  context_->GetDiagnostics(), file->GetSource());
+
+            if (!file_op.xml_to_flatten) {
+              return false;
+            }
+
+            file_op.xml_to_flatten->file.config = config_value->config;
+            file_op.xml_to_flatten->file.source = file_ref->GetSource();
+            file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
+
+            // Enqueue the XML files to be processed.
+            file_operations.push(std::move(file_op));
+          } else {
+            file_op.file_to_copy = file;
+
+            // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
+            // else we end up copying the string in the std::make_pair() method,
+            // then creating a StringPiece from the copy, which would cause us
+            // to end up referencing garbage in the map.
+            const StringPiece entry_name(entry->name);
+            config_sorted_files[std::make_pair(config_value->config, entry_name)] =
+                std::move(file_op);
+          }
+        }
+      }
+
+      // Now process the XML queue
+      for (; !file_operations.empty(); file_operations.pop()) {
+        FileOperation& file_op = file_operations.front();
+
+        if (!LinkAndVersionXmlFile(table, &file_op, &file_operations)) {
+          error = true;
+          continue;
+        }
+
+        // NOTE(adamlesinski): Explicitly construct a StringPiece here, or else
+        // we end up copying the string in the std::make_pair() method, then
+        // creating a StringPiece from the copy, which would cause us to end up
+        // referencing garbage in the map.
+        const StringPiece entry_name(file_op.entry->name);
+        config_sorted_files[std::make_pair(file_op.config, entry_name)] = std::move(file_op);
+      }
+
+      if (error) {
+        return false;
+      }
+
+      // Now flatten the sorted values.
+      for (auto& map_entry : config_sorted_files) {
+        const ConfigDescription& config = map_entry.first.first;
+        const FileOperation& file_op = map_entry.second;
+
+        if (file_op.xml_to_flatten) {
+          Maybe<size_t> max_sdk_level;
+          if (!options_.no_auto_version && !file_op.skip_version) {
+            max_sdk_level = std::max<size_t>(std::max<size_t>(config.sdkVersion, 1u),
+                                             context_->GetMinSdkVersion());
+          }
+
+          bool result = FlattenXml(file_op.xml_to_flatten.get(), file_op.dst_path, max_sdk_level,
+                                   options_.keep_raw_values, archive_writer, context_);
+          if (!result) {
+            error = true;
+          }
+        } else {
+          bool result =
+              io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
+                                    GetCompressionFlags(file_op.dst_path), archive_writer);
+          if (!result) {
+            error = true;
+          }
+        }
+      }
+    }
+  }
+  return !error;
+}
+
+static bool WriteStableIdMapToPath(IDiagnostics* diag,
+                                   const std::unordered_map<ResourceName, ResourceId>& id_map,
+                                   const std::string& id_map_path) {
+  std::ofstream fout(id_map_path, std::ofstream::binary);
+  if (!fout) {
+    diag->Error(DiagMessage(id_map_path) << strerror(errno));
+    return false;
+  }
+
+  for (const auto& entry : id_map) {
+    const ResourceName& name = entry.first;
+    const ResourceId& id = entry.second;
+    fout << name << " = " << id << "\n";
+  }
+
+  if (!fout) {
+    diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
+                                         << android::base::SystemErrorCodeToString(errno));
+    return false;
+  }
+
+  return true;
+}
+
+static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
+                            std::unordered_map<ResourceName, ResourceId>* out_id_map) {
+  std::string content;
+  if (!android::base::ReadFileToString(path, &content)) {
+    diag->Error(DiagMessage(path) << "failed reading stable ID file");
+    return false;
+  }
+
+  out_id_map->clear();
+  size_t line_no = 0;
+  for (StringPiece line : util::Tokenize(content, '\n')) {
+    line_no++;
+    line = util::TrimWhitespace(line);
+    if (line.empty()) {
+      continue;
+    }
+
+    auto iter = std::find(line.begin(), line.end(), '=');
+    if (iter == line.end()) {
+      diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
+      return false;
+    }
+
+    ResourceNameRef name;
+    StringPiece res_name_str =
+        util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
+    if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
+      diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
+                                                     << "'");
+      return false;
+    }
+
+    const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
+    const size_t res_id_str_len = line.size() - res_id_start_idx;
+    StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
+
+    Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
+    if (!maybe_id) {
+      diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
+                                                     << "'");
+      return false;
+    }
+
+    (*out_id_map)[name.ToResourceName()] = maybe_id.value();
+  }
+  return true;
+}
+
+class LinkCommand {
+ public:
+  LinkCommand(LinkContext* context, const LinkOptions& options)
+      : options_(options),
+        context_(context),
+        final_table_(),
+        file_collection_(util::make_unique<io::FileCollection>()) {
+  }
+
+  /**
+   * Creates a SymbolTable that loads symbols from the various APKs and caches
+   * the results for faster lookup.
+   */
+  bool LoadSymbolsFromIncludePaths() {
+    std::unique_ptr<AssetManagerSymbolSource> asset_source =
+        util::make_unique<AssetManagerSymbolSource>();
+    for (const std::string& path : options_.include_paths) {
+      if (context_->IsVerbose()) {
+        context_->GetDiagnostics()->Note(DiagMessage(path) << "loading include path");
+      }
+
+      // First try to load the file as a static lib.
+      std::string error_str;
+      std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
+      if (include_static) {
+        if (options_.package_type != PackageType::kStaticLib) {
+          // Can't include static libraries when not building a static library (they have no IDs
+          // assigned).
+          context_->GetDiagnostics()->Error(
+              DiagMessage(path) << "can't include static library when not building a static lib");
+          return false;
+        }
+
+        // If we are using --no-static-lib-packages, we need to rename the
+        // package of this table to our compilation package.
+        if (options_.no_static_lib_packages) {
+          // Since package names can differ, and multiple packages can exist in a ResourceTable,
+          // we place the requirement that all static libraries are built with the package
+          // ID 0x7f. So if one is not found, this is an error.
+          if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
+            pkg->name = context_->GetCompilationPackage();
+          } else {
+            context_->GetDiagnostics()->Error(DiagMessage(path)
+                                              << "no package with ID 0x7f found in static library");
+            return false;
+          }
+        }
+
+        context_->GetExternalSymbols()->AppendSource(
+            util::make_unique<ResourceTableSymbolSource>(include_static.get()));
+
+        static_table_includes_.push_back(std::move(include_static));
+
+      } else if (!error_str.empty()) {
+        // We had an error with reading, so fail.
+        context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
+        return false;
+      }
+
+      if (!asset_source->AddAssetPath(path)) {
+        context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
+        return false;
+      }
+    }
+
+    // Capture the shared libraries so that the final resource table can be properly flattened
+    // with support for shared libraries.
+    for (auto& entry : asset_source->GetAssignedPackageIds()) {
+      if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
+        final_table_.included_packages_[entry.first] = entry.second;
+      }
+    }
+
+    context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
+    return true;
+  }
+
+  Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
+    // Make sure the first element is <manifest> with package attribute.
+    xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
+    if (manifest_el == nullptr) {
+      return {};
+    }
+
+    AppInfo app_info;
+
+    if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
+      diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
+      return {};
+    }
+
+    xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
+    if (!package_attr) {
+      diag->Error(DiagMessage(xml_res->file.source)
+                  << "<manifest> must have a 'package' attribute");
+      return {};
+    }
+    app_info.package = package_attr->value;
+
+    if (xml::Attribute* version_code_attr =
+            manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
+      Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
+      if (!maybe_code) {
+        diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                    << "invalid android:versionCode '" << version_code_attr->value << "'");
+        return {};
+      }
+      app_info.version_code = maybe_code.value();
+    }
+
+    if (xml::Attribute* revision_code_attr =
+            manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
+      Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
+      if (!maybe_code) {
+        diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                    << "invalid android:revisionCode '" << revision_code_attr->value << "'");
+        return {};
+      }
+      app_info.revision_code = maybe_code.value();
+    }
+
+    if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
+      if (!split_name_attr->value.empty()) {
+        app_info.split_name = split_name_attr->value;
+      }
+    }
+
+    if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
+      if (xml::Attribute* min_sdk =
+              uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
+        app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
+      }
+    }
+    return app_info;
+  }
+
+  /**
+   * Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
+   * Postcondition: ResourceTable has only one package left. All others are
+   * stripped, or there is an error and false is returned.
+   */
+  bool VerifyNoExternalPackages() {
+    auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
+      return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
+             pkg->id.value() != context_->GetPackageId();
+    };
+
+    bool error = false;
+    for (const auto& package : final_table_.packages) {
+      if (is_ext_package_func(package)) {
+        // We have a package that is not related to the one we're building!
+        for (const auto& type : package->types) {
+          for (const auto& entry : type->entries) {
+            ResourceNameRef res_name(package->name, type->type, entry->name);
+
+            for (const auto& config_value : entry->values) {
+              // Special case the occurrence of an ID that is being generated
+              // for the 'android' package. This is due to legacy reasons.
+              if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
+                context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
+                                                 << "generated id '" << res_name
+                                                 << "' for external package '" << package->name
+                                                 << "'");
+              } else {
+                context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
+                                                  << "defined resource '" << res_name
+                                                  << "' for external package '" << package->name
+                                                  << "'");
+                error = true;
+              }
+            }
+          }
+        }
+      }
+    }
+
+    auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
+                                       is_ext_package_func);
+    final_table_.packages.erase(new_end_iter, final_table_.packages.end());
+    return !error;
+  }
+
+  /**
+   * Returns true if no IDs have been set, false otherwise.
+   */
+  bool VerifyNoIdsSet() {
+    for (const auto& package : final_table_.packages) {
+      for (const auto& type : package->types) {
+        if (type->id) {
+          context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
+                                                          << StringPrintf("%02x", type->id.value())
+                                                          << " assigned");
+          return false;
+        }
+
+        for (const auto& entry : type->entries) {
+          if (entry->id) {
+            ResourceNameRef res_name(package->name, type->type, entry->name);
+            context_->GetDiagnostics()->Error(
+                DiagMessage() << "entry " << res_name << " has ID "
+                              << StringPrintf("%02x", entry->id.value()) << " assigned");
+            return false;
+          }
+        }
+      }
+    }
+    return true;
+  }
+
+  std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
+    if (options_.output_to_directory) {
+      return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
+    } else {
+      return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
+    }
+  }
+
+  bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
+    BigBuffer buffer(1024);
+    TableFlattener flattener(options_.table_flattener_options, &buffer);
+    if (!flattener.Consume(context_, table)) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
+      return false;
+    }
+
+    io::BigBufferInputStream input_stream(&buffer);
+    return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
+                                        ArchiveEntry::kAlign, writer);
+  }
+
+  bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
+    std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
+    return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
+  }
+
+  bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
+                     const StringPiece& out_package,
+                     const JavaClassGeneratorOptions& java_options) {
+    if (!options_.generate_java_class_path) {
+      return true;
+    }
+
+    std::string out_path = options_.generate_java_class_path.value();
+    file::AppendPath(&out_path, file::PackageToPath(out_package));
+    if (!file::mkdirs(out_path)) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
+                                                      << "'");
+      return false;
+    }
+
+    file::AppendPath(&out_path, "R.java");
+
+    std::ofstream fout(out_path, std::ofstream::binary);
+    if (!fout) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    JavaClassGenerator generator(context_, table, java_options);
+    if (!generator.Generate(package_name_to_generate, out_package, &fout)) {
+      context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
+      return false;
+    }
+
+    if (!fout) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+    }
+    return true;
+  }
+
+  bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
+    if (!options_.generate_java_class_path) {
+      return true;
+    }
+
+    std::unique_ptr<ClassDefinition> manifest_class =
+        GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
+
+    if (!manifest_class) {
+      // Something bad happened, but we already logged it, so exit.
+      return false;
+    }
+
+    if (manifest_class->empty()) {
+      // Empty Manifest class, no need to generate it.
+      return true;
+    }
+
+    // Add any JavaDoc annotations to the generated class.
+    for (const std::string& annotation : options_.javadoc_annotations) {
+      std::string proper_annotation = "@";
+      proper_annotation += annotation;
+      manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
+    }
+
+    const std::string& package_utf8 = context_->GetCompilationPackage();
+
+    std::string out_path = options_.generate_java_class_path.value();
+    file::AppendPath(&out_path, file::PackageToPath(package_utf8));
+
+    if (!file::mkdirs(out_path)) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
+                                                      << "'");
+      return false;
+    }
+
+    file::AppendPath(&out_path, "Manifest.java");
+
+    std::ofstream fout(out_path, std::ofstream::binary);
+    if (!fout) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+    return true;
+  }
+
+  bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
+    if (!out) {
+      return true;
+    }
+
+    const std::string& out_path = out.value();
+    std::ofstream fout(out_path, std::ofstream::binary);
+    if (!fout) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed to open '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+
+    proguard::WriteKeepSet(&fout, keep_set);
+    if (!fout) {
+      context_->GetDiagnostics()->Error(DiagMessage()
+                                        << "failed writing to '" << out_path
+                                        << "': " << android::base::SystemErrorCodeToString(errno));
+      return false;
+    }
+    return true;
+  }
+
+  std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
+                                                   std::string* out_error) {
+    std::unique_ptr<io::ZipFileCollection> collection =
+        io::ZipFileCollection::Create(input, out_error);
+    if (!collection) {
+      return {};
+    }
+    return LoadTablePbFromCollection(collection.get());
+  }
+
+  std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
+    io::IFile* file = collection->FindFile("resources.arsc.flat");
+    if (!file) {
+      return {};
+    }
+
+    std::unique_ptr<io::IData> data = file->OpenAsData();
+    return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
+                           context_->GetDiagnostics());
+  }
+
+  bool MergeStaticLibrary(const std::string& input, bool override) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
+    }
+
+    std::string error_str;
+    std::unique_ptr<io::ZipFileCollection> collection =
+        io::ZipFileCollection::Create(input, &error_str);
+    if (!collection) {
+      context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
+      return false;
+    }
+
+    std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
+    if (!table) {
+      context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
+      return false;
+    }
+
+    ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
+    if (!pkg) {
+      context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
+      return false;
+    }
+
+    bool result;
+    if (options_.no_static_lib_packages) {
+      // Merge all resources as if they were in the compilation package. This is
+      // the old behavior of aapt.
+
+      // Add the package to the set of --extra-packages so we emit an R.java for
+      // each library package.
+      if (!pkg->name.empty()) {
+        options_.extra_java_packages.insert(pkg->name);
+      }
+
+      pkg->name = "";
+      if (override) {
+        result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
+      } else {
+        result = table_merger_->Merge(Source(input), table.get(), collection.get());
+      }
+
+    } else {
+      // This is the proper way to merge libraries, where the package name is
+      // preserved and resource names are mangled.
+      result =
+          table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
+    }
+
+    if (!result) {
+      return false;
+    }
+
+    // Make sure to move the collection into the set of IFileCollections.
+    collections_.push_back(std::move(collection));
+    return true;
+  }
+
+  bool MergeResourceTable(io::IFile* file, bool override) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
+                                                     << file->GetSource());
+    }
+
+    std::unique_ptr<io::IData> data = file->OpenAsData();
+    if (!data) {
+      context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
+      return false;
+    }
+
+    std::unique_ptr<ResourceTable> table =
+        LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
+    if (!table) {
+      return false;
+    }
+
+    bool result = false;
+    if (override) {
+      result = table_merger_->MergeOverlay(file->GetSource(), table.get());
+    } else {
+      result = table_merger_->Merge(file->GetSource(), table.get());
+    }
+    return result;
+  }
+
+  bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
+                                                     << "' from compiled file "
+                                                     << file->GetSource());
+    }
+
+    bool result = false;
+    if (override) {
+      result = table_merger_->MergeFileOverlay(*file_desc, file);
+    } else {
+      result = table_merger_->MergeFile(*file_desc, file);
+    }
+
+    if (!result) {
+      return false;
+    }
+
+    // Add the exports of this file to the table.
+    for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
+      if (exported_symbol.name.package.empty()) {
+        exported_symbol.name.package = context_->GetCompilationPackage();
+      }
+
+      ResourceNameRef res_name = exported_symbol.name;
+
+      Maybe<ResourceName> mangled_name =
+          context_->GetNameMangler()->MangleName(exported_symbol.name);
+      if (mangled_name) {
+        res_name = mangled_name.value();
+      }
+
+      std::unique_ptr<Id> id = util::make_unique<Id>();
+      id->SetSource(file_desc->source.WithLine(exported_symbol.line));
+      bool result = final_table_.AddResourceAllowMangled(
+          res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
+          context_->GetDiagnostics());
+      if (!result) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Takes a path to load as a ZIP file and merges the files within into the
+   * master ResourceTable.
+   * If override is true, conflicting resources are allowed to override each
+   * other, in order of last seen.
+   *
+   * An io::IFileCollection is created from the ZIP file and added to the set of
+   * io::IFileCollections that are open.
+   */
+  bool MergeArchive(const std::string& input, bool override) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
+    }
+
+    std::string error_str;
+    std::unique_ptr<io::ZipFileCollection> collection =
+        io::ZipFileCollection::Create(input, &error_str);
+    if (!collection) {
+      context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
+      return false;
+    }
+
+    bool error = false;
+    for (auto iter = collection->Iterator(); iter->HasNext();) {
+      if (!MergeFile(iter->Next(), override)) {
+        error = true;
+      }
+    }
+
+    // Make sure to move the collection into the set of IFileCollections.
+    collections_.push_back(std::move(collection));
+    return !error;
+  }
+
+  /**
+   * Takes a path to load and merge into the master ResourceTable. If override
+   * is true,
+   * conflicting resources are allowed to override each other, in order of last
+   * seen.
+   *
+   * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
+   * as ZIP archive
+   * and the files within are merged individually.
+   *
+   * Otherwise the files is processed on its own.
+   */
+  bool MergePath(const std::string& path, bool override) {
+    if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
+        util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
+      return MergeArchive(path, override);
+    } else if (util::EndsWith(path, ".apk")) {
+      return MergeStaticLibrary(path, override);
+    }
+
+    io::IFile* file = file_collection_->InsertFile(path);
+    return MergeFile(file, override);
+  }
+
+  /**
+   * Takes a file to load and merge into the master ResourceTable. If override
+   * is true,
+   * conflicting resources are allowed to override each other, in order of last
+   * seen.
+   *
+   * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
+   * merged into the
+   * master ResourceTable. If the file ends with .flat, then it is treated like
+   * a compiled file
+   * and the header data is read and merged into the final ResourceTable.
+   *
+   * All other file types are ignored. This is because these files could be
+   * coming from a zip,
+   * where we could have other files like classes.dex.
+   */
+  bool MergeFile(io::IFile* file, bool override) {
+    const Source& src = file->GetSource();
+    if (util::EndsWith(src.path, ".arsc.flat")) {
+      return MergeResourceTable(file, override);
+
+    } else if (util::EndsWith(src.path, ".flat")) {
+      // Try opening the file and looking for an Export header.
+      std::unique_ptr<io::IData> data = file->OpenAsData();
+      if (!data) {
+        context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
+        return false;
+      }
+
+      CompiledFileInputStream input_stream(data->data(), data->size());
+      uint32_t num_files = 0;
+      if (!input_stream.ReadLittleEndian32(&num_files)) {
+        context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
+        return false;
+      }
+
+      for (uint32_t i = 0; i < num_files; i++) {
+        pb::CompiledFile compiled_file;
+        if (!input_stream.ReadCompiledFile(&compiled_file)) {
+          context_->GetDiagnostics()->Error(DiagMessage(src)
+                                            << "failed to read compiled file header");
+          return false;
+        }
+
+        uint64_t offset, len;
+        if (!input_stream.ReadDataMetaData(&offset, &len)) {
+          context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
+          return false;
+        }
+
+        std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
+            compiled_file, file->GetSource(), context_->GetDiagnostics());
+        if (!resource_file) {
+          return false;
+        }
+
+        if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
+                               override)) {
+          return false;
+        }
+      }
+      return true;
+    } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
+      // Since AAPT compiles these file types and appends .flat to them, seeing
+      // their raw extensions is a sign that they weren't compiled.
+      const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
+      context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
+                                                         << " file passed as argument. Must be "
+                                                            "compiled first into .flat file.");
+      return false;
+    }
+
+    // Ignore non .flat files. This could be classes.dex or something else that
+    // happens
+    // to be in an archive.
+    return true;
+  }
+
+  bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
+    std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
+    for (const std::string& assets_dir : options_.assets_dirs) {
+      Maybe<std::vector<std::string>> files =
+          file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
+      if (!files) {
+        return false;
+      }
+
+      for (const std::string& file : files.value()) {
+        std::string full_key = "assets/" + file;
+        std::string full_path = assets_dir;
+        file::AppendPath(&full_path, file);
+
+        auto iter = merged_assets.find(full_key);
+        if (iter == merged_assets.end()) {
+          merged_assets.emplace(std::move(full_key),
+                                util::make_unique<io::RegularFile>(Source(std::move(full_path))));
+        } else if (context_->IsVerbose()) {
+          context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
+                                           << "asset file overrides '" << full_path << "'");
+        }
+      }
+    }
+
+    for (auto& entry : merged_assets) {
+      uint32_t compression_flags = ArchiveEntry::kCompress;
+      std::string extension = file::GetExtension(entry.first).to_string();
+      if (options_.extensions_to_not_compress.count(extension) > 0) {
+        compression_flags = 0u;
+      }
+
+      if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
+                                 writer)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
+   * the ResourceTable to the IArchiveWriter.
+   */
+  bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
+                ResourceTable* table) {
+    const bool keep_raw_values = options_.package_type == PackageType::kStaticLib;
+    bool result =
+        FlattenXml(manifest, "AndroidManifest.xml", {}, keep_raw_values, writer, context_);
+    if (!result) {
+      return false;
+    }
+
+    ResourceFileFlattenerOptions file_flattener_options;
+    file_flattener_options.keep_raw_values = keep_raw_values;
+    file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
+    file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
+    file_flattener_options.no_auto_version = options_.no_auto_version;
+    file_flattener_options.no_version_vectors = options_.no_version_vectors;
+    file_flattener_options.no_version_transitions = options_.no_version_transitions;
+    file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
+    file_flattener_options.update_proguard_spec =
+        static_cast<bool>(options_.generate_proguard_rules_path);
+
+    ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
+
+    if (!file_flattener.Flatten(table, writer)) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
+      return false;
+    }
+
+    if (options_.package_type == PackageType::kStaticLib) {
+      if (!FlattenTableToPb(table, writer)) {
+        return false;
+      }
+    } else {
+      if (!FlattenTable(table, writer)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
+        return false;
+      }
+    }
+    return true;
+  }
+
+  int Run(const std::vector<std::string>& input_files) {
+    // Load the AndroidManifest.xml
+    std::unique_ptr<xml::XmlResource> manifest_xml =
+        LoadXml(options_.manifest_path, context_->GetDiagnostics());
+    if (!manifest_xml) {
+      return 1;
+    }
+
+    // First extract the Package name without modifying it (via --rename-manifest-package).
+    if (Maybe<AppInfo> maybe_app_info =
+            ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
+      const AppInfo& app_info = maybe_app_info.value();
+      context_->SetCompilationPackage(app_info.package);
+    }
+
+    ManifestFixer manifest_fixer(options_.manifest_fixer_options);
+    if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
+      return 1;
+    }
+
+    Maybe<AppInfo> maybe_app_info =
+        ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
+    if (!maybe_app_info) {
+      return 1;
+    }
+
+    const AppInfo& app_info = maybe_app_info.value();
+    context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
+
+    context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
+
+    // Override the package ID when it is "android".
+    if (context_->GetCompilationPackage() == "android") {
+      context_->SetPackageId(0x01);
+
+      // Verify we're building a regular app.
+      if (options_.package_type != PackageType::kApp) {
+        context_->GetDiagnostics()->Error(
+            DiagMessage() << "package 'android' can only be built as a regular app");
+        return 1;
+      }
+    }
+
+    if (!LoadSymbolsFromIncludePaths()) {
+      return 1;
+    }
+
+    TableMergerOptions table_merger_options;
+    table_merger_options.auto_add_overlay = options_.auto_add_overlay;
+    table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
+
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage()
+                                       << StringPrintf("linking package '%s' using package ID %02x",
+                                                       context_->GetCompilationPackage().data(),
+                                                       context_->GetPackageId()));
+    }
+
+    for (const std::string& input : input_files) {
+      if (!MergePath(input, false)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
+        return 1;
+      }
+    }
+
+    for (const std::string& input : options_.overlay_files) {
+      if (!MergePath(input, true)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
+        return 1;
+      }
+    }
+
+    if (!VerifyNoExternalPackages()) {
+      return 1;
+    }
+
+    if (options_.package_type != PackageType::kStaticLib) {
+      PrivateAttributeMover mover;
+      if (!mover.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
+        return 1;
+      }
+
+      // Assign IDs if we are building a regular app.
+      IdAssigner id_assigner(&options_.stable_id_map);
+      if (!id_assigner.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
+        return 1;
+      }
+
+      // Now grab each ID and emit it as a file.
+      if (options_.resource_id_map_path) {
+        for (auto& package : final_table_.packages) {
+          for (auto& type : package->types) {
+            for (auto& entry : type->entries) {
+              ResourceName name(package->name, type->type, entry->name);
+              // The IDs are guaranteed to exist.
+              options_.stable_id_map[std::move(name)] =
+                  ResourceId(package->id.value(), type->id.value(), entry->id.value());
+            }
+          }
+        }
+
+        if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
+                                    options_.resource_id_map_path.value())) {
+          return 1;
+        }
+      }
+    } else {
+      // Static libs are merged with other apps, and ID collisions are bad, so
+      // verify that
+      // no IDs have been set.
+      if (!VerifyNoIdsSet()) {
+        return 1;
+      }
+    }
+
+    // Add the names to mangle based on our source merge earlier.
+    context_->SetNameManglerPolicy(
+        NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
+
+    // Add our table to the symbol table.
+    context_->GetExternalSymbols()->PrependSource(
+        util::make_unique<ResourceTableSymbolSource>(&final_table_));
+
+    ReferenceLinker linker;
+    if (!linker.Consume(context_, &final_table_)) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
+      return 1;
+    }
+
+    if (options_.package_type == PackageType::kStaticLib) {
+      if (!options_.products.empty()) {
+        context_->GetDiagnostics()->Warn(DiagMessage()
+                                         << "can't select products when building static library");
+      }
+    } else {
+      ProductFilter product_filter(options_.products);
+      if (!product_filter.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
+        return 1;
+      }
+    }
+
+    if (!options_.no_auto_version) {
+      AutoVersioner versioner;
+      if (!versioner.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
+        return 1;
+      }
+    }
+
+    if (options_.package_type != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
+      if (context_->IsVerbose()) {
+        context_->GetDiagnostics()->Note(DiagMessage()
+                                         << "collapsing resource versions for minimum SDK "
+                                         << context_->GetMinSdkVersion());
+      }
+
+      VersionCollapser collapser;
+      if (!collapser.Consume(context_, &final_table_)) {
+        return 1;
+      }
+    }
+
+    if (!options_.no_resource_deduping) {
+      ResourceDeduper deduper;
+      if (!deduper.Consume(context_, &final_table_)) {
+        context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
+        return 1;
+      }
+    }
+
+    proguard::KeepSet proguard_keep_set;
+    proguard::KeepSet proguard_main_dex_keep_set;
+
+    if (options_.package_type == PackageType::kStaticLib) {
+      if (options_.table_splitter_options.config_filter != nullptr ||
+          !options_.table_splitter_options.preferred_densities.empty()) {
+        context_->GetDiagnostics()->Warn(DiagMessage()
+                                         << "can't strip resources when building static library");
+      }
+    } else {
+      // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
+      // equal to the minSdk.
+      options_.split_constraints =
+          AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
+
+      TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
+      if (!table_splitter.VerifySplitConstraints(context_)) {
+        return 1;
+      }
+      table_splitter.SplitTable(&final_table_);
+
+      // Now we need to write out the Split APKs.
+      auto path_iter = options_.split_paths.begin();
+      auto split_constraints_iter = options_.split_constraints.begin();
+      for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
+        if (context_->IsVerbose()) {
+          context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
+                                           << "generating split with configurations '"
+                                           << util::Joiner(split_constraints_iter->configs, ", ")
+                                           << "'");
+        }
+
+        std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
+        if (!archive_writer) {
+          context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
+          return 1;
+        }
+
+        // Generate an AndroidManifest.xml for each split.
+        std::unique_ptr<xml::XmlResource> split_manifest =
+            GenerateSplitManifest(app_info, *split_constraints_iter);
+
+        XmlReferenceLinker linker;
+        if (!linker.Consume(context_, split_manifest.get())) {
+          context_->GetDiagnostics()->Error(DiagMessage()
+                                            << "failed to create Split AndroidManifest.xml");
+          return 1;
+        }
+
+        if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
+                      split_table.get())) {
+          return 1;
+        }
+
+        ++path_iter;
+        ++split_constraints_iter;
+      }
+    }
+
+    // Start writing the base APK.
+    std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
+    if (!archive_writer) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
+      return 1;
+    }
+
+    bool error = false;
+    {
+      // AndroidManifest.xml has no resource name, but the CallSite is built
+      // from the name
+      // (aka, which package the AndroidManifest.xml is coming from).
+      // So we give it a package name so it can see local resources.
+      manifest_xml->file.name.package = context_->GetCompilationPackage();
+
+      XmlReferenceLinker manifest_linker;
+      if (manifest_linker.Consume(context_, manifest_xml.get())) {
+        if (options_.generate_proguard_rules_path &&
+            !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
+                                                       manifest_xml.get(), &proguard_keep_set)) {
+          error = true;
+        }
+
+        if (options_.generate_main_dex_proguard_rules_path &&
+            !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
+                                                       manifest_xml.get(),
+                                                       &proguard_main_dex_keep_set, true)) {
+          error = true;
+        }
+
+        if (options_.generate_java_class_path) {
+          if (!WriteManifestJavaFile(manifest_xml.get())) {
+            error = true;
+          }
+        }
+
+        if (options_.no_xml_namespaces) {
+          // PackageParser will fail if URIs are removed from
+          // AndroidManifest.xml.
+          XmlNamespaceRemover namespace_remover(true /* keepUris */);
+          if (!namespace_remover.Consume(context_, manifest_xml.get())) {
+            error = true;
+          }
+        }
+      } else {
+        error = true;
+      }
+    }
+
+    if (error) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
+      return 1;
+    }
+
+    if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
+      return 1;
+    }
+
+    if (!CopyAssetsDirsToApk(archive_writer.get())) {
+      return 1;
+    }
+
+    if (options_.generate_java_class_path) {
+      // The set of packages whose R class to call in the main classes
+      // onResourcesLoaded callback.
+      std::vector<std::string> packages_to_callback;
+
+      JavaClassGeneratorOptions template_options;
+      template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
+      template_options.javadoc_annotations = options_.javadoc_annotations;
+
+      if (options_.package_type == PackageType::kStaticLib || options_.generate_non_final_ids) {
+        template_options.use_final = false;
+      }
+
+      if (options_.package_type == PackageType::kSharedLib) {
+        template_options.use_final = false;
+        template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
+      }
+
+      const StringPiece actual_package = context_->GetCompilationPackage();
+      StringPiece output_package = context_->GetCompilationPackage();
+      if (options_.custom_java_package) {
+        // Override the output java package to the custom one.
+        output_package = options_.custom_java_package.value();
+      }
+
+      // Generate the private symbols if required.
+      if (options_.private_symbols) {
+        packages_to_callback.push_back(options_.private_symbols.value());
+
+        // If we defined a private symbols package, we only emit Public symbols
+        // to the original package, and private and public symbols to the
+        // private package.
+        JavaClassGeneratorOptions options = template_options;
+        options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
+        if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
+                           options)) {
+          return 1;
+        }
+      }
+
+      // Generate all the symbols for all extra packages.
+      for (const std::string& extra_package : options_.extra_java_packages) {
+        packages_to_callback.push_back(extra_package);
+
+        JavaClassGeneratorOptions options = template_options;
+        options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
+        if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
+          return 1;
+        }
+      }
+
+      // Generate the main public R class.
+      JavaClassGeneratorOptions options = template_options;
+
+      // Only generate public symbols if we have a private package.
+      if (options_.private_symbols) {
+        options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
+      }
+
+      if (options.rewrite_callback_options) {
+        options.rewrite_callback_options.value().packages_to_callback =
+            std::move(packages_to_callback);
+      }
+
+      if (!WriteJavaFile(&final_table_, actual_package, output_package, options)) {
+        return 1;
+      }
+    }
+
+    if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
+      return 1;
+    }
+
+    if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
+                           proguard_main_dex_keep_set)) {
+      return 1;
+    }
+    return 0;
+  }
+
+ private:
+  LinkOptions options_;
+  LinkContext* context_;
+  ResourceTable final_table_;
+
+  std::unique_ptr<TableMerger> table_merger_;
+
+  // A pointer to the FileCollection representing the filesystem (not archives).
+  std::unique_ptr<io::FileCollection> file_collection_;
+
+  // A vector of IFileCollections. This is mainly here to keep ownership of the
+  // collections.
+  std::vector<std::unique_ptr<io::IFileCollection>> collections_;
+
+  // A vector of ResourceTables. This is here to retain ownership, so that the
+  // SymbolTable can use these.
+  std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
+
+  // The set of shared libraries being used, mapping their assigned package ID to package name.
+  std::map<size_t, std::string> shared_libs_;
+};
+
+int Link(const std::vector<StringPiece>& args) {
+  LinkContext context;
+  LinkOptions options;
+  std::vector<std::string> overlay_arg_list;
+  std::vector<std::string> extra_java_packages;
+  Maybe<std::string> package_id;
+  std::vector<std::string> configs;
+  Maybe<std::string> preferred_density;
+  Maybe<std::string> product_list;
+  bool legacy_x_flag = false;
+  bool require_localization = false;
+  bool verbose = false;
+  bool shared_lib = false;
+  bool static_lib = false;
+  Maybe<std::string> stable_id_file_path;
+  std::vector<std::string> split_args;
+  Flags flags =
+      Flags()
+          .RequiredFlag("-o", "Output path.", &options.output_path)
+          .RequiredFlag("--manifest", "Path to the Android manifest to build.",
+                        &options.manifest_path)
+          .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
+          .OptionalFlagList("-A",
+                            "An assets directory to include in the APK. These are unprocessed.",
+                            &options.assets_dirs)
+          .OptionalFlagList("-R",
+                            "Compilation unit to link, using `overlay` semantics.\n"
+                            "The last conflicting resource given takes precedence.",
+                            &overlay_arg_list)
+          .OptionalFlag("--package-id",
+                        "Specify the package ID to use for this app. Must be greater or equal to\n"
+                        "0x7f and can't be used with --static-lib or --shared-lib.",
+                        &package_id)
+          .OptionalFlag("--java", "Directory in which to generate R.java.",
+                        &options.generate_java_class_path)
+          .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
+                        &options.generate_proguard_rules_path)
+          .OptionalFlag("--proguard-main-dex",
+                        "Output file for generated Proguard rules for the main dex.",
+                        &options.generate_main_dex_proguard_rules_path)
+          .OptionalSwitch("--no-auto-version",
+                          "Disables automatic style and layout SDK versioning.",
+                          &options.no_auto_version)
+          .OptionalSwitch("--no-version-vectors",
+                          "Disables automatic versioning of vector drawables. Use this only\n"
+                          "when building with vector drawable support library.",
+                          &options.no_version_vectors)
+          .OptionalSwitch("--no-version-transitions",
+                          "Disables automatic versioning of transition resources. Use this only\n"
+                          "when building with transition support library.",
+                          &options.no_version_transitions)
+          .OptionalSwitch("--no-resource-deduping",
+                          "Disables automatic deduping of resources with\n"
+                          "identical values across compatible configurations.",
+                          &options.no_resource_deduping)
+          .OptionalSwitch("--enable-sparse-encoding",
+                          "Enables encoding sparse entries using a binary search tree.\n"
+                          "This decreases APK size at the cost of resource retrieval performance.",
+                          &options.table_flattener_options.use_sparse_entries)
+          .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
+                          &legacy_x_flag)
+          .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
+                          &require_localization)
+          .OptionalFlagList("-c",
+                        "Comma separated list of configurations to include. The default\n"
+                        "is all configurations.",
+                        &configs)
+          .OptionalFlag("--preferred-density",
+                        "Selects the closest matching density and strips out all others.",
+                        &preferred_density)
+          .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
+          .OptionalSwitch("--output-to-dir",
+                          "Outputs the APK contents to a directory specified by -o.",
+                          &options.output_to_directory)
+          .OptionalSwitch("--no-xml-namespaces",
+                          "Removes XML namespace prefix and URI information from\n"
+                          "AndroidManifest.xml and XML binaries in res/*.",
+                          &options.no_xml_namespaces)
+          .OptionalFlag("--min-sdk-version",
+                        "Default minimum SDK version to use for AndroidManifest.xml.",
+                        &options.manifest_fixer_options.min_sdk_version_default)
+          .OptionalFlag("--target-sdk-version",
+                        "Default target SDK version to use for AndroidManifest.xml.",
+                        &options.manifest_fixer_options.target_sdk_version_default)
+          .OptionalFlag("--version-code",
+                        "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
+                        "present.",
+                        &options.manifest_fixer_options.version_code_default)
+          .OptionalFlag("--version-name",
+                        "Version name to inject into the AndroidManifest.xml if none is present.",
+                        &options.manifest_fixer_options.version_name_default)
+          .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
+                          &shared_lib)
+          .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
+          .OptionalSwitch("--no-static-lib-packages",
+                          "Merge all library resources under the app's package.",
+                          &options.no_static_lib_packages)
+          .OptionalSwitch("--non-final-ids",
+                          "Generates R.java without the final modifier. This is implied when\n"
+                          "--static-lib is specified.",
+                          &options.generate_non_final_ids)
+          .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
+                        &stable_id_file_path)
+          .OptionalFlag("--emit-ids",
+                        "Emit a file at the given path with a list of name to ID mappings,\n"
+                        "suitable for use with --stable-ids.",
+                        &options.resource_id_map_path)
+          .OptionalFlag("--private-symbols",
+                        "Package name to use when generating R.java for private symbols.\n"
+                        "If not specified, public and private symbols will use the application's\n"
+                        "package name.",
+                        &options.private_symbols)
+          .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
+                        &options.custom_java_package)
+          .OptionalFlagList("--extra-packages",
+                            "Generate the same R.java but with different package names.",
+                            &extra_java_packages)
+          .OptionalFlagList("--add-javadoc-annotation",
+                            "Adds a JavaDoc annotation to all generated Java classes.",
+                            &options.javadoc_annotations)
+          .OptionalSwitch("--auto-add-overlay",
+                          "Allows the addition of new resources in overlays without\n"
+                          "<add-resource> tags.",
+                          &options.auto_add_overlay)
+          .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
+                        &options.manifest_fixer_options.rename_manifest_package)
+          .OptionalFlag("--rename-instrumentation-target-package",
+                        "Changes the name of the target package for instrumentation. Most useful\n"
+                        "when used in conjunction with --rename-manifest-package.",
+                        &options.manifest_fixer_options.rename_instrumentation_target_package)
+          .OptionalFlagList("-0", "File extensions not to compress.",
+                            &options.extensions_to_not_compress)
+          .OptionalFlagList("--split",
+                            "Split resources matching a set of configs out to a Split APK.\n"
+                            "Syntax: path/to/output.apk:<config>[,<config>[...]].",
+                            &split_args)
+          .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
+
+  if (!flags.Parse("aapt2 link", args, &std::cerr)) {
+    return 1;
+  }
+
+  // Expand all argument-files passed into the command line. These start with '@'.
+  std::vector<std::string> arg_list;
+  for (const std::string& arg : flags.GetArgs()) {
+    if (util::StartsWith(arg, "@")) {
+      const std::string path = arg.substr(1, arg.size() - 1);
+      std::string error;
+      if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
+        context.GetDiagnostics()->Error(DiagMessage(path) << error);
+        return 1;
+      }
+    } else {
+      arg_list.push_back(arg);
+    }
+  }
+
+  // Expand all argument-files passed to -R.
+  for (const std::string& arg : overlay_arg_list) {
+    if (util::StartsWith(arg, "@")) {
+      const std::string path = arg.substr(1, arg.size() - 1);
+      std::string error;
+      if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
+        context.GetDiagnostics()->Error(DiagMessage(path) << error);
+        return 1;
+      }
+    } else {
+      options.overlay_files.push_back(arg);
+    }
+  }
+
+  if (verbose) {
+    context.SetVerbose(verbose);
+  }
+
+  if (shared_lib && static_lib) {
+    context.GetDiagnostics()->Error(DiagMessage()
+                                    << "only one of --shared-lib and --static-lib can be defined");
+    return 1;
+  }
+
+  if (shared_lib) {
+    options.package_type = PackageType::kSharedLib;
+    context.SetPackageId(0x00);
+  } else if (static_lib) {
+    options.package_type = PackageType::kStaticLib;
+    context.SetPackageId(kAppPackageId);
+  } else {
+    options.package_type = PackageType::kApp;
+    context.SetPackageId(kAppPackageId);
+  }
+
+  if (package_id) {
+    if (options.package_type != PackageType::kApp) {
+      context.GetDiagnostics()->Error(
+          DiagMessage() << "can't specify --package-id when not building a regular app");
+      return 1;
+    }
+
+    const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
+    if (!maybe_package_id_int) {
+      context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
+                                                    << "' is not a valid integer");
+      return 1;
+    }
+
+    const uint32_t package_id_int = maybe_package_id_int.value();
+    if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
+      context.GetDiagnostics()->Error(
+          DiagMessage() << StringPrintf(
+              "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
+      return 1;
+    }
+    context.SetPackageId(static_cast<uint8_t>(package_id_int));
+  }
+
+  // Populate the set of extra packages for which to generate R.java.
+  for (std::string& extra_package : extra_java_packages) {
+    // A given package can actually be a colon separated list of packages.
+    for (StringPiece package : util::Split(extra_package, ':')) {
+      options.extra_java_packages.insert(package.to_string());
+    }
+  }
+
+  if (product_list) {
+    for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
+      if (product != "" && product != "default") {
+        options.products.insert(product.to_string());
+      }
+    }
+  }
+
+  std::unique_ptr<IConfigFilter> filter;
+  if (!configs.empty()) {
+    filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
+    if (filter == nullptr) {
+      return 1;
+    }
+    options.table_splitter_options.config_filter = filter.get();
+  }
+
+  if (preferred_density) {
+    Maybe<uint16_t> density =
+        ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
+    if (!density) {
+      return 1;
+    }
+    options.table_splitter_options.preferred_densities.push_back(density.value());
+  }
+
+  // Parse the split parameters.
+  for (const std::string& split_arg : split_args) {
+    options.split_paths.push_back({});
+    options.split_constraints.push_back({});
+    if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
+                             &options.split_constraints.back())) {
+      return 1;
+    }
+  }
+
+  if (options.package_type != PackageType::kStaticLib && stable_id_file_path) {
+    if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
+                         &options.stable_id_map)) {
+      return 1;
+    }
+  }
+
+  // Populate some default no-compress extensions that are already compressed.
+  options.extensions_to_not_compress.insert(
+      {".jpg",   ".jpeg", ".png",  ".gif", ".wav",  ".mp2",  ".mp3",  ".ogg",
+       ".aac",   ".mpg",  ".mpeg", ".mid", ".midi", ".smf",  ".jet",  ".rtttl",
+       ".imy",   ".xmf",  ".mp4",  ".m4a", ".m4v",  ".3gp",  ".3gpp", ".3g2",
+       ".3gpp2", ".amr",  ".awb",  ".wma", ".wmv",  ".webm", ".mkv"});
+
+  // Turn off auto versioning for static-libs.
+  if (options.package_type == PackageType::kStaticLib) {
+    options.no_auto_version = true;
+    options.no_version_vectors = true;
+    options.no_version_transitions = true;
+  }
+
+  LinkCommand cmd(&context, options);
+  return cmd.Run(arg_list);
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Optimize.cpp b/tools/aapt2/cmd/Optimize.cpp
new file mode 100644
index 0000000..8f8e0c8
--- /dev/null
+++ b/tools/aapt2/cmd/Optimize.cpp
@@ -0,0 +1,369 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <memory>
+#include <vector>
+
+#include "androidfw/StringPiece.h"
+
+#include "Diagnostics.h"
+#include "Flags.h"
+#include "LoadedApk.h"
+#include "ResourceUtils.h"
+#include "SdkConstants.h"
+#include "ValueVisitor.h"
+#include "cmd/Util.h"
+#include "flatten/TableFlattener.h"
+#include "flatten/XmlFlattener.h"
+#include "io/BigBufferInputStream.h"
+#include "io/Util.h"
+#include "optimize/ResourceDeduper.h"
+#include "optimize/VersionCollapser.h"
+#include "split/TableSplitter.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+struct OptimizeOptions {
+  // Path to the output APK.
+  std::string output_path;
+
+  // Details of the app extracted from the AndroidManifest.xml
+  AppInfo app_info;
+
+  // Split APK options.
+  TableSplitterOptions table_splitter_options;
+
+  // List of output split paths. These are in the same order as `split_constraints`.
+  std::vector<std::string> split_paths;
+
+  // List of SplitConstraints governing what resources go into each split. Ordered by `split_paths`.
+  std::vector<SplitConstraints> split_constraints;
+
+  TableFlattenerOptions table_flattener_options;
+};
+
+class OptimizeContext : public IAaptContext {
+ public:
+  IDiagnostics* GetDiagnostics() override {
+    return &diagnostics_;
+  }
+
+  NameMangler* GetNameMangler() override {
+    UNIMPLEMENTED(FATAL);
+    return nullptr;
+  }
+
+  const std::string& GetCompilationPackage() override {
+    static std::string empty;
+    return empty;
+  }
+
+  uint8_t GetPackageId() override {
+    return 0;
+  }
+
+  SymbolTable* GetExternalSymbols() override {
+    UNIMPLEMENTED(FATAL);
+    return nullptr;
+  }
+
+  bool IsVerbose() override {
+    return verbose_;
+  }
+
+  void SetVerbose(bool val) {
+    verbose_ = val;
+  }
+
+  void SetMinSdkVersion(int sdk_version) {
+    sdk_version_ = sdk_version;
+  }
+
+  int GetMinSdkVersion() override {
+    return sdk_version_;
+  }
+
+ private:
+  StdErrDiagnostics diagnostics_;
+  bool verbose_ = false;
+  int sdk_version_ = 0;
+};
+
+class OptimizeCommand {
+ public:
+  OptimizeCommand(OptimizeContext* context, const OptimizeOptions& options)
+      : options_(options), context_(context) {
+  }
+
+  int Run(std::unique_ptr<LoadedApk> apk) {
+    if (context_->IsVerbose()) {
+      context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
+    }
+
+    VersionCollapser collapser;
+    if (!collapser.Consume(context_, apk->GetResourceTable())) {
+      return 1;
+    }
+
+    ResourceDeduper deduper;
+    if (!deduper.Consume(context_, apk->GetResourceTable())) {
+      context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
+      return 1;
+    }
+
+    // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
+    // equal to the minSdk.
+    options_.split_constraints =
+        AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
+
+    // Stripping the APK using the TableSplitter. The resource table is modified in place in the
+    // LoadedApk.
+    TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
+    if (!splitter.VerifySplitConstraints(context_)) {
+      return 1;
+    }
+    splitter.SplitTable(apk->GetResourceTable());
+
+    auto path_iter = options_.split_paths.begin();
+    auto split_constraints_iter = options_.split_constraints.begin();
+    for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
+      if (context_->IsVerbose()) {
+        context_->GetDiagnostics()->Note(
+            DiagMessage(*path_iter) << "generating split with configurations '"
+                                    << util::Joiner(split_constraints_iter->configs, ", ") << "'");
+      }
+
+      // Generate an AndroidManifest.xml for each split.
+      std::unique_ptr<xml::XmlResource> split_manifest =
+          GenerateSplitManifest(options_.app_info, *split_constraints_iter);
+      std::unique_ptr<IArchiveWriter> split_writer =
+          CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
+      if (!split_writer) {
+        return 1;
+      }
+
+      if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
+        return 1;
+      }
+
+      ++path_iter;
+      ++split_constraints_iter;
+    }
+
+    std::unique_ptr<IArchiveWriter> writer =
+        CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path);
+    if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
+      return 1;
+    }
+
+    return 0;
+  }
+
+ private:
+  bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
+    BigBuffer manifest_buffer(4096);
+    XmlFlattener xml_flattener(&manifest_buffer, {});
+    if (!xml_flattener.Consume(context_, manifest)) {
+      return false;
+    }
+
+    io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
+    if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
+                                      ArchiveEntry::kCompress, writer)) {
+      return false;
+    }
+
+    std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
+    for (auto& pkg : table->packages) {
+      for (auto& type : pkg->types) {
+        // Sort by config and name, so that we get better locality in the zip file.
+        config_sorted_files.clear();
+
+        for (auto& entry : type->entries) {
+          for (auto& config_value : entry->values) {
+            FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
+            if (file_ref == nullptr) {
+              continue;
+            }
+
+            if (file_ref->file == nullptr) {
+              ResourceNameRef name(pkg->name, type->type, entry->name);
+              context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
+                                                << "file for resource " << name << " with config '"
+                                                << config_value->config << "' not found");
+              return false;
+            }
+
+            const StringPiece entry_name = entry->name;
+            config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
+          }
+        }
+
+        for (auto& entry : config_sorted_files) {
+          FileReference* file_ref = entry.second;
+          uint32_t compression_flags =
+              file_ref->file->WasCompressed() ? ArchiveEntry::kCompress : 0u;
+          if (!io::CopyFileToArchive(context_, file_ref->file, *file_ref->path, compression_flags,
+                                     writer)) {
+            return false;
+          }
+        }
+      }
+    }
+
+    BigBuffer table_buffer(4096);
+    TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
+    if (!table_flattener.Consume(context_, table)) {
+      return false;
+    }
+
+    io::BigBufferInputStream table_buffer_in(&table_buffer);
+    if (!io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
+                                      ArchiveEntry::kAlign, writer)) {
+      return false;
+    }
+    return true;
+  }
+
+  OptimizeOptions options_;
+  OptimizeContext* context_;
+};
+
+bool ExtractAppDataFromManifest(OptimizeContext* context, LoadedApk* apk,
+                                OptimizeOptions* out_options) {
+  io::IFile* manifest_file = apk->GetFileCollection()->FindFile("AndroidManifest.xml");
+  if (manifest_file == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage(apk->GetSource())
+                                     << "missing AndroidManifest.xml");
+    return false;
+  }
+
+  std::unique_ptr<io::IData> data = manifest_file->OpenAsData();
+  if (data == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage(manifest_file->GetSource())
+                                     << "failed to open file");
+    return false;
+  }
+
+  std::unique_ptr<xml::XmlResource> manifest = xml::Inflate(
+      data->data(), data->size(), context->GetDiagnostics(), manifest_file->GetSource());
+  if (manifest == nullptr) {
+    context->GetDiagnostics()->Error(DiagMessage() << "failed to read binary AndroidManifest.xml");
+    return false;
+  }
+
+  Maybe<AppInfo> app_info =
+      ExtractAppInfoFromBinaryManifest(manifest.get(), context->GetDiagnostics());
+  if (!app_info) {
+    context->GetDiagnostics()->Error(DiagMessage()
+                                     << "failed to extract data from AndroidManifest.xml");
+    return false;
+  }
+
+  out_options->app_info = std::move(app_info.value());
+  context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
+  return true;
+}
+
+int Optimize(const std::vector<StringPiece>& args) {
+  OptimizeContext context;
+  OptimizeOptions options;
+  Maybe<std::string> target_densities;
+  std::vector<std::string> configs;
+  std::vector<std::string> split_args;
+  bool verbose = false;
+  Flags flags =
+      Flags()
+          .RequiredFlag("-o", "Path to the output APK.", &options.output_path)
+          .OptionalFlag(
+              "--target-densities",
+              "Comma separated list of the screen densities that the APK will be optimized for.\n"
+              "All the resources that would be unused on devices of the given densities will be \n"
+              "removed from the APK.",
+              &target_densities)
+          .OptionalFlagList("-c",
+                            "Comma separated list of configurations to include. The default\n"
+                            "is all configurations.",
+                            &configs)
+          .OptionalFlagList("--split",
+                            "Split resources matching a set of configs out to a "
+                            "Split APK.\nSyntax: path/to/output.apk:<config>[,<config>[...]].",
+                            &split_args)
+          .OptionalSwitch("--enable-sparse-encoding",
+                          "Enables encoding sparse entries using a binary search tree.\n"
+                          "This decreases APK size at the cost of resource retrieval performance.",
+                          &options.table_flattener_options.use_sparse_entries)
+          .OptionalSwitch("-v", "Enables verbose logging", &verbose);
+
+  if (!flags.Parse("aapt2 optimize", args, &std::cerr)) {
+    return 1;
+  }
+
+  if (flags.GetArgs().size() != 1u) {
+    std::cerr << "must have one APK as argument.\n\n";
+    flags.Usage("aapt2 optimize", &std::cerr);
+    return 1;
+  }
+
+  std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(&context, flags.GetArgs()[0]);
+  if (!apk) {
+    return 1;
+  }
+
+  context.SetVerbose(verbose);
+
+  if (target_densities) {
+    // Parse the target screen densities.
+    for (const StringPiece& config_str : util::Tokenize(target_densities.value(), ',')) {
+      Maybe<uint16_t> target_density =
+          ParseTargetDensityParameter(config_str, context.GetDiagnostics());
+      if (!target_density) {
+        return 1;
+      }
+      options.table_splitter_options.preferred_densities.push_back(target_density.value());
+    }
+  }
+
+  std::unique_ptr<IConfigFilter> filter;
+  if (!configs.empty()) {
+    filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
+    if (filter == nullptr) {
+      return 1;
+    }
+    options.table_splitter_options.config_filter = filter.get();
+  }
+
+  // Parse the split parameters.
+  for (const std::string& split_arg : split_args) {
+    options.split_paths.push_back({});
+    options.split_constraints.push_back({});
+    if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
+                             &options.split_constraints.back())) {
+      return 1;
+    }
+  }
+
+  if (!ExtractAppDataFromManifest(&context, apk.get(), &options)) {
+    return 1;
+  }
+
+  OptimizeCommand cmd(&context, options);
+  return cmd.Run(std::move(apk));
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Util.cpp b/tools/aapt2/cmd/Util.cpp
new file mode 100644
index 0000000..fd94bbc
--- /dev/null
+++ b/tools/aapt2/cmd/Util.cpp
@@ -0,0 +1,347 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include "cmd/Util.h"
+
+#include <vector>
+
+#include "android-base/logging.h"
+
+#include "ConfigDescription.h"
+#include "Locale.h"
+#include "ResourceUtils.h"
+#include "ValueVisitor.h"
+#include "split/TableSplitter.h"
+#include "util/Maybe.h"
+#include "util/Util.h"
+
+using android::StringPiece;
+
+namespace aapt {
+
+Maybe<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, IDiagnostics* diag) {
+  ConfigDescription preferred_density_config;
+  if (!ConfigDescription::Parse(arg, &preferred_density_config)) {
+    diag->Error(DiagMessage() << "invalid density '" << arg << "' for --preferred-density option");
+    return {};
+  }
+
+  // Clear the version that can be automatically added.
+  preferred_density_config.sdkVersion = 0;
+
+  if (preferred_density_config.diff(ConfigDescription::DefaultConfig()) !=
+      ConfigDescription::CONFIG_DENSITY) {
+    diag->Error(DiagMessage() << "invalid preferred density '" << arg << "'. "
+                              << "Preferred density must only be a density value");
+    return {};
+  }
+  return preferred_density_config.density;
+}
+
+bool ParseSplitParameter(const StringPiece& arg, IDiagnostics* diag, std::string* out_path,
+                         SplitConstraints* out_split) {
+  CHECK(diag != nullptr);
+  CHECK(out_path != nullptr);
+  CHECK(out_split != nullptr);
+
+  std::vector<std::string> parts = util::Split(arg, ':');
+  if (parts.size() != 2) {
+    diag->Error(DiagMessage() << "invalid split parameter '" << arg << "'");
+    diag->Note(DiagMessage() << "should be --split path/to/output.apk:<config>[,<config>...]");
+    return false;
+  }
+
+  *out_path = parts[0];
+  std::vector<ConfigDescription> configs;
+  for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) {
+    ConfigDescription config;
+    if (!ConfigDescription::Parse(config_str, &config)) {
+      diag->Error(DiagMessage() << "invalid config '" << config_str << "' in split parameter '"
+                                << arg << "'");
+      return false;
+    }
+    out_split->configs.insert(config);
+  }
+  return true;
+}
+
+std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
+                                                           IDiagnostics* diag) {
+  std::unique_ptr<AxisConfigFilter> filter = util::make_unique<AxisConfigFilter>();
+  for (const std::string& config_arg : args) {
+    for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
+      ConfigDescription config;
+      LocaleValue lv;
+      if (lv.InitFromFilterString(config_str)) {
+        lv.WriteTo(&config);
+      } else if (!ConfigDescription::Parse(config_str, &config)) {
+        diag->Error(DiagMessage() << "invalid config '" << config_str << "' for -c option");
+        return {};
+      }
+
+      if (config.density != 0) {
+        diag->Warn(DiagMessage() << "ignoring density '" << config << "' for -c option");
+      } else {
+        filter->AddConfig(config);
+      }
+    }
+  }
+  return std::move(filter);
+}
+
+// Adjust the SplitConstraints so that their SDK version is stripped if it
+// is less than or equal to the minSdk. Otherwise the resources that have had
+// their SDK version stripped due to minSdk won't ever match.
+std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
+    int min_sdk, const std::vector<SplitConstraints>& split_constraints) {
+  std::vector<SplitConstraints> adjusted_constraints;
+  adjusted_constraints.reserve(split_constraints.size());
+  for (const SplitConstraints& constraints : split_constraints) {
+    SplitConstraints constraint;
+    for (const ConfigDescription& config : constraints.configs) {
+      if (config.sdkVersion <= min_sdk) {
+        constraint.configs.insert(config.CopyWithoutSdkVersion());
+      } else {
+        constraint.configs.insert(config);
+      }
+    }
+    adjusted_constraints.push_back(std::move(constraint));
+  }
+  return adjusted_constraints;
+}
+
+static xml::AaptAttribute CreateAttributeWithId(const ResourceId& id) {
+  return xml::AaptAttribute{id, Attribute(true)};
+}
+
+std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
+                                                        const SplitConstraints& constraints) {
+  const ResourceId kVersionCode(0x0101021b);
+  const ResourceId kRevisionCode(0x010104d5);
+  const ResourceId kHasCode(0x0101000c);
+
+  std::unique_ptr<xml::XmlResource> doc = util::make_unique<xml::XmlResource>();
+
+  std::unique_ptr<xml::Namespace> namespace_android = util::make_unique<xml::Namespace>();
+  namespace_android->namespace_uri = xml::kSchemaAndroid;
+  namespace_android->namespace_prefix = "android";
+
+  std::unique_ptr<xml::Element> manifest_el = util::make_unique<xml::Element>();
+  manifest_el->name = "manifest";
+  manifest_el->attributes.push_back(xml::Attribute{"", "package", app_info.package});
+
+  if (app_info.version_code) {
+    const uint32_t version_code = app_info.version_code.value();
+    manifest_el->attributes.push_back(xml::Attribute{
+        xml::kSchemaAndroid, "versionCode", std::to_string(version_code),
+        CreateAttributeWithId(kVersionCode),
+        util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, version_code)});
+  }
+
+  if (app_info.revision_code) {
+    const uint32_t revision_code = app_info.revision_code.value();
+    manifest_el->attributes.push_back(xml::Attribute{
+        xml::kSchemaAndroid, "revisionCode", std::to_string(revision_code),
+        CreateAttributeWithId(kRevisionCode),
+        util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, revision_code)});
+  }
+
+  std::stringstream split_name;
+  if (app_info.split_name) {
+    split_name << app_info.split_name.value() << ".";
+  }
+  split_name << "config." << util::Joiner(constraints.configs, "_");
+
+  manifest_el->attributes.push_back(xml::Attribute{"", "split", split_name.str()});
+
+  if (app_info.split_name) {
+    manifest_el->attributes.push_back(
+        xml::Attribute{"", "configForSplit", app_info.split_name.value()});
+  }
+
+  std::unique_ptr<xml::Element> application_el = util::make_unique<xml::Element>();
+  application_el->name = "application";
+  application_el->attributes.push_back(
+      xml::Attribute{xml::kSchemaAndroid, "hasCode", "false", CreateAttributeWithId(kHasCode),
+                     util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_BOOLEAN, 0u)});
+
+  manifest_el->AppendChild(std::move(application_el));
+  namespace_android->AppendChild(std::move(manifest_el));
+  doc->root = std::move(namespace_android);
+  return doc;
+}
+
+static Maybe<std::string> ExtractCompiledString(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    String* compiled_str = ValueCast<String>(attr->compiled_value.get());
+    if (compiled_str != nullptr) {
+      if (!compiled_str->value->empty()) {
+        return *compiled_str->value;
+      } else {
+        *out_error = "compiled value is an empty string";
+        return {};
+      }
+    }
+    *out_error = "compiled value is not a string";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  if (!attr->value.empty()) {
+    return attr->value;
+  }
+  *out_error = "value is an empty string";
+  return {};
+}
+
+static Maybe<uint32_t> ExtractCompiledInt(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
+    if (compiled_prim != nullptr) {
+      if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
+          compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
+        return compiled_prim->value.data;
+      }
+    }
+    *out_error = "compiled value is not an integer";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  Maybe<uint32_t> integer = ResourceUtils::ParseInt(attr->value);
+  if (integer) {
+    return integer;
+  }
+  std::stringstream error_msg;
+  error_msg << "'" << attr->value << "' is not a valid integer";
+  *out_error = error_msg.str();
+  return {};
+}
+
+static Maybe<int> ExtractSdkVersion(xml::Attribute* attr, std::string* out_error) {
+  if (attr->compiled_value != nullptr) {
+    BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
+    if (compiled_prim != nullptr) {
+      if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
+          compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
+        return compiled_prim->value.data;
+      }
+      *out_error = "compiled value is not an integer or string";
+      return {};
+    }
+
+    String* compiled_str = ValueCast<String>(attr->compiled_value.get());
+    if (compiled_str != nullptr) {
+      Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(*compiled_str->value);
+      if (sdk_version) {
+        return sdk_version;
+      }
+
+      *out_error = "compiled string value is not a valid SDK version";
+      return {};
+    }
+    *out_error = "compiled value is not an integer or string";
+    return {};
+  }
+
+  // Fallback to the plain text value if there is one.
+  Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(attr->value);
+  if (sdk_version) {
+    return sdk_version;
+  }
+  std::stringstream error_msg;
+  error_msg << "'" << attr->value << "' is not a valid SDK version";
+  *out_error = error_msg.str();
+  return {};
+}
+
+Maybe<AppInfo> ExtractAppInfoFromBinaryManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
+  // Make sure the first element is <manifest> with package attribute.
+  xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
+  if (manifest_el == nullptr) {
+    return {};
+  }
+
+  AppInfo app_info;
+
+  if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
+    diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
+    return {};
+  }
+
+  xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
+  if (!package_attr) {
+    diag->Error(DiagMessage(xml_res->file.source) << "<manifest> must have a 'package' attribute");
+    return {};
+  }
+
+  std::string error_msg;
+  Maybe<std::string> maybe_package = ExtractCompiledString(package_attr, &error_msg);
+  if (!maybe_package) {
+    diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                << "invalid package name: " << error_msg);
+    return {};
+  }
+  app_info.package = maybe_package.value();
+
+  if (xml::Attribute* version_code_attr =
+          manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
+    Maybe<uint32_t> maybe_code = ExtractCompiledInt(version_code_attr, &error_msg);
+    if (!maybe_code) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid android:versionCode: " << error_msg);
+      return {};
+    }
+    app_info.version_code = maybe_code.value();
+  }
+
+  if (xml::Attribute* revision_code_attr =
+          manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
+    Maybe<uint32_t> maybe_code = ExtractCompiledInt(revision_code_attr, &error_msg);
+    if (!maybe_code) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid android:revisionCode: " << error_msg);
+      return {};
+    }
+    app_info.revision_code = maybe_code.value();
+  }
+
+  if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
+    Maybe<std::string> maybe_split_name = ExtractCompiledString(split_name_attr, &error_msg);
+    if (!maybe_split_name) {
+      diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
+                  << "invalid split name: " << error_msg);
+      return {};
+    }
+    app_info.split_name = maybe_split_name.value();
+  }
+
+  if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
+    if (xml::Attribute* min_sdk =
+            uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
+      Maybe<int> maybe_sdk = ExtractSdkVersion(min_sdk, &error_msg);
+      if (!maybe_sdk) {
+        diag->Error(DiagMessage(xml_res->file.source.WithLine(uses_sdk_el->line_number))
+                    << "invalid android:minSdkVersion: " << error_msg);
+        return {};
+      }
+      app_info.min_sdk_version = maybe_sdk.value();
+    }
+  }
+  return app_info;
+}
+
+}  // namespace aapt
diff --git a/tools/aapt2/cmd/Util.h b/tools/aapt2/cmd/Util.h
new file mode 100644
index 0000000..fd9b39c
--- /dev/null
+++ b/tools/aapt2/cmd/Util.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#ifndef AAPT_SPLIT_UTIL_H
+#define AAPT_SPLIT_UTIL_H
+
+#include "androidfw/StringPiece.h"
+
+#include "AppInfo.h"
+#include "Diagnostics.h"
+#include "SdkConstants.h"
+#include "filter/ConfigFilter.h"
+#include "split/TableSplitter.h"
+#include "util/Maybe.h"
+#include "xml/XmlDom.h"
+
+namespace aapt {
+
+// Parses a configuration density (ex. hdpi, xxhdpi, 234dpi, anydpi, etc).
+// Returns Nothing and logs a human friendly error message if the string was not legal.
+Maybe<uint16_t> ParseTargetDensityParameter(const android::StringPiece& arg, IDiagnostics* diag);
+
+// Parses a string of the form 'path/to/output.apk:<config>[,<config>...]' and fills in
+// `out_path` with the path and `out_split` with the set of ConfigDescriptions.
+// Returns false and logs a human friendly error message if the string was not legal.
+bool ParseSplitParameter(const android::StringPiece& arg, IDiagnostics* diag, std::string* out_path,
+                         SplitConstraints* out_split);
+
+// Parses a set of config filter strings of the form 'en,fr-rFR' and returns an IConfigFilter.
+// Returns nullptr and logs a human friendly error message if the string was not legal.
+std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
+                                                           IDiagnostics* diag);
+
+// Adjust the SplitConstraints so that their SDK version is stripped if it
+// is less than or equal to the min_sdk. Otherwise the resources that have had
+// their SDK version stripped due to min_sdk won't ever match.
+std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
+    int min_sdk, const std::vector<SplitConstraints>& split_constraints);
+
+// Generates a split AndroidManifest.xml given the split constraints and app info. The resulting
+// XmlResource does not need to be linked via XmlReferenceLinker.
+// This will never fail/return nullptr.
+std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
+                                                        const SplitConstraints& constraints);
+
+// Extracts relevant info from the AndroidManifest.xml.
+Maybe<AppInfo> ExtractAppInfoFromBinaryManifest(xml::XmlResource* xml_res, IDiagnostics* diag);
+
+}  // namespace aapt
+
+#endif /* AAPT_SPLIT_UTIL_H */