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