• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "Link.h"
18 
19 #include <sys/stat.h>
20 
21 #include <algorithm>
22 #include <cinttypes>
23 #include <queue>
24 #include <unordered_map>
25 #include <vector>
26 
27 #include "AppInfo.h"
28 #include "Debug.h"
29 #include "LoadedApk.h"
30 #include "NameMangler.h"
31 #include "ResourceUtils.h"
32 #include "ResourceValues.h"
33 #include "ValueVisitor.h"
34 #include "android-base/errors.h"
35 #include "android-base/expected.h"
36 #include "android-base/file.h"
37 #include "android-base/stringprintf.h"
38 #include "androidfw/BigBufferStream.h"
39 #include "androidfw/FileStream.h"
40 #include "androidfw/IDiagnostics.h"
41 #include "androidfw/Locale.h"
42 #include "androidfw/StringPiece.h"
43 #include "cmd/Util.h"
44 #include "compile/IdAssigner.h"
45 #include "compile/XmlIdCollector.h"
46 #include "filter/ConfigFilter.h"
47 #include "format/Archive.h"
48 #include "format/Container.h"
49 #include "format/binary/TableFlattener.h"
50 #include "format/binary/XmlFlattener.h"
51 #include "format/proto/ProtoDeserialize.h"
52 #include "format/proto/ProtoSerialize.h"
53 #include "io/FileSystem.h"
54 #include "io/Util.h"
55 #include "io/ZipArchive.h"
56 #include "java/JavaClassGenerator.h"
57 #include "java/ManifestClassGenerator.h"
58 #include "java/ProguardRules.h"
59 #include "link/FeatureFlagsFilter.h"
60 #include "link/Linkers.h"
61 #include "link/ManifestFixer.h"
62 #include "link/NoDefaultResourceRemover.h"
63 #include "link/ReferenceLinker.h"
64 #include "link/ResourceExcluder.h"
65 #include "link/TableMerger.h"
66 #include "link/XmlCompatVersioner.h"
67 #include "optimize/ResourceDeduper.h"
68 #include "optimize/VersionCollapser.h"
69 #include "process/IResourceTableConsumer.h"
70 #include "process/ProductFilter.h"
71 #include "process/SymbolTable.h"
72 #include "split/TableSplitter.h"
73 #include "trace/TraceBuffer.h"
74 #include "util/Files.h"
75 #include "xml/XmlDom.h"
76 
77 using ::android::ConfigDescription;
78 using ::android::FileInputStream;
79 using ::android::StringPiece;
80 using ::android::base::expected;
81 using ::android::base::StringPrintf;
82 using ::android::base::unexpected;
83 
84 namespace aapt {
85 
86 namespace {
87 
GetStaticLibraryPackage(ResourceTable * table)88 expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
89   // Resource tables built by aapt2 always contain one package. This is a post condition of
90   // VerifyNoExternalPackages.
91   if (table->packages.size() != 1u) {
92     return unexpected("static library contains more than one package");
93   }
94   return table->packages.back().get();
95 }
96 
97 }  // namespace
98 
99 constexpr uint8_t kAndroidPackageId = 0x01;
100 
101 class LinkContext : public IAaptContext {
102  public:
LinkContext(android::IDiagnostics * diagnostics)103   explicit LinkContext(android::IDiagnostics* diagnostics)
104       : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
105   }
106 
GetPackageType()107   PackageType GetPackageType() override {
108     return package_type_;
109   }
110 
SetPackageType(PackageType type)111   void SetPackageType(PackageType type) {
112     package_type_ = type;
113   }
114 
GetDiagnostics()115   android::IDiagnostics* GetDiagnostics() override {
116     return diagnostics_;
117   }
118 
GetNameMangler()119   NameMangler* GetNameMangler() override {
120     return &name_mangler_;
121   }
122 
SetNameManglerPolicy(const NameManglerPolicy & policy)123   void SetNameManglerPolicy(const NameManglerPolicy& policy) {
124     name_mangler_ = NameMangler(policy);
125   }
126 
GetCompilationPackage()127   const std::string& GetCompilationPackage() override {
128     return compilation_package_;
129   }
130 
SetCompilationPackage(StringPiece package_name)131   void SetCompilationPackage(StringPiece package_name) {
132     compilation_package_ = std::string(package_name);
133   }
134 
GetPackageId()135   uint8_t GetPackageId() override {
136     return package_id_;
137   }
138 
SetPackageId(uint8_t id)139   void SetPackageId(uint8_t id) {
140     package_id_ = id;
141   }
142 
GetExternalSymbols()143   SymbolTable* GetExternalSymbols() override {
144     return &symbols_;
145   }
146 
IsVerbose()147   bool IsVerbose() override {
148     return verbose_;
149   }
150 
SetVerbose(bool val)151   void SetVerbose(bool val) {
152     verbose_ = val;
153     diagnostics_->SetVerbose(val);
154   }
155 
GetMinSdkVersion()156   int GetMinSdkVersion() override {
157     return min_sdk_version_;
158   }
159 
SetMinSdkVersion(int minSdk)160   void SetMinSdkVersion(int minSdk) {
161     min_sdk_version_ = minSdk;
162   }
163 
GetSplitNameDependencies()164   const std::set<std::string>& GetSplitNameDependencies() override {
165     return split_name_dependencies_;
166   }
167 
SetSplitNameDependencies(const std::set<std::string> & split_name_dependencies)168   void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
169     split_name_dependencies_ = split_name_dependencies;
170   }
171 
172  private:
173   DISALLOW_COPY_AND_ASSIGN(LinkContext);
174 
175   PackageType package_type_ = PackageType::kApp;
176   android::IDiagnostics* diagnostics_;
177   NameMangler name_mangler_;
178   std::string compilation_package_;
179   uint8_t package_id_ = 0x0;
180   SymbolTable symbols_;
181   bool verbose_ = false;
182   int min_sdk_version_ = 0;
183   std::set<std::string> split_name_dependencies_;
184 };
185 
186 // A custom delegate that generates compatible pre-O IDs for use with feature splits.
187 // Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
188 // is interpreted as a negative number. Some verification was wrongly assuming negative values
189 // were invalid.
190 //
191 // This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
192 // where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
193 // an overlap exists.
194 //
195 // See b/37498913.
196 class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
197  public:
FeatureSplitSymbolTableDelegate(IAaptContext * context)198   explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
199   }
200 
201   virtual ~FeatureSplitSymbolTableDelegate() = default;
202 
FindByName(const ResourceName & name,const std::vector<std::unique_ptr<ISymbolSource>> & sources)203   virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
204       const ResourceName& name,
205       const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
206     std::unique_ptr<SymbolTable::Symbol> symbol =
207         DefaultSymbolTableDelegate::FindByName(name, sources);
208     if (symbol == nullptr) {
209       return {};
210     }
211 
212     // Check to see if this is an 'id' with the target package.
213     if (name.type.type == ResourceType::kId && symbol->id) {
214       ResourceId* id = &symbol->id.value();
215       if (id->package_id() > kAppPackageId) {
216         // Rewrite the resource ID to be compatible pre-O.
217         ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
218 
219         // Check that this doesn't overlap another resource.
220         if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
221           // The ID overlaps, so log a message (since this is a weird failure) and fail.
222           context_->GetDiagnostics()->Error(android::DiagMessage()
223                                             << "Failed to rewrite " << name
224                                             << " for pre-O feature split support");
225           return {};
226         }
227 
228         if (context_->IsVerbose()) {
229           context_->GetDiagnostics()->Note(android::DiagMessage()
230                                            << "rewriting " << name << " (" << *id << ") -> ("
231                                            << rewritten_id << ")");
232         }
233 
234         *id = rewritten_id;
235       }
236     }
237     return symbol;
238   }
239 
240  private:
241   DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
242 
243   IAaptContext* context_;
244 };
245 
FlattenXml(IAaptContext * context,const xml::XmlResource & xml_res,StringPiece path,bool keep_raw_values,bool utf16,OutputFormat format,IArchiveWriter * writer)246 static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path,
247                        bool keep_raw_values, bool utf16, OutputFormat format,
248                        IArchiveWriter* writer) {
249   TRACE_CALL();
250   if (context->IsVerbose()) {
251     context->GetDiagnostics()->Note(android::DiagMessage(path)
252                                     << "writing to archive (keep_raw_values="
253                                     << (keep_raw_values ? "true" : "false") << ")");
254   }
255 
256   switch (format) {
257     case OutputFormat::kApk: {
258       android::BigBuffer buffer(1024);
259       XmlFlattenerOptions options = {};
260       options.keep_raw_values = keep_raw_values;
261       options.use_utf16 = utf16;
262       XmlFlattener flattener(&buffer, options);
263       if (!flattener.Consume(context, &xml_res)) {
264         return false;
265       }
266 
267       android::BigBufferInputStream input_stream(&buffer);
268       return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
269                                           writer);
270     } break;
271 
272     case OutputFormat::kProto: {
273       pb::XmlNode pb_node;
274       // Strip whitespace text nodes from tha AndroidManifest.xml
275       SerializeXmlOptions options;
276       options.remove_empty_text_nodes = (path == kAndroidManifestPath);
277       SerializeXmlResourceToPb(xml_res, &pb_node);
278       return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer);
279     } break;
280   }
281   return false;
282 }
283 
284 // Inflates an XML file from the source path.
LoadXml(const std::string & path,android::IDiagnostics * diag)285 static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
286                                                  android::IDiagnostics* diag) {
287   TRACE_CALL();
288   android::FileInputStream fin(path);
289   if (fin.HadError()) {
290     diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
291     return {};
292   }
293   return xml::Inflate(&fin, diag, android::Source(path));
294 }
295 
296 struct ResourceFileFlattenerOptions {
297   bool no_auto_version = false;
298   bool no_version_vectors = false;
299   bool no_version_transitions = false;
300   bool no_xml_namespaces = false;
301   bool keep_raw_values = false;
302   bool do_not_compress_anything = false;
303   bool update_proguard_spec = false;
304   bool do_not_fail_on_missing_resources = false;
305   OutputFormat output_format = OutputFormat::kApk;
306   std::unordered_set<std::string> extensions_to_not_compress;
307   std::optional<std::regex> regex_to_not_compress;
308 };
309 
310 // A sampling of public framework resource IDs.
311 struct R {
312   struct attr {
313     enum : uint32_t {
314       paddingLeft = 0x010100d6u,
315       paddingRight = 0x010100d8u,
316       paddingHorizontal = 0x0101053du,
317 
318       paddingTop = 0x010100d7u,
319       paddingBottom = 0x010100d9u,
320       paddingVertical = 0x0101053eu,
321 
322       layout_marginLeft = 0x010100f7u,
323       layout_marginRight = 0x010100f9u,
324       layout_marginHorizontal = 0x0101053bu,
325 
326       layout_marginTop = 0x010100f8u,
327       layout_marginBottom = 0x010100fau,
328       layout_marginVertical = 0x0101053cu,
329     };
330   };
331 };
332 
333 template <typename T>
GetCompressionFlags(StringPiece str,T options)334 uint32_t GetCompressionFlags(StringPiece str, T options) {
335   if (options.do_not_compress_anything) {
336     return 0;
337   }
338 
339   if (options.regex_to_not_compress &&
340       std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) {
341     return 0;
342   }
343 
344   for (const std::string& extension : options.extensions_to_not_compress) {
345     if (util::EndsWith(str, extension)) {
346       return 0;
347     }
348   }
349   return ArchiveEntry::kCompress;
350 }
351 
352 class ResourceFileFlattener {
353  public:
354   ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
355                         proguard::KeepSet* keep_set);
356 
357   bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
358 
359  private:
360   struct FileOperation {
361     ConfigDescription config;
362 
363     // The entry this file came from.
364     ResourceEntry* entry;
365 
366     // The file to copy as-is.
367     io::IFile* file_to_copy;
368 
369     // The XML to process and flatten.
370     std::unique_ptr<xml::XmlResource> xml_to_flatten;
371 
372     // The destination to write this file to.
373     std::string dst_path;
374   };
375 
376   std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
377                                                                        FileOperation* file_op);
378 
379   ResourceFileFlattenerOptions options_;
380   IAaptContext* context_;
381   proguard::KeepSet* keep_set_;
382   XmlCompatVersioner::Rules rules_;
383 };
384 
ResourceFileFlattener(const ResourceFileFlattenerOptions & options,IAaptContext * context,proguard::KeepSet * keep_set)385 ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
386                                              IAaptContext* context, proguard::KeepSet* keep_set)
387     : options_(options), context_(context), keep_set_(keep_set) {
388   SymbolTable* symm = context_->GetExternalSymbols();
389 
390   // Build up the rules for degrading newer attributes to older ones.
391   // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
392   // generated from the attribute definitions themselves (b/62028956).
393   if (symm->FindById(R::attr::paddingHorizontal)) {
394     std::vector<ReplacementAttr> replacements{
395         {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
396         {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
397     };
398     rules_[R::attr::paddingHorizontal] =
399         util::make_unique<DegradeToManyRule>(std::move(replacements));
400   }
401 
402   if (symm->FindById(R::attr::paddingVertical)) {
403     std::vector<ReplacementAttr> replacements{
404         {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
405         {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
406     };
407     rules_[R::attr::paddingVertical] =
408         util::make_unique<DegradeToManyRule>(std::move(replacements));
409   }
410 
411   if (symm->FindById(R::attr::layout_marginHorizontal)) {
412     std::vector<ReplacementAttr> replacements{
413         {"layout_marginLeft", R::attr::layout_marginLeft,
414          Attribute(android::ResTable_map::TYPE_DIMENSION)},
415         {"layout_marginRight", R::attr::layout_marginRight,
416          Attribute(android::ResTable_map::TYPE_DIMENSION)},
417     };
418     rules_[R::attr::layout_marginHorizontal] =
419         util::make_unique<DegradeToManyRule>(std::move(replacements));
420   }
421 
422   if (symm->FindById(R::attr::layout_marginVertical)) {
423     std::vector<ReplacementAttr> replacements{
424         {"layout_marginTop", R::attr::layout_marginTop,
425          Attribute(android::ResTable_map::TYPE_DIMENSION)},
426         {"layout_marginBottom", R::attr::layout_marginBottom,
427          Attribute(android::ResTable_map::TYPE_DIMENSION)},
428     };
429     rules_[R::attr::layout_marginVertical] =
430         util::make_unique<DegradeToManyRule>(std::move(replacements));
431   }
432 }
433 
IsTransitionElement(const std::string & name)434 static bool IsTransitionElement(const std::string& name) {
435   return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
436          name == "changeImageTransform" || name == "changeTransform" ||
437          name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
438          name == "changeScroll" || name == "transitionSet" || name == "transition" ||
439          name == "transitionManager";
440 }
441 
IsVectorElement(const std::string & name)442 static bool IsVectorElement(const std::string& name) {
443   return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
444          name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
445          name == "set";
446 }
447 
448 template <typename T>
make_singleton_vec(T && val)449 std::vector<T> make_singleton_vec(T&& val) {
450   std::vector<T> vec;
451   vec.emplace_back(std::forward<T>(val));
452   return vec;
453 }
454 
LinkAndVersionXmlFile(ResourceTable * table,FileOperation * file_op)455 std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
456     ResourceTable* table, FileOperation* file_op) {
457   TRACE_CALL();
458   xml::XmlResource* doc = file_op->xml_to_flatten.get();
459   const android::Source& src = doc->file.source;
460 
461   if (context_->IsVerbose()) {
462     context_->GetDiagnostics()->Note(android::DiagMessage()
463                                      << "linking " << src.path << " (" << doc->file.name << ")");
464   }
465 
466   // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
467   // that existing projects have out-of-date references which pass compilation.
468   xml::StripAndroidStudioAttributes(doc->root.get());
469 
470   XmlReferenceLinker xml_linker(table);
471   if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
472     return {};
473   }
474 
475   if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
476     return {};
477   }
478 
479   if (options_.no_xml_namespaces) {
480     XmlNamespaceRemover namespace_remover;
481     if (!namespace_remover.Consume(context_, doc)) {
482       return {};
483     }
484   }
485 
486   if (options_.no_auto_version) {
487     return make_singleton_vec(std::move(file_op->xml_to_flatten));
488   }
489 
490   if (options_.no_version_vectors || options_.no_version_transitions) {
491     // Skip this if it is a vector or animated-vector.
492     xml::Element* el = doc->root.get();
493     if (el && el->namespace_uri.empty()) {
494       if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
495           (options_.no_version_transitions && IsTransitionElement(el->name))) {
496         return make_singleton_vec(std::move(file_op->xml_to_flatten));
497       }
498     }
499   }
500 
501   const ConfigDescription& config = file_op->config;
502   ResourceEntry* entry = file_op->entry;
503 
504   XmlCompatVersioner xml_compat_versioner(&rules_);
505   const util::Range<ApiVersion> api_range{config.sdkVersion,
506                                           FindNextApiVersionForConfig(entry, config)};
507   return xml_compat_versioner.Process(context_, doc, api_range);
508 }
509 
XmlFileTypeForOutputFormat(OutputFormat format)510 ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
511   switch (format) {
512     case OutputFormat::kApk:
513       return ResourceFile::Type::kBinaryXml;
514     case OutputFormat::kProto:
515       return ResourceFile::Type::kProtoXml;
516   }
517   LOG_ALWAYS_FATAL("unreachable");
518   return ResourceFile::Type::kUnknown;
519 }
520 
521 static auto kDrawableVersions = std::map<std::string, ApiVersion>{
522     { "adaptive-icon" , SDK_O },
523 };
524 
Flatten(ResourceTable * table,IArchiveWriter * archive_writer)525 bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
526   TRACE_CALL();
527   bool error = false;
528   std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
529 
530   proguard::CollectResourceReferences(context_, table, keep_set_);
531 
532   for (auto& pkg : table->packages) {
533     CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
534 
535     for (auto& type : pkg->types) {
536       // Sort by config and name, so that we get better locality in the zip file.
537       config_sorted_files.clear();
538       std::queue<FileOperation> file_operations;
539 
540       // Populate the queue with all files in the ResourceTable.
541       for (auto& entry : type->entries) {
542         for (auto& config_value : entry->values) {
543           // WARNING! Do not insert or remove any resources while executing in this scope. It will
544           // corrupt the iteration order.
545 
546           FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
547           if (!file_ref) {
548             continue;
549           }
550 
551           io::IFile* file = file_ref->file;
552           if (!file) {
553             context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
554                                               << "file not found");
555             return false;
556           }
557 
558           FileOperation file_op;
559           file_op.entry = entry.get();
560           file_op.dst_path = *file_ref->path;
561           file_op.config = config_value->config;
562           file_op.file_to_copy = file;
563 
564           if (type->named_type.type != ResourceType::kRaw &&
565               (file_ref->type == ResourceFile::Type::kBinaryXml ||
566                file_ref->type == ResourceFile::Type::kProtoXml)) {
567             std::unique_ptr<io::IData> data = file->OpenAsData();
568             if (!data) {
569               context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
570                                                 << "failed to open file");
571               return false;
572             }
573 
574             if (file_ref->type == ResourceFile::Type::kProtoXml) {
575               pb::XmlNode pb_xml_node;
576               if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
577                 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
578                                                   << "failed to parse proto XML");
579                 return false;
580               }
581 
582               std::string error;
583               file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
584               if (file_op.xml_to_flatten == nullptr) {
585                 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
586                                                   << "failed to deserialize proto XML: " << error);
587                 return false;
588               }
589             } else {
590               std::string error_str;
591               file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
592               if (file_op.xml_to_flatten == nullptr) {
593                 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
594                                                   << "failed to parse binary XML: " << error_str);
595                 return false;
596               }
597             }
598 
599             // Update the type that this file will be written as.
600             file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
601 
602             file_op.xml_to_flatten->file.config = config_value->config;
603             file_op.xml_to_flatten->file.source = file_ref->GetSource();
604             file_op.xml_to_flatten->file.name =
605                 ResourceName(pkg->name, type->named_type, entry->name);
606           }
607 
608           // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
609           // else we end up copying the string in the std::make_pair() method,
610           // then creating a StringPiece from the copy, which would cause us
611           // to end up referencing garbage in the map.
612           const StringPiece entry_name(entry->name);
613           config_sorted_files[std::make_pair(config_value->config, entry_name)] =
614               std::move(file_op);
615         }
616       }
617 
618       // Now flatten the sorted values.
619       for (auto& map_entry : config_sorted_files) {
620         const ConfigDescription& config = map_entry.first.first;
621         FileOperation& file_op = map_entry.second;
622 
623         if (file_op.xml_to_flatten) {
624           // Check minimum sdk versions supported for drawables
625           auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
626           if (drawable_entry != kDrawableVersions.end()) {
627             if (drawable_entry->second > context_->GetMinSdkVersion()
628                 && drawable_entry->second > config.sdkVersion) {
629               context_->GetDiagnostics()->Error(
630                   android::DiagMessage(file_op.xml_to_flatten->file.source)
631                   << "<" << drawable_entry->first << "> elements "
632                   << "require a sdk version of at least " << (int16_t)drawable_entry->second);
633               error = true;
634               continue;
635             }
636           }
637 
638           std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
639               LinkAndVersionXmlFile(table, &file_op);
640           if (versioned_docs.empty()) {
641             error = true;
642             continue;
643           }
644 
645           for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
646             std::string dst_path = file_op.dst_path;
647             if (doc->file.config != file_op.config) {
648               // Only add the new versioned configurations.
649               if (context_->IsVerbose()) {
650                 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
651                                                  << "auto-versioning resource from config '"
652                                                  << config << "' -> '" << doc->file.config << "'");
653               }
654 
655               const ResourceFile& file = doc->file;
656               dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
657 
658               auto file_ref =
659                   util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
660               file_ref->SetSource(doc->file.source);
661 
662               // Update the output format of this XML file.
663               file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
664               bool result = table->AddResource(NewResourceBuilder(file.name)
665                                                    .SetValue(std::move(file_ref), file.config)
666                                                    .SetAllowMangled(true)
667                                                    .Build(),
668                                                context_->GetDiagnostics());
669               if (!result) {
670                 return false;
671               }
672             }
673 
674             error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
675                                  false /*utf16*/, options_.output_format, archive_writer);
676           }
677         } else {
678           error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
679                                           GetCompressionFlags(file_op.dst_path, options_),
680                                           archive_writer);
681         }
682       }
683     }
684   }
685   return !error;
686 }
687 
WriteStableIdMapToPath(android::IDiagnostics * diag,const std::unordered_map<ResourceName,ResourceId> & id_map,const std::string & id_map_path)688 static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
689                                    const std::unordered_map<ResourceName, ResourceId>& id_map,
690                                    const std::string& id_map_path) {
691   android::FileOutputStream fout(id_map_path);
692   if (fout.HadError()) {
693     diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
694     return false;
695   }
696 
697   text::Printer printer(&fout);
698   for (const auto& entry : id_map) {
699     const ResourceName& name = entry.first;
700     const ResourceId& id = entry.second;
701     printer.Print(name.to_string());
702     printer.Print(" = ");
703     printer.Println(id.to_string());
704   }
705   fout.Flush();
706 
707   if (fout.HadError()) {
708     diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
709     return false;
710   }
711   return true;
712 }
713 
LoadStableIdMap(android::IDiagnostics * diag,const std::string & path,std::unordered_map<ResourceName,ResourceId> * out_id_map)714 static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
715                             std::unordered_map<ResourceName, ResourceId>* out_id_map) {
716   std::string content;
717   if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
718     diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
719     return false;
720   }
721 
722   out_id_map->clear();
723   size_t line_no = 0;
724   for (StringPiece line : util::Tokenize(content, '\n')) {
725     line_no++;
726     line = util::TrimWhitespace(line);
727     if (line.empty()) {
728       continue;
729     }
730 
731     auto iter = std::find(line.begin(), line.end(), '=');
732     if (iter == line.end()) {
733       diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
734       return false;
735     }
736 
737     ResourceNameRef name;
738     StringPiece res_name_str =
739         util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
740     if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
741       diag->Error(android::DiagMessage(android::Source(path, line_no))
742                   << "invalid resource name '" << res_name_str << "'");
743       return false;
744     }
745 
746     const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
747     const size_t res_id_str_len = line.size() - res_id_start_idx;
748     StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
749 
750     std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
751     if (!maybe_id) {
752       diag->Error(android::DiagMessage(android::Source(path, line_no))
753                   << "invalid resource ID '" << res_id_str << "'");
754       return false;
755     }
756 
757     (*out_id_map)[name.ToResourceName()] = maybe_id.value();
758   }
759   return true;
760 }
761 
762 class Linker {
763  public:
Linker(LinkContext * context,const LinkOptions & options)764   Linker(LinkContext* context, const LinkOptions& options)
765       : options_(options),
766         context_(context),
767         final_table_(),
768         file_collection_(util::make_unique<io::FileCollection>()) {
769   }
770 
ExtractCompileSdkVersions(android::AssetManager2 * assets)771   void ExtractCompileSdkVersions(android::AssetManager2* assets) {
772     using namespace android;
773 
774     // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
775     // we're looking for the first attribute resource in the system package.
776     android::ApkAssetsCookie cookie;
777     if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
778       cookie = value->cookie;
779     } else {
780       // No Framework assets loaded. Not a failure.
781       return;
782     }
783 
784     std::unique_ptr<Asset> manifest(
785         assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
786     if (manifest == nullptr) {
787       // No errors.
788       return;
789     }
790 
791     std::string error;
792     std::unique_ptr<xml::XmlResource> manifest_xml =
793         xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
794     if (manifest_xml == nullptr) {
795       // No errors.
796       return;
797     }
798 
799     if (!options_.manifest_fixer_options.compile_sdk_version) {
800       xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
801       if (attr != nullptr) {
802         auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
803         if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
804           switch (prim->value.dataType) {
805             case Res_value::TYPE_INT_DEC:
806               compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
807               break;
808             case Res_value::TYPE_INT_HEX:
809               compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
810               break;
811             default:
812               break;
813           }
814         } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
815           compile_sdk_version = *str->value;
816         } else {
817           compile_sdk_version = attr->value;
818         }
819       }
820     }
821 
822     if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
823       xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
824       if (attr != nullptr) {
825         std::optional<std::string>& compile_sdk_version_codename =
826             options_.manifest_fixer_options.compile_sdk_version_codename;
827         if (String* str = ValueCast<String>(attr->compiled_value.get())) {
828           compile_sdk_version_codename = *str->value;
829         } else {
830           compile_sdk_version_codename = attr->value;
831         }
832       }
833     }
834   }
835 
836   // Creates a SymbolTable that loads symbols from the various APKs.
837   // Pre-condition: context_->GetCompilationPackage() needs to be set.
LoadSymbolsFromIncludePaths()838   bool LoadSymbolsFromIncludePaths() {
839     TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
840     auto asset_source = util::make_unique<AssetManagerSymbolSource>();
841     for (const std::string& path : options_.include_paths) {
842       if (context_->IsVerbose()) {
843         context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
844       }
845 
846       std::string error;
847       auto zip_collection = io::ZipFileCollection::Create(path, &error);
848       if (zip_collection == nullptr) {
849         context_->GetDiagnostics()->Error(android::DiagMessage()
850                                           << "failed to open APK: " << error);
851         return false;
852       }
853 
854       if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
855         // Load this as a static library include.
856         std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
857             android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
858         if (static_apk == nullptr) {
859           return false;
860         }
861 
862         if (context_->GetPackageType() != PackageType::kStaticLib) {
863           // Can't include static libraries when not building a static library (they have no IDs
864           // assigned).
865           context_->GetDiagnostics()->Error(
866               android::DiagMessage(path)
867               << "can't include static library when not building a static lib");
868           return false;
869         }
870 
871         ResourceTable* table = static_apk->GetResourceTable();
872 
873         // If we are using --no-static-lib-packages, we need to rename the package of this table to
874         // our compilation package so the symbol package name does not get mangled into the entry
875         // name.
876         if (options_.no_static_lib_packages && !table->packages.empty()) {
877           auto lib_package_result = GetStaticLibraryPackage(table);
878           if (!lib_package_result.has_value()) {
879             context_->GetDiagnostics()->Error(android::DiagMessage(path)
880                                               << lib_package_result.error());
881             return false;
882           }
883           lib_package_result.value()->name = context_->GetCompilationPackage();
884         }
885 
886         context_->GetExternalSymbols()->AppendSource(
887             util::make_unique<ResourceTableSymbolSource>(table));
888         static_library_includes_.push_back(std::move(static_apk));
889       } else {
890         if (!asset_source->AddAssetPath(path)) {
891           context_->GetDiagnostics()->Error(android::DiagMessage()
892                                             << "failed to load include path " << path);
893           return false;
894         }
895       }
896     }
897 
898     // Capture the shared libraries so that the final resource table can be properly flattened
899     // with support for shared libraries.
900     for (auto& entry : asset_source->GetAssignedPackageIds()) {
901       if (entry.first == kAppPackageId) {
902         // Capture the included base feature package.
903         included_feature_base_ = entry.second;
904       } else if (entry.first == kFrameworkPackageId) {
905         // Try to embed which version of the framework we're compiling against.
906         // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
907         // when linking our synthesized 'android:compileSdkVersion' attribute.
908         std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
909             ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
910         if (symbol != nullptr && symbol->is_public) {
911           // The symbol is present and public, extract the android:versionName and
912           // android:versionCode from the framework AndroidManifest.xml.
913           ExtractCompileSdkVersions(asset_source->GetAssetManager());
914         }
915       } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
916         final_table_.included_packages_[entry.first] = entry.second;
917       }
918     }
919 
920     context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
921     return true;
922   }
923 
ExtractAppInfoFromManifest(xml::XmlResource * xml_res,android::IDiagnostics * diag)924   std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
925                                                     android::IDiagnostics* diag) {
926     TRACE_CALL();
927     // Make sure the first element is <manifest> with package attribute.
928     xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
929     if (manifest_el == nullptr) {
930       return {};
931     }
932 
933     AppInfo app_info;
934 
935     if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
936       diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
937       return {};
938     }
939 
940     xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
941     if (!package_attr) {
942       diag->Error(android::DiagMessage(xml_res->file.source)
943                   << "<manifest> must have a 'package' attribute");
944       return {};
945     }
946     app_info.package = package_attr->value;
947 
948     if (xml::Attribute* version_code_attr =
949             manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
950       std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
951       if (!maybe_code) {
952         diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
953                     << "invalid android:versionCode '" << version_code_attr->value << "'");
954         return {};
955       }
956       app_info.version_code = maybe_code.value();
957     }
958 
959     if (xml::Attribute* version_code_major_attr =
960         manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
961       std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
962       if (!maybe_code) {
963         diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
964                     << "invalid android:versionCodeMajor '" << version_code_major_attr->value
965                     << "'");
966         return {};
967       }
968       app_info.version_code_major = maybe_code.value();
969     }
970 
971     if (xml::Attribute* revision_code_attr =
972             manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
973       std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
974       if (!maybe_code) {
975         diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
976                     << "invalid android:revisionCode '" << revision_code_attr->value << "'");
977         return {};
978       }
979       app_info.revision_code = maybe_code.value();
980     }
981 
982     if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
983       if (!split_name_attr->value.empty()) {
984         app_info.split_name = split_name_attr->value;
985       }
986     }
987 
988     if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
989       if (xml::Attribute* min_sdk =
990               uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
991         app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
992       }
993     }
994 
995     for (const xml::Element* child_el : manifest_el->GetChildElements()) {
996       if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
997         if (const xml::Attribute* split_name =
998             child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
999           if (!split_name->value.empty()) {
1000             app_info.split_name_dependencies.insert(split_name->value);
1001           }
1002         }
1003       }
1004     }
1005     return app_info;
1006   }
1007 
1008   // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1009   // Postcondition: ResourceTable has only one package left. All others are
1010   // stripped, or there is an error and false is returned.
VerifyNoExternalPackages()1011   bool VerifyNoExternalPackages() {
1012     auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
1013       return context_->GetCompilationPackage() != pkg->name;
1014     };
1015 
1016     bool error = false;
1017     for (const auto& package : final_table_.packages) {
1018       if (is_ext_package_func(package)) {
1019         // We have a package that is not related to the one we're building!
1020         for (const auto& type : package->types) {
1021           for (const auto& entry : type->entries) {
1022             ResourceNameRef res_name(package->name, type->named_type, entry->name);
1023 
1024             for (const auto& config_value : entry->values) {
1025               // Special case the occurrence of an ID that is being generated
1026               // for the 'android' package. This is due to legacy reasons.
1027               if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1028                 context_->GetDiagnostics()->Warn(
1029                     android::DiagMessage(config_value->value->GetSource())
1030                     << "generated id '" << res_name << "' for external package '" << package->name
1031                     << "'");
1032               } else {
1033                 context_->GetDiagnostics()->Error(
1034                     android::DiagMessage(config_value->value->GetSource())
1035                     << "defined resource '" << res_name << "' for external package '"
1036                     << package->name << "'");
1037                 error = true;
1038               }
1039             }
1040           }
1041         }
1042       }
1043     }
1044 
1045     auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1046                                        is_ext_package_func);
1047     final_table_.packages.erase(new_end_iter, final_table_.packages.end());
1048     return !error;
1049   }
1050 
1051   /**
1052    * Returns true if no IDs have been set, false otherwise.
1053    */
VerifyNoIdsSet()1054   bool VerifyNoIdsSet() {
1055     for (const auto& package : final_table_.packages) {
1056       for (const auto& type : package->types) {
1057         for (const auto& entry : type->entries) {
1058           if (entry->id) {
1059             ResourceNameRef res_name(package->name, type->named_type, entry->name);
1060             context_->GetDiagnostics()->Error(android::DiagMessage()
1061                                               << "resource " << res_name << " has ID "
1062                                               << entry->id.value() << " assigned");
1063             return false;
1064           }
1065         }
1066       }
1067     }
1068     return true;
1069   }
1070 
VerifyLocaleFormat(xml::XmlResource * manifest,android::IDiagnostics * diag)1071   bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
1072     // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1073     // element.
1074     const xml::Element* application = manifest->root->FindChild("", "application");
1075     if (!application) {
1076       return true;
1077     }
1078     const xml::Attribute* localeConfig =
1079         application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1080     if (!localeConfig) {
1081       return true;
1082     }
1083 
1084     // Deserialize XML from the compiled file
1085     if (localeConfig->compiled_value) {
1086       const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1087       const auto localeconfig_entry =
1088           ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1089       if (!localeconfig_entry) {
1090         // If locale config is resolved from external symbols - skip validation.
1091         if (context_->GetExternalSymbols()->FindByReference(*localeconfig_reference)) {
1092           return true;
1093         }
1094         context_->GetDiagnostics()->Error(
1095             android::DiagMessage(localeConfig->compiled_value->GetSource())
1096             << "no localeConfig entry");
1097         return false;
1098       }
1099       for (const auto& value : localeconfig_entry->values) {
1100         const FileReference* file_ref = ValueCast<FileReference>(value->value.get());
1101         if (!file_ref) {
1102           context_->GetDiagnostics()->Error(
1103               android::DiagMessage(localeConfig->compiled_value->GetSource())
1104               << "no file reference");
1105           return false;
1106         }
1107         io::IFile* file = file_ref->file;
1108         if (!file) {
1109           context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
1110                                             << "file not found");
1111           return false;
1112         }
1113         std::unique_ptr<io::IData> data = file->OpenAsData();
1114         if (!data) {
1115           context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1116                                             << "failed to open file");
1117           return false;
1118         }
1119         pb::XmlNode pb_xml_node;
1120         if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
1121           context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1122                                             << "failed to parse proto XML");
1123           return false;
1124         }
1125 
1126         std::string error;
1127         std::unique_ptr<xml::XmlResource> localeConfig_xml =
1128             DeserializeXmlResourceFromPb(pb_xml_node, &error);
1129         if (!localeConfig_xml) {
1130           context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1131                                             << "failed to deserialize proto XML: " << error);
1132           return false;
1133         }
1134         xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1135         if (!localeConfig_el) {
1136           diag->Error(android::DiagMessage(file->GetSource()) << "no root tag defined");
1137           return false;
1138         }
1139         if (localeConfig_el->name != "locale-config") {
1140           diag->Error(android::DiagMessage(file->GetSource())
1141                       << "invalid element name: " << localeConfig_el->name
1142                       << ", expected: locale-config");
1143           return false;
1144         }
1145         for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1146           if (child_el->name == "locale") {
1147             if (const xml::Attribute* locale_name_attr =
1148                     child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1149               const std::string& locale_name = locale_name_attr->value;
1150               const std::string valid_name = ConvertToBCP47Tag(locale_name);
1151               // Start to verify the locale format
1152               ConfigDescription config;
1153               if (!ConfigDescription::Parse(valid_name, &config)) {
1154                 diag->Error(android::DiagMessage(file->GetSource())
1155                             << "invalid configuration: " << locale_name);
1156                 return false;
1157               }
1158             } else {
1159               diag->Error(android::DiagMessage(file->GetSource())
1160                           << "the attribute android:name is not found");
1161               return false;
1162             }
1163           } else {
1164             diag->Error(android::DiagMessage(file->GetSource())
1165                         << "invalid element name: " << child_el->name << ", expected: locale");
1166             return false;
1167           }
1168         }
1169       }
1170     }
1171     return true;
1172   }
1173 
ConvertToBCP47Tag(const std::string & locale)1174   std::string ConvertToBCP47Tag(const std::string& locale) {
1175     std::string bcp47tag = "b+";
1176     bcp47tag += locale;
1177     std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1178     return bcp47tag;
1179   }
1180 
MakeArchiveWriter(StringPiece out)1181   std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) {
1182     if (options_.output_to_directory) {
1183       return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
1184     } else {
1185       return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
1186     }
1187   }
1188 
FlattenTable(ResourceTable * table,OutputFormat format,IArchiveWriter * writer)1189   bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1190     TRACE_CALL();
1191     switch (format) {
1192       case OutputFormat::kApk: {
1193         android::BigBuffer buffer(1024);
1194         TableFlattener flattener(options_.table_flattener_options, &buffer);
1195         if (!flattener.Consume(context_, table)) {
1196           context_->GetDiagnostics()->Error(android::DiagMessage()
1197                                             << "failed to flatten resource table");
1198           return false;
1199         }
1200 
1201         android::BigBufferInputStream input_stream(&buffer);
1202         return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1203                                             ArchiveEntry::kAlign, writer);
1204       } break;
1205 
1206       case OutputFormat::kProto: {
1207         pb::ResourceTable pb_table;
1208         SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1209                            options_.proto_table_flattener_options);
1210         return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1211                                       ArchiveEntry::kCompress, writer);
1212       } break;
1213     }
1214     return false;
1215   }
1216 
WriteJavaFile(ResourceTable * table,StringPiece package_name_to_generate,StringPiece out_package,const JavaClassGeneratorOptions & java_options,const std::optional<std::string> & out_text_symbols_path={})1217   bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate,
1218                      StringPiece out_package, const JavaClassGeneratorOptions& java_options,
1219                      const std::optional<std::string>& out_text_symbols_path = {}) {
1220     if (!options_.generate_java_class_path && !out_text_symbols_path) {
1221       return true;
1222     }
1223 
1224     std::string out_path;
1225     std::unique_ptr<android::FileOutputStream> fout;
1226     if (options_.generate_java_class_path) {
1227       out_path = options_.generate_java_class_path.value();
1228       file::AppendPath(&out_path, file::PackageToPath(out_package));
1229       if (!file::mkdirs(out_path)) {
1230         context_->GetDiagnostics()->Error(android::DiagMessage()
1231                                           << "failed to create directory '" << out_path << "'");
1232         return false;
1233       }
1234 
1235       file::AppendPath(&out_path, "R.java");
1236 
1237       fout = util::make_unique<android::FileOutputStream>(out_path);
1238       if (fout->HadError()) {
1239         context_->GetDiagnostics()->Error(android::DiagMessage()
1240                                           << "failed writing to '" << out_path
1241                                           << "': " << fout->GetError());
1242         return false;
1243       }
1244     }
1245 
1246     std::unique_ptr<android::FileOutputStream> fout_text;
1247     if (out_text_symbols_path) {
1248       fout_text = util::make_unique<android::FileOutputStream>(out_text_symbols_path.value());
1249       if (fout_text->HadError()) {
1250         context_->GetDiagnostics()->Error(android::DiagMessage()
1251                                           << "failed writing to '" << out_text_symbols_path.value()
1252                                           << "': " << fout_text->GetError());
1253         return false;
1254       }
1255     }
1256 
1257     JavaClassGenerator generator(context_, table, java_options);
1258     if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
1259       context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
1260       return false;
1261     }
1262 
1263     return true;
1264   }
1265 
GenerateJavaClasses()1266   bool GenerateJavaClasses() {
1267     TRACE_CALL();
1268     // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1269     std::vector<std::string> packages_to_callback;
1270 
1271     JavaClassGeneratorOptions template_options;
1272     template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1273     template_options.javadoc_annotations = options_.javadoc_annotations;
1274 
1275     if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1276       template_options.use_final = false;
1277     }
1278 
1279     if (context_->GetPackageType() == PackageType::kSharedLib) {
1280       template_options.use_final = false;
1281       template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1282     }
1283 
1284     const StringPiece actual_package = context_->GetCompilationPackage();
1285     StringPiece output_package = context_->GetCompilationPackage();
1286     if (options_.custom_java_package) {
1287       // Override the output java package to the custom one.
1288       output_package = options_.custom_java_package.value();
1289     }
1290 
1291     // Generate the private symbols if required.
1292     if (options_.private_symbols) {
1293       packages_to_callback.push_back(options_.private_symbols.value());
1294 
1295       // If we defined a private symbols package, we only emit Public symbols
1296       // to the original package, and private and public symbols to the private package.
1297       JavaClassGeneratorOptions options = template_options;
1298       options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1299       if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1300                          options)) {
1301         return false;
1302       }
1303     }
1304 
1305     // Generate copies of the original package R class but with different package names.
1306     // This is to support non-namespaced builds.
1307     for (const std::string& extra_package : options_.extra_java_packages) {
1308       packages_to_callback.push_back(extra_package);
1309 
1310       JavaClassGeneratorOptions options = template_options;
1311       options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1312       if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1313         return false;
1314       }
1315     }
1316 
1317     // Generate R classes for each package that was merged (static library).
1318     // Use the actual package's resources only.
1319     for (const std::string& package : table_merger_->merged_packages()) {
1320       packages_to_callback.push_back(package);
1321 
1322       JavaClassGeneratorOptions options = template_options;
1323       options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1324       if (!WriteJavaFile(&final_table_, package, package, options)) {
1325         return false;
1326       }
1327     }
1328 
1329     // Generate the main public R class.
1330     JavaClassGeneratorOptions options = template_options;
1331 
1332     // Only generate public symbols if we have a private package.
1333     if (options_.private_symbols) {
1334       options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1335     }
1336 
1337     if (options.rewrite_callback_options) {
1338       options.rewrite_callback_options.value().packages_to_callback =
1339           std::move(packages_to_callback);
1340     }
1341 
1342     if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1343                        options_.generate_text_symbols_path)) {
1344       return false;
1345     }
1346 
1347     return true;
1348   }
1349 
WriteManifestJavaFile(xml::XmlResource * manifest_xml)1350   bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1351     TRACE_CALL();
1352     if (!options_.generate_java_class_path) {
1353       return true;
1354     }
1355 
1356     std::unique_ptr<ClassDefinition> manifest_class =
1357         GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
1358 
1359     if (!manifest_class) {
1360       // Something bad happened, but we already logged it, so exit.
1361       return false;
1362     }
1363 
1364     if (manifest_class->empty()) {
1365       // Empty Manifest class, no need to generate it.
1366       return true;
1367     }
1368 
1369     // Add any JavaDoc annotations to the generated class.
1370     for (const std::string& annotation : options_.javadoc_annotations) {
1371       std::string proper_annotation = "@";
1372       proper_annotation += annotation;
1373       manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
1374     }
1375 
1376     const std::string package_utf8 =
1377         options_.custom_java_package.value_or(context_->GetCompilationPackage());
1378 
1379     std::string out_path = options_.generate_java_class_path.value();
1380     file::AppendPath(&out_path, file::PackageToPath(package_utf8));
1381 
1382     if (!file::mkdirs(out_path)) {
1383       context_->GetDiagnostics()->Error(android::DiagMessage()
1384                                         << "failed to create directory '" << out_path << "'");
1385       return false;
1386     }
1387 
1388     file::AppendPath(&out_path, "Manifest.java");
1389 
1390     android::FileOutputStream fout(out_path);
1391     if (fout.HadError()) {
1392       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1393                                                                << "': " << fout.GetError());
1394       return false;
1395     }
1396 
1397     ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1398                                    false /* strip_api_annotations */, &fout);
1399     fout.Flush();
1400 
1401     if (fout.HadError()) {
1402       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1403                                                                << "': " << fout.GetError());
1404       return false;
1405     }
1406     return true;
1407   }
1408 
WriteProguardFile(const std::optional<std::string> & out,const proguard::KeepSet & keep_set)1409   bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
1410     TRACE_CALL();
1411     if (!out) {
1412       return true;
1413     }
1414 
1415     const std::string& out_path = out.value();
1416     android::FileOutputStream fout(out_path);
1417     if (fout.HadError()) {
1418       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1419                                                                << "': " << fout.GetError());
1420       return false;
1421     }
1422 
1423     proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1424                            options_.no_proguard_location_reference);
1425     fout.Flush();
1426 
1427     if (fout.HadError()) {
1428       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1429                                                                << "': " << fout.GetError());
1430       return false;
1431     }
1432     return true;
1433   }
1434 
MergeStaticLibrary(const std::string & input,bool override)1435   bool MergeStaticLibrary(const std::string& input, bool override) {
1436     TRACE_CALL();
1437     if (context_->IsVerbose()) {
1438       context_->GetDiagnostics()->Note(android::DiagMessage()
1439                                        << "merging static library " << input);
1440     }
1441 
1442     std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1443     if (apk == nullptr) {
1444       context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
1445       return false;
1446     }
1447 
1448     ResourceTable* table = apk->GetResourceTable();
1449     if (table->packages.empty()) {
1450       return true;
1451     }
1452 
1453     auto lib_package_result = GetStaticLibraryPackage(table);
1454     if (!lib_package_result.has_value()) {
1455       context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
1456       return false;
1457     }
1458 
1459     ResourceTablePackage* pkg = lib_package_result.value();
1460     bool result;
1461     if (options_.no_static_lib_packages) {
1462       // Merge all resources as if they were in the compilation package. This is the old behavior
1463       // of aapt.
1464 
1465       // Add the package to the set of --extra-packages so we emit an R.java for each library
1466       // package.
1467       if (!pkg->name.empty()) {
1468         options_.extra_java_packages.insert(pkg->name);
1469       }
1470 
1471       // Clear the package name, so as to make the resources look like they are coming from the
1472       // local package.
1473       pkg->name = "";
1474       result = table_merger_->Merge(android::Source(input), table, override);
1475 
1476     } else {
1477       // This is the proper way to merge libraries, where the package name is
1478       // preserved and resource names are mangled.
1479       result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
1480     }
1481 
1482     if (!result) {
1483       return false;
1484     }
1485 
1486     // Make sure to move the collection into the set of IFileCollections.
1487     merged_apks_.push_back(std::move(apk));
1488     return true;
1489   }
1490 
MergeExportedSymbols(const android::Source & source,const std::vector<SourcedResourceName> & exported_symbols)1491   bool MergeExportedSymbols(const android::Source& source,
1492                             const std::vector<SourcedResourceName>& exported_symbols) {
1493     TRACE_CALL();
1494     // Add the exports of this file to the table.
1495     for (const SourcedResourceName& exported_symbol : exported_symbols) {
1496       ResourceName res_name = exported_symbol.name;
1497       if (res_name.package.empty()) {
1498         res_name.package = context_->GetCompilationPackage();
1499       }
1500 
1501       std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
1502       if (mangled_name) {
1503         res_name = mangled_name.value();
1504       }
1505 
1506       auto id = util::make_unique<Id>();
1507       id->SetSource(source.WithLine(exported_symbol.line));
1508       bool result = final_table_.AddResource(
1509           NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1510           context_->GetDiagnostics());
1511       if (!result) {
1512         return false;
1513       }
1514     }
1515     return true;
1516   }
1517 
MergeCompiledFile(const ResourceFile & compiled_file,io::IFile * file,bool override)1518   bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1519     TRACE_CALL();
1520     if (context_->IsVerbose()) {
1521       context_->GetDiagnostics()->Note(android::DiagMessage()
1522                                        << "merging '" << compiled_file.name
1523                                        << "' from compiled file " << compiled_file.source);
1524     }
1525 
1526     if (!table_merger_->MergeFile(compiled_file, override, file)) {
1527       return false;
1528     }
1529     return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1530   }
1531 
1532   // Takes a path to load as a ZIP file and merges the files within into the main ResourceTable.
1533   // If override is true, conflicting resources are allowed to override each other, in order of last
1534   // seen.
1535   // An io::IFileCollection is created from the ZIP file and added to the set of
1536   // io::IFileCollections that are open.
MergeArchive(const std::string & input,bool override)1537   bool MergeArchive(const std::string& input, bool override) {
1538     TRACE_CALL();
1539     if (context_->IsVerbose()) {
1540       context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
1541     }
1542 
1543     std::string error_str;
1544     std::unique_ptr<io::ZipFileCollection> collection =
1545         io::ZipFileCollection::Create(input, &error_str);
1546     if (!collection) {
1547       context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
1548       return false;
1549     }
1550 
1551     bool error = false;
1552     for (auto iter = collection->Iterator(); iter->HasNext();) {
1553       if (!MergeFile(iter->Next(), override)) {
1554         error = true;
1555       }
1556     }
1557 
1558     // Make sure to move the collection into the set of IFileCollections.
1559     collections_.push_back(std::move(collection));
1560     return !error;
1561   }
1562 
1563   // Takes a path to load and merge into the main ResourceTable. If override is true,
1564   // conflicting resources are allowed to override each other, in order of last seen.
1565   // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1566   // as ZIP archive and the files within are merged individually.
1567   // Otherwise the file is processed on its own.
MergePath(const std::string & path,bool override)1568   bool MergePath(const std::string& path, bool override) {
1569     if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1570         util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1571       return MergeArchive(path, override);
1572     } else if (util::EndsWith(path, ".apk")) {
1573       return MergeStaticLibrary(path, override);
1574     }
1575 
1576     io::IFile* file = file_collection_->InsertFile(path);
1577     return MergeFile(file, override);
1578   }
1579 
1580   // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
1581   // If override is true, conflicting resources are allowed to override each other, in order of last
1582   // seen.
1583   // All other file types are ignored. This is because these files could be coming from a zip,
1584   // where we could have other files like classes.dex.
MergeFile(io::IFile * file,bool override)1585   bool MergeFile(io::IFile* file, bool override) {
1586     TRACE_CALL();
1587     const android::Source& src = file->GetSource();
1588 
1589     if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
1590       // Since AAPT compiles these file types and appends .flat to them, seeing
1591       // their raw extensions is a sign that they weren't compiled.
1592       const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1593       context_->GetDiagnostics()->Error(android::DiagMessage(src)
1594                                         << "uncompiled " << file_type
1595                                         << " file passed as argument. Must be "
1596                                            "compiled first into .flat file.");
1597       return false;
1598     } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1599       if (context_->IsVerbose()) {
1600         context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
1601         return true;
1602       }
1603     }
1604 
1605     std::unique_ptr<android::InputStream> input_stream = file->OpenInputStream();
1606     if (input_stream == nullptr) {
1607       context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
1608       return false;
1609     }
1610 
1611     if (input_stream->HadError()) {
1612       context_->GetDiagnostics()->Error(android::DiagMessage(src)
1613                                         << "failed to open file: " << input_stream->GetError());
1614       return false;
1615     }
1616 
1617     ContainerReaderEntry* entry;
1618     ContainerReader reader(input_stream.get());
1619 
1620     if (reader.HadError()) {
1621       context_->GetDiagnostics()->Error(android::DiagMessage(src)
1622                                         << "failed to read file: " << reader.GetError());
1623       return false;
1624     }
1625 
1626     while ((entry = reader.Next()) != nullptr) {
1627       if (entry->Type() == ContainerEntryType::kResTable) {
1628         TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
1629         pb::ResourceTable pb_table;
1630         if (!entry->GetResTable(&pb_table)) {
1631           context_->GetDiagnostics()->Error(
1632               android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
1633           return false;
1634         }
1635 
1636         ResourceTable table;
1637         std::string error;
1638         if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
1639           context_->GetDiagnostics()->Error(android::DiagMessage(src)
1640                                             << "failed to deserialize resource table: " << error);
1641           return false;
1642         }
1643 
1644         if (!table_merger_->Merge(src, &table, override)) {
1645           context_->GetDiagnostics()->Error(android::DiagMessage(src)
1646                                             << "failed to merge resource table");
1647           return false;
1648         }
1649       } else if (entry->Type() == ContainerEntryType::kResFile) {
1650         TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
1651         pb::internal::CompiledFile pb_compiled_file;
1652         off64_t offset;
1653         size_t len;
1654         if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1655           context_->GetDiagnostics()->Error(
1656               android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
1657           return false;
1658         }
1659 
1660         ResourceFile resource_file;
1661         std::string error;
1662         if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1663           context_->GetDiagnostics()->Error(android::DiagMessage(src)
1664                                             << "failed to read compiled header: " << error);
1665           return false;
1666         }
1667 
1668         if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1669           return false;
1670         }
1671       }
1672     }
1673     return true;
1674   }
1675 
CopyAssetsDirsToApk(IArchiveWriter * writer)1676   bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1677     std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1678     for (const std::string& assets_dir : options_.assets_dirs) {
1679       std::optional<std::vector<std::string>> files =
1680           file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1681       if (!files) {
1682         return false;
1683       }
1684 
1685       for (const std::string& file : files.value()) {
1686         std::string full_key = "assets/" + file;
1687         std::string full_path = assets_dir;
1688         file::AppendPath(&full_path, file);
1689 
1690         auto iter = merged_assets.find(full_key);
1691         if (iter == merged_assets.end()) {
1692           merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1693                                                          android::Source(std::move(full_path))));
1694         } else if (context_->IsVerbose()) {
1695           context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
1696                                            << "asset file overrides '" << full_path << "'");
1697         }
1698       }
1699     }
1700 
1701     for (auto& entry : merged_assets) {
1702       uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
1703       if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1704                                  writer)) {
1705         return false;
1706       }
1707     }
1708     return true;
1709   }
1710 
ResolveTableEntry(LinkContext * context,ResourceTable * table,Reference * reference)1711   ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1712                                    Reference* reference) {
1713     if (!reference || !reference->name) {
1714       return nullptr;
1715     }
1716     auto name_ref = ResourceNameRef(reference->name.value());
1717     if (name_ref.package.empty()) {
1718       name_ref.package = context->GetCompilationPackage();
1719     }
1720     const auto search_result = table->FindResource(name_ref);
1721     if (!search_result) {
1722       return nullptr;
1723     }
1724     return search_result.value().entry;
1725   }
1726 
AliasAdaptiveIcon(xml::XmlResource * manifest,ResourceTable * table)1727   void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
1728     const xml::Element* application = manifest->root->FindChild("", "application");
1729     if (!application) {
1730       return;
1731     }
1732 
1733     const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1734     const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
1735     if (!icon || !round_icon) {
1736       return;
1737     }
1738 
1739     // Find the icon resource defined within the application.
1740     const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
1741     const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1742     if (!icon_entry) {
1743       return;
1744     }
1745 
1746     int icon_max_sdk = 0;
1747     for (auto& config_value : icon_entry->values) {
1748       icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1749           ? config_value->config.sdkVersion : icon_max_sdk;
1750     }
1751     if (icon_max_sdk < SDK_O) {
1752       // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1753       return;
1754     }
1755 
1756     // Find the roundIcon resource defined within the application.
1757     const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
1758     const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1759     if (!round_icon_entry) {
1760       return;
1761     }
1762 
1763     int round_icon_max_sdk = 0;
1764     for (auto& config_value : round_icon_entry->values) {
1765       round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1766                      ? config_value->config.sdkVersion : round_icon_max_sdk;
1767     }
1768     if (round_icon_max_sdk >= SDK_O) {
1769       // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1770       // not generate an alias to the icon drawable.
1771       return;
1772     }
1773 
1774     // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
1775     for (auto& config_value : icon_entry->values) {
1776       if (config_value->config.sdkVersion < SDK_O) {
1777         continue;
1778       }
1779 
1780       context_->GetDiagnostics()->Note(android::DiagMessage()
1781                                        << "generating " << round_icon_reference->name.value()
1782                                        << " with config \"" << config_value->config
1783                                        << "\" for round icon compatibility");
1784 
1785       CloningValueTransformer cloner(&table->string_pool);
1786       auto value = icon_reference->Transform(cloner);
1787       auto round_config_value =
1788           round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
1789       round_config_value->value = std::move(value);
1790     }
1791   }
1792 
VerifySharedUserId(xml::XmlResource * manifest,ResourceTable * table)1793   bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1794     const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1795     if (manifest_el == nullptr) {
1796       return true;
1797     }
1798     if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1799       return true;
1800     }
1801     const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1802     if (!attr) {
1803       return true;
1804     }
1805     const auto validate = [&](const std::string& shared_user_id) -> bool {
1806       if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1807         return true;
1808       }
1809       android::DiagMessage error_msg(manifest_el->line_number);
1810       error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1811                 << shared_user_id << "'";
1812       if (options_.manifest_fixer_options.warn_validation) {
1813         // Treat the error only as a warning.
1814         context_->GetDiagnostics()->Warn(error_msg);
1815         return true;
1816       }
1817       context_->GetDiagnostics()->Error(error_msg);
1818       return false;
1819     };
1820     // If attr->compiled_value is not null, check if it is a ref
1821     if (attr->compiled_value) {
1822       const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1823       if (ref == nullptr) {
1824         return true;
1825       }
1826       const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1827       if (!shared_user_id_entry) {
1828         return true;
1829       }
1830       for (const auto& value : shared_user_id_entry->values) {
1831         const auto str_value = ValueCast<String>(value->value.get());
1832         if (str_value != nullptr && !validate(*str_value->value)) {
1833           return false;
1834         }
1835       }
1836       return true;
1837     }
1838 
1839     // Fallback to checking the raw value
1840     return validate(attr->value);
1841   }
1842 
1843   // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1844   // to the IArchiveWriter.
WriteApk(IArchiveWriter * writer,proguard::KeepSet * keep_set,xml::XmlResource * manifest,ResourceTable * table)1845   bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1846                 ResourceTable* table) {
1847     TRACE_CALL();
1848     const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1849                                  || options_.keep_raw_values;
1850     bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
1851                              true /*utf16*/, options_.output_format, writer);
1852     if (!result) {
1853       return false;
1854     }
1855 
1856     // When a developer specifies an adaptive application icon, and a non-adaptive round application
1857     // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1858     // because certain devices prefer android:roundIcon over android:icon regardless of the API
1859     // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1860     // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1861     // See (b/34829129)
1862     AliasAdaptiveIcon(manifest, table);
1863 
1864     // Verify the shared user id here to handle the case of reference value.
1865     if (!VerifySharedUserId(manifest, table)) {
1866       return false;
1867     }
1868 
1869     ResourceFileFlattenerOptions file_flattener_options;
1870     file_flattener_options.keep_raw_values = keep_raw_values;
1871     file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1872     file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
1873     file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
1874     file_flattener_options.no_auto_version = options_.no_auto_version;
1875     file_flattener_options.no_version_vectors = options_.no_version_vectors;
1876     file_flattener_options.no_version_transitions = options_.no_version_transitions;
1877     file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1878     file_flattener_options.update_proguard_spec =
1879         static_cast<bool>(options_.generate_proguard_rules_path);
1880     file_flattener_options.output_format = options_.output_format;
1881     file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
1882 
1883     ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
1884     if (!file_flattener.Flatten(table, writer)) {
1885       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
1886       return false;
1887     }
1888 
1889     // Hack to fix b/68820737.
1890     // We need to modify the ResourceTable's package name, but that should NOT affect
1891     // anything else being generated, which includes the Java classes.
1892     // If required, the package name is modifed before flattening, and then modified back
1893     // to its original name.
1894     ResourceTablePackage* package_to_rewrite = nullptr;
1895     // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1896     // or higher] as invalid. In order to work around this limitation, we allow the use
1897     // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1898     // definition of what a valid "split" package ID is to account for this.
1899     const bool isSplitPackage = (options_.allow_reserved_package_id &&
1900           context_->GetPackageId() != kAppPackageId &&
1901           context_->GetPackageId() != kFrameworkPackageId)
1902         || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1903     if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
1904       // The base APK is included, and this is a feature split. If the base package is
1905       // the same as this package, then we are building an old style Android Instant Apps feature
1906       // split and must apply this workaround to avoid requiring namespaces support.
1907       if (!table->packages.empty() &&
1908           table->packages.back()->name == context_->GetCompilationPackage()) {
1909         package_to_rewrite = table->packages.back().get();
1910         std::string new_package_name =
1911             StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1912                          app_info_.split_name.value_or("feature").c_str());
1913 
1914         if (context_->IsVerbose()) {
1915           context_->GetDiagnostics()->Note(
1916               android::DiagMessage() << "rewriting resource package name for feature split to '"
1917                                      << new_package_name << "'");
1918         }
1919         package_to_rewrite->name = new_package_name;
1920       }
1921     }
1922 
1923     bool success = FlattenTable(table, options_.output_format, writer);
1924 
1925     if (package_to_rewrite != nullptr) {
1926       // Change the name back.
1927       package_to_rewrite->name = context_->GetCompilationPackage();
1928 
1929       // TableFlattener creates an `included_packages_` mapping entry for each package with a
1930       // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1931       // library, do not include a mapping from the feature package name to the feature package id
1932       // in the feature's dynamic reference table.
1933       table->included_packages_.erase(context_->GetPackageId());
1934     }
1935 
1936     if (!success) {
1937       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
1938     }
1939     return success;
1940   }
1941 
Run(const std::vector<std::string> & input_files)1942   int Run(const std::vector<std::string>& input_files) {
1943     TRACE_CALL();
1944     // Load the AndroidManifest.xml
1945     std::unique_ptr<xml::XmlResource> manifest_xml =
1946         LoadXml(options_.manifest_path, context_->GetDiagnostics());
1947     if (!manifest_xml) {
1948       return 1;
1949     }
1950 
1951     // First extract the Package name without modifying it (via --rename-manifest-package).
1952     if (std::optional<AppInfo> maybe_app_info =
1953             ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
1954       const AppInfo& app_info = maybe_app_info.value();
1955       context_->SetCompilationPackage(app_info.package);
1956     }
1957 
1958     // Determine the package name under which to merge resources.
1959     if (options_.rename_resources_package) {
1960       if (!options_.custom_java_package) {
1961         // Generate the R.java under the original package name instead of the package name specified
1962         // through --rename-resources-package.
1963         options_.custom_java_package = context_->GetCompilationPackage();
1964       }
1965       context_->SetCompilationPackage(options_.rename_resources_package.value());
1966     }
1967 
1968     // Now that the compilation package is set, load the dependencies. This will also extract
1969     // the Android framework's versionCode and versionName, if they exist.
1970     if (!LoadSymbolsFromIncludePaths()) {
1971       return 1;
1972     }
1973 
1974     ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1975     if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
1976       return 1;
1977     }
1978 
1979     std::optional<AppInfo> maybe_app_info =
1980         ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
1981     if (!maybe_app_info) {
1982       return 1;
1983     }
1984 
1985     app_info_ = maybe_app_info.value();
1986     context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
1987 
1988     context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
1989     context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
1990 
1991     std::unique_ptr<xml::XmlResource> pre_flags_filter_manifest_xml = manifest_xml->Clone();
1992 
1993     FeatureFlagsFilterOptions flags_filter_options;
1994     if (context_->GetMinSdkVersion() > SDK_UPSIDE_DOWN_CAKE) {
1995       // For API version > U, PackageManager will dynamically read the flag values and disable
1996       // manifest elements accordingly when parsing the manifest.
1997       // For API version <= U, we remove disabled elements from the manifest with the filter.
1998       flags_filter_options.remove_disabled_elements = false;
1999       flags_filter_options.flags_must_have_value = false;
2000     }
2001     FeatureFlagsFilter flags_filter(options_.feature_flag_values, flags_filter_options);
2002     if (!flags_filter.Consume(context_, manifest_xml.get())) {
2003       return 1;
2004     }
2005 
2006     // Override the package ID when it is "android".
2007     if (context_->GetCompilationPackage() == "android") {
2008       context_->SetPackageId(kAndroidPackageId);
2009 
2010       // Verify we're building a regular app.
2011       if (context_->GetPackageType() != PackageType::kApp) {
2012         context_->GetDiagnostics()->Error(
2013             android::DiagMessage() << "package 'android' can only be built as a regular app");
2014         return 1;
2015       }
2016     }
2017 
2018     TableMergerOptions table_merger_options;
2019     table_merger_options.auto_add_overlay = options_.auto_add_overlay;
2020     table_merger_options.override_styles_instead_of_overlaying =
2021         options_.override_styles_instead_of_overlaying;
2022     table_merger_options.strict_visibility = options_.strict_visibility;
2023     table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
2024 
2025     if (context_->IsVerbose()) {
2026       context_->GetDiagnostics()->Note(android::DiagMessage()
2027                                        << StringPrintf("linking package '%s' using package ID %02x",
2028                                                        context_->GetCompilationPackage().data(),
2029                                                        context_->GetPackageId()));
2030     }
2031 
2032     // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
2033     // in res/**/*.
2034     {
2035       XmlIdCollector collector;
2036       if (!collector.Consume(context_, manifest_xml.get())) {
2037         return false;
2038       }
2039 
2040       if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
2041         return false;
2042       }
2043     }
2044 
2045     for (const std::string& input : input_files) {
2046       if (!MergePath(input, false)) {
2047         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
2048         return 1;
2049       }
2050     }
2051 
2052     for (const std::string& input : options_.overlay_files) {
2053       if (!MergePath(input, true)) {
2054         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
2055         return 1;
2056       }
2057     }
2058 
2059     if (!VerifyNoExternalPackages()) {
2060       return 1;
2061     }
2062 
2063     if (context_->GetPackageType() != PackageType::kStaticLib) {
2064       PrivateAttributeMover mover;
2065       if (context_->GetPackageId() == kAndroidPackageId &&
2066           !mover.Consume(context_, &final_table_)) {
2067         context_->GetDiagnostics()->Error(android::DiagMessage()
2068                                           << "failed moving private attributes");
2069         return 1;
2070       }
2071 
2072       // Assign IDs if we are building a regular app.
2073       IdAssigner id_assigner(&options_.stable_id_map);
2074       if (!id_assigner.Consume(context_, &final_table_)) {
2075         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
2076         return 1;
2077       }
2078 
2079       // Now grab each ID and emit it as a file.
2080       if (options_.resource_id_map_path) {
2081         for (auto& package : final_table_.packages) {
2082           for (auto& type : package->types) {
2083             for (auto& entry : type->entries) {
2084               ResourceName name(package->name, type->named_type, entry->name);
2085               // The IDs are guaranteed to exist.
2086               options_.stable_id_map[std::move(name)] = entry->id.value();
2087             }
2088           }
2089         }
2090 
2091         if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
2092                                     options_.resource_id_map_path.value())) {
2093           return 1;
2094         }
2095       }
2096     } else {
2097       // Static libs are merged with other apps, and ID collisions are bad, so
2098       // verify that
2099       // no IDs have been set.
2100       if (!VerifyNoIdsSet()) {
2101         return 1;
2102       }
2103     }
2104 
2105     // Add the names to mangle based on our source merge earlier.
2106     context_->SetNameManglerPolicy(
2107         NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
2108 
2109     // Add our table to the symbol table.
2110     context_->GetExternalSymbols()->PrependSource(
2111         util::make_unique<ResourceTableSymbolSource>(&final_table_));
2112 
2113     // Workaround for pre-O runtime that would treat negative resource IDs
2114     // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2115     // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2116     // are just identifiers.
2117     if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2118       if (context_->IsVerbose()) {
2119         context_->GetDiagnostics()->Note(android::DiagMessage()
2120                                          << "enabling pre-O feature split ID rewriting");
2121       }
2122       context_->GetExternalSymbols()->SetDelegate(
2123           util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2124     }
2125 
2126     // Before we process anything, remove the resources whose default values don't exist.
2127     // We want to force any references to these to fail the build.
2128     if (!options_.no_resource_removal) {
2129       if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
2130         context_->GetDiagnostics()->Error(android::DiagMessage()
2131                                           << "failed removing resources with no defaults");
2132         return 1;
2133       }
2134     }
2135 
2136     ReferenceLinker linker;
2137     if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
2138       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
2139       return 1;
2140     }
2141 
2142     if (context_->GetPackageType() == PackageType::kStaticLib) {
2143       if (!options_.products.empty()) {
2144         context_->GetDiagnostics()->Warn(android::DiagMessage()
2145                                          << "can't select products when building static library");
2146       }
2147     } else {
2148       ProductFilter product_filter(options_.products, /* remove_default_config_values = */ false);
2149       if (!product_filter.Consume(context_, &final_table_)) {
2150         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
2151         return 1;
2152       }
2153     }
2154 
2155     if (!options_.no_auto_version) {
2156       AutoVersioner versioner;
2157       if (!versioner.Consume(context_, &final_table_)) {
2158         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
2159         return 1;
2160       }
2161     }
2162 
2163     if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
2164       if (context_->IsVerbose()) {
2165         context_->GetDiagnostics()->Note(android::DiagMessage()
2166                                          << "collapsing resource versions for minimum SDK "
2167                                          << context_->GetMinSdkVersion());
2168       }
2169 
2170       VersionCollapser collapser;
2171       if (!collapser.Consume(context_, &final_table_)) {
2172         return 1;
2173       }
2174     }
2175 
2176     if (!options_.exclude_configs_.empty()) {
2177       std::vector<ConfigDescription> excluded_configs;
2178 
2179       for (auto& config_string : options_.exclude_configs_) {
2180         TRACE_NAME("ConfigDescription::Parse");
2181         ConfigDescription config_description;
2182 
2183         if (!ConfigDescription::Parse(config_string, &config_description)) {
2184           context_->GetDiagnostics()->Error(
2185               android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
2186           return 1;
2187         }
2188 
2189         excluded_configs.push_back(config_description);
2190       }
2191 
2192       ResourceExcluder excluder(excluded_configs);
2193       if (!excluder.Consume(context_, &final_table_)) {
2194         context_->GetDiagnostics()->Error(android::DiagMessage()
2195                                           << "failed excluding configurations");
2196         return 1;
2197       }
2198     }
2199 
2200     if (!options_.no_resource_deduping) {
2201       ResourceDeduper deduper;
2202       if (!deduper.Consume(context_, &final_table_)) {
2203         context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
2204         return 1;
2205       }
2206     }
2207 
2208     proguard::KeepSet proguard_keep_set =
2209         proguard::KeepSet(options_.generate_conditional_proguard_rules);
2210     proguard::KeepSet proguard_main_dex_keep_set;
2211 
2212     if (context_->GetPackageType() == PackageType::kStaticLib) {
2213       if (options_.table_splitter_options.config_filter != nullptr ||
2214           !options_.table_splitter_options.preferred_densities.empty()) {
2215         context_->GetDiagnostics()->Warn(android::DiagMessage()
2216                                          << "can't strip resources when building static library");
2217       }
2218     } else {
2219       // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2220       // equal to the minSdk.
2221       const size_t origConstraintSize = options_.split_constraints.size();
2222       options_.split_constraints =
2223           AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
2224 
2225       if (origConstraintSize != options_.split_constraints.size()) {
2226         context_->GetDiagnostics()->Warn(android::DiagMessage()
2227                                          << "requested to split resources prior to min sdk of "
2228                                          << context_->GetMinSdkVersion());
2229       }
2230       TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
2231       if (!table_splitter.VerifySplitConstraints(context_)) {
2232         return 1;
2233       }
2234       table_splitter.SplitTable(&final_table_);
2235 
2236       // Now we need to write out the Split APKs.
2237       auto path_iter = options_.split_paths.begin();
2238       auto split_constraints_iter = options_.split_constraints.begin();
2239       for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
2240         if (context_->IsVerbose()) {
2241           context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
2242                                            << "generating split with configurations '"
2243                                            << util::Joiner(split_constraints_iter->configs, ", ")
2244                                            << "'");
2245         }
2246 
2247         std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
2248         if (!archive_writer) {
2249           context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
2250           return 1;
2251         }
2252 
2253         // Generate an AndroidManifest.xml for each split.
2254         std::unique_ptr<xml::XmlResource> split_manifest =
2255             GenerateSplitManifest(app_info_, *split_constraints_iter);
2256 
2257         XmlReferenceLinker linker(&final_table_);
2258         if (!linker.Consume(context_, split_manifest.get())) {
2259           context_->GetDiagnostics()->Error(android::DiagMessage()
2260                                             << "failed to create Split AndroidManifest.xml");
2261           return 1;
2262         }
2263 
2264         if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2265                       split_table.get())) {
2266           return 1;
2267         }
2268 
2269         ++path_iter;
2270         ++split_constraints_iter;
2271       }
2272     }
2273 
2274     // Start writing the base APK.
2275     std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
2276     if (!archive_writer) {
2277       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
2278       return 1;
2279     }
2280 
2281     bool error = false;
2282     {
2283       // AndroidManifest.xml has no resource name, but the CallSite is built from the name
2284       // (aka, which package the AndroidManifest.xml is coming from).
2285       // So we give it a package name so it can see local resources.
2286       manifest_xml->file.name.package = context_->GetCompilationPackage();
2287 
2288       XmlReferenceLinker manifest_linker(&final_table_);
2289       if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
2290         if (options_.generate_proguard_rules_path &&
2291             !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
2292           error = true;
2293         }
2294 
2295         if (options_.generate_main_dex_proguard_rules_path &&
2296             !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
2297                                                        &proguard_main_dex_keep_set, true)) {
2298           error = true;
2299         }
2300 
2301         if (options_.generate_java_class_path) {
2302           // The FeatureFlagsFilter may remove <permission> and <permission-group> elements that
2303           // generate constants in the Manifest Java file. While we want those permissions and
2304           // permission groups removed in the SDK (i.e., if a feature flag is disabled), the
2305           // constants should still remain so that code referencing it (e.g., within a feature
2306           // flag check) will still compile. Therefore we use the manifest XML before the filter.
2307           if (!WriteManifestJavaFile(pre_flags_filter_manifest_xml.get())) {
2308             error = true;
2309           }
2310         }
2311 
2312         if (options_.no_xml_namespaces) {
2313           // PackageParser will fail if URIs are removed from
2314           // AndroidManifest.xml.
2315           XmlNamespaceRemover namespace_remover(true /* keepUris */);
2316           if (!namespace_remover.Consume(context_, manifest_xml.get())) {
2317             error = true;
2318           }
2319         }
2320       } else {
2321         error = true;
2322       }
2323     }
2324 
2325     if (error) {
2326       context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
2327       return 1;
2328     }
2329 
2330     if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2331       return 1;
2332     };
2333 
2334     if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2335       return 1;
2336     }
2337 
2338     if (!CopyAssetsDirsToApk(archive_writer.get())) {
2339       return 1;
2340     }
2341 
2342     if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
2343       if (!GenerateJavaClasses()) {
2344         return 1;
2345       }
2346     }
2347 
2348     if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
2349       return 1;
2350     }
2351 
2352     if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2353                            proguard_main_dex_keep_set)) {
2354       return 1;
2355     }
2356     return 0;
2357   }
2358 
2359  private:
2360   LinkOptions options_;
2361   LinkContext* context_;
2362   ResourceTable final_table_;
2363 
2364   AppInfo app_info_;
2365 
2366   std::unique_ptr<TableMerger> table_merger_;
2367 
2368   // A pointer to the FileCollection representing the filesystem (not archives).
2369   std::unique_ptr<io::FileCollection> file_collection_;
2370 
2371   // A vector of IFileCollections. This is mainly here to retain ownership of the
2372   // collections.
2373   std::vector<std::unique_ptr<io::IFileCollection>> collections_;
2374 
2375   // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2376   std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2377 
2378   // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2379   std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
2380 
2381   // The set of shared libraries being used, mapping their assigned package ID to package name.
2382   std::map<size_t, std::string> shared_libs_;
2383 
2384   // The package name of the base application, if it is included.
2385   std::optional<std::string> included_feature_base_;
2386 };
2387 
Action(const std::vector<std::string> & args)2388 int LinkCommand::Action(const std::vector<std::string>& args) {
2389   TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
2390   LinkContext context(diag_);
2391 
2392   // Expand all argument-files passed into the command line. These start with '@'.
2393   std::vector<std::string> arg_list;
2394   for (const std::string& arg : args) {
2395     if (util::StartsWith(arg, "@")) {
2396       const std::string path = arg.substr(1, arg.size() - 1);
2397       std::string error;
2398       if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2399         context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2400         return 1;
2401       }
2402     } else {
2403       arg_list.push_back(arg);
2404     }
2405   }
2406 
2407   // Expand all argument-files passed to -R.
2408   for (const std::string& arg : overlay_arg_list_) {
2409     if (util::StartsWith(arg, "@")) {
2410       const std::string path = arg.substr(1, arg.size() - 1);
2411       std::string error;
2412       if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
2413         context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2414         return 1;
2415       }
2416     } else {
2417       options_.overlay_files.push_back(arg);
2418     }
2419   }
2420 
2421   if (verbose_) {
2422     context.SetVerbose(verbose_);
2423   }
2424 
2425   if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
2426     context.GetDiagnostics()
2427         ->Error(android::DiagMessage()
2428                 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
2429     return 1;
2430   }
2431 
2432   if (shared_lib_ && options_.private_symbols) {
2433     // If a shared library styleable in a public R.java uses a private attribute, attempting to
2434     // reference the private attribute within the styleable array will cause a link error because
2435     // the private attribute will not be emitted in the public R.java.
2436     context.GetDiagnostics()->Error(android::DiagMessage()
2437                                     << "--shared-lib cannot currently be used in combination with"
2438                                     << " --private-symbols");
2439     return 1;
2440   }
2441 
2442   if (options_.merge_only && !static_lib_) {
2443     context.GetDiagnostics()
2444         ->Error(android::DiagMessage()
2445                 << "the --merge-only flag can be only used when building a static library");
2446     return 1;
2447   }
2448   if (options_.use_sparse_encoding) {
2449     options_.table_flattener_options.sparse_entries = SparseEntriesMode::Enabled;
2450   }
2451 
2452   // The default build type.
2453   context.SetPackageType(PackageType::kApp);
2454   context.SetPackageId(kAppPackageId);
2455 
2456   if (shared_lib_) {
2457     context.SetPackageType(PackageType::kSharedLib);
2458     context.SetPackageId(0x00);
2459   } else if (static_lib_) {
2460     context.SetPackageType(PackageType::kStaticLib);
2461     options_.output_format = OutputFormat::kProto;
2462   } else if (proto_format_) {
2463     options_.output_format = OutputFormat::kProto;
2464   }
2465 
2466   if (package_id_) {
2467     if (context.GetPackageType() != PackageType::kApp) {
2468       context.GetDiagnostics()->Error(
2469           android::DiagMessage() << "can't specify --package-id when not building a regular app");
2470       return 1;
2471     }
2472 
2473     const std::optional<uint32_t> maybe_package_id_int =
2474         ResourceUtils::ParseInt(package_id_.value());
2475     if (!maybe_package_id_int) {
2476       context.GetDiagnostics()->Error(android::DiagMessage()
2477                                       << "package ID '" << package_id_.value()
2478                                       << "' is not a valid integer");
2479       return 1;
2480     }
2481 
2482     const uint32_t package_id_int = maybe_package_id_int.value();
2483     if (package_id_int > std::numeric_limits<uint8_t>::max()
2484         || package_id_int == kFrameworkPackageId
2485         || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
2486       context.GetDiagnostics()->Error(
2487           android::DiagMessage() << StringPrintf(
2488               "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2489       return 1;
2490     }
2491     context.SetPackageId(static_cast<uint8_t>(package_id_int));
2492   }
2493 
2494   // Populate the set of extra packages for which to generate R.java.
2495   for (std::string& extra_package : extra_java_packages_) {
2496     // A given package can actually be a colon separated list of packages.
2497     for (StringPiece package : util::Split(extra_package, ':')) {
2498       options_.extra_java_packages.emplace(package);
2499     }
2500   }
2501 
2502   if (product_list_) {
2503     for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
2504       if (product != "" && product != "default") {
2505         options_.products.emplace(product);
2506       }
2507     }
2508   }
2509 
2510   std::unique_ptr<IConfigFilter> filter;
2511   if (!configs_.empty()) {
2512     filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
2513     if (filter == nullptr) {
2514       return 1;
2515     }
2516     options_.table_splitter_options.config_filter = filter.get();
2517   }
2518 
2519   if (preferred_density_) {
2520     std::optional<uint16_t> density =
2521         ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
2522     if (!density) {
2523       return 1;
2524     }
2525     options_.table_splitter_options.preferred_densities.push_back(density.value());
2526   }
2527 
2528   // Parse the split parameters.
2529   for (const std::string& split_arg : split_args_) {
2530     options_.split_paths.push_back({});
2531     options_.split_constraints.push_back({});
2532     if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2533         &options_.split_constraints.back())) {
2534       return 1;
2535     }
2536   }
2537 
2538   // Parse the feature flag values. An argument that starts with '@' points to a file to read flag
2539   // values from.
2540   std::vector<std::string> all_feature_flags_args;
2541   for (const std::string& arg : feature_flags_args_) {
2542     if (util::StartsWith(arg, "@")) {
2543       const std::string path = arg.substr(1, arg.size() - 1);
2544       std::string error;
2545       if (!file::AppendArgsFromFile(path, &all_feature_flags_args, &error)) {
2546         context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2547         return 1;
2548       }
2549     } else {
2550       all_feature_flags_args.push_back(arg);
2551     }
2552   }
2553 
2554   for (const std::string& arg : all_feature_flags_args) {
2555     if (!ParseFeatureFlagsParameter(arg, context.GetDiagnostics(), &options_.feature_flag_values)) {
2556       return 1;
2557     }
2558   }
2559 
2560   if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2561     if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2562         &options_.stable_id_map)) {
2563       return 1;
2564     }
2565   }
2566 
2567   if (no_compress_regex) {
2568     std::string regex = no_compress_regex.value();
2569     if (util::StartsWith(regex, "@")) {
2570       const std::string path = regex.substr(1, regex.size() -1);
2571       std::string error;
2572       if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2573         context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2574         return 1;
2575       }
2576     } else {
2577       options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2578     }
2579   }
2580 
2581   // Populate some default no-compress extensions that are already compressed.
2582   options_.extensions_to_not_compress.insert({
2583       // Image extensions
2584       ".jpg", ".jpeg", ".png", ".gif", ".webp",
2585       // Audio extensions
2586       ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2587       ".xmf", ".amr", ".awb",
2588       // Audio/video extensions
2589       ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2590       ".webm", ".mkv"});
2591 
2592   // Turn off auto versioning for static-libs.
2593   if (context.GetPackageType() == PackageType::kStaticLib) {
2594     options_.no_auto_version = true;
2595     options_.no_version_vectors = true;
2596     options_.no_version_transitions = true;
2597   }
2598 
2599   Linker cmd(&context, options_);
2600   return cmd.Run(arg_list);
2601 }
2602 
2603 }  // namespace aapt
2604