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