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