blob: aacf9199239e2aa2f59d0f766af59c1bce53ba94 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
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
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
20
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050021#include <algorithm>
Jeremy Meyer56f36e82022-05-20 20:35:42 +000022#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
Adam Lesinski1ab598f2015-08-14 14:26:04 -070027#include "AppInfo.h"
28#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070029#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080031#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070032#include "ResourceValues.h"
33#include "ValueVisitor.h"
Jeremy Meyer56f36e82022-05-20 20:35:42 +000034#include "android-base/errors.h"
35#include "android-base/expected.h"
36#include "android-base/file.h"
37#include "android-base/stringprintf.h"
38#include "androidfw/IDiagnostics.h"
39#include "androidfw/Locale.h"
40#include "androidfw/StringPiece.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070041#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070042#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080043#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080044#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070046#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070047#include "format/binary/TableFlattener.h"
48#include "format/binary/XmlFlattener.h"
49#include "format/proto/ProtoDeserialize.h"
50#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070051#include "io/BigBufferStream.h"
52#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070054#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080055#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070056#include "java/JavaClassGenerator.h"
57#include "java/ManifestClassGenerator.h"
58#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070060#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080061#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080062#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080063#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070065#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080066#include "optimize/ResourceDeduper.h"
67#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "process/IResourceTableConsumer.h"
69#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080070#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080071#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080073#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070075using ::aapt::io::FileInputStream;
MÃ¥rten Kongstad24c9aa62018-06-20 08:46:41 +020076using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070077using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070078using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070079using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070080using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070081
Adam Lesinski1ab598f2015-08-14 14:26:04 -070082namespace aapt {
83
Ryan Mitchell9634efb2021-03-19 14:53:17 -070084namespace {
85
86expected<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
Ryan Mitchell22dc5312020-06-01 12:17:07 -070097constexpr uint8_t kAndroidPackageId = 0x01;
98
Adam Lesinski64587af2016-02-18 18:33:06 -080099class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700100 public:
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000101 explicit LinkContext(android::IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100102 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700103 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104
Adam Lesinskib522f042017-04-21 16:57:59 -0700105 PackageType GetPackageType() override {
106 return package_type_;
107 }
108
109 void SetPackageType(PackageType type) {
110 package_type_ = type;
111 }
112
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000113 android::IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100114 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 NameMangler* GetNameMangler() override {
118 return &name_mangler_;
119 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700121 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
122 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800124
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 const std::string& GetCompilationPackage() override {
126 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700128
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700129 void SetCompilationPackage(StringPiece package_name) {
130 compilation_package_ = std::string(package_name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 uint8_t GetPackageId() override {
134 return package_id_;
135 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetPackageId(uint8_t id) {
138 package_id_ = id;
139 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800140
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700141 SymbolTable* GetExternalSymbols() override {
142 return &symbols_;
143 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800144
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 bool IsVerbose() override {
146 return verbose_;
147 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 void SetVerbose(bool val) {
150 verbose_ = val;
151 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800152
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700153 int GetMinSdkVersion() override {
154 return min_sdk_version_;
155 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700156
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700157 void SetMinSdkVersion(int minSdk) {
158 min_sdk_version_ = minSdk;
159 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700160
Udam Sainib228df32019-06-18 16:50:34 -0700161 const std::set<std::string>& GetSplitNameDependencies() override {
162 return split_name_dependencies_;
163 }
164
165 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
166 split_name_dependencies_ = split_name_dependencies;
167 }
168
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700170 DISALLOW_COPY_AND_ASSIGN(LinkContext);
171
Adam Lesinskib522f042017-04-21 16:57:59 -0700172 PackageType package_type_ = PackageType::kApp;
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000173 android::IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700174 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;
Udam Sainib228df32019-06-18 16:50:34 -0700180 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700181};
182
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700183// 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.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800191//
192// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700193class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
194 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800195 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700196 }
197
198 virtual ~FeatureSplitSymbolTableDelegate() = default;
199
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.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000210 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700211 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.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000219 context_->GetDiagnostics()->Error(android::DiagMessage()
220 << "Failed to rewrite " << name
221 << " for pre-O feature split support");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700222 return {};
223 }
224
225 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000226 context_->GetDiagnostics()->Note(android::DiagMessage()
227 << "rewriting " << name << " (" << *id << ") -> ("
228 << rewritten_id << ")");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700229 }
230
231 *id = rewritten_id;
232 }
233 }
234 return symbol;
235 }
236
237 private:
238 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
239
240 IAaptContext* context_;
241};
242
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700243static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path,
244 bool keep_raw_values, bool utf16, OutputFormat format,
245 IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800246 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700247 if (context->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000248 context->GetDiagnostics()->Note(android::DiagMessage(path)
249 << "writing to archive (keep_raw_values="
250 << (keep_raw_values ? "true" : "false") << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700251 }
252
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700253 switch (format) {
254 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000255 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700256 XmlFlattenerOptions options = {};
257 options.keep_raw_values = keep_raw_values;
258 options.use_utf16 = utf16;
259 XmlFlattener flattener(&buffer, options);
260 if (!flattener.Consume(context, &xml_res)) {
261 return false;
262 }
263
264 io::BigBufferInputStream input_stream(&buffer);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700265 return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
266 writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700267 } break;
268
269 case OutputFormat::kProto: {
270 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800271 // Strip whitespace text nodes from tha AndroidManifest.xml
272 SerializeXmlOptions options;
273 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700274 SerializeXmlResourceToPb(xml_res, &pb_node);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700275 return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700276 } break;
277 }
278 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800279}
280
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700281// Inflates an XML file from the source path.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000282static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
283 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800284 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700285 FileInputStream fin(path);
286 if (fin.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000287 diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700288 return {};
289 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000290 return xml::Inflate(&fin, diag, android::Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800291}
292
Adam Lesinski355f2852016-02-13 20:26:45 -0800293struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700294 bool no_auto_version = false;
295 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900296 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700297 bool no_xml_namespaces = false;
298 bool keep_raw_values = false;
299 bool do_not_compress_anything = false;
300 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100301 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700302 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700303 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700304 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800305};
306
Adam Lesinskic744ae82017-05-17 19:28:38 -0700307// A sampling of public framework resource IDs.
308struct R {
309 struct attr {
310 enum : uint32_t {
311 paddingLeft = 0x010100d6u,
312 paddingRight = 0x010100d8u,
313 paddingHorizontal = 0x0101053du,
314
315 paddingTop = 0x010100d7u,
316 paddingBottom = 0x010100d9u,
317 paddingVertical = 0x0101053eu,
318
319 layout_marginLeft = 0x010100f7u,
320 layout_marginRight = 0x010100f9u,
321 layout_marginHorizontal = 0x0101053bu,
322
323 layout_marginTop = 0x010100f8u,
324 layout_marginBottom = 0x010100fau,
325 layout_marginVertical = 0x0101053cu,
326 };
327 };
328};
329
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700330template <typename T>
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700331uint32_t GetCompressionFlags(StringPiece str, T options) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700332 if (options.do_not_compress_anything) {
333 return 0;
334 }
335
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700336 if (options.regex_to_not_compress &&
337 std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700338 return 0;
339 }
340
341 for (const std::string& extension : options.extensions_to_not_compress) {
342 if (util::EndsWith(str, extension)) {
343 return 0;
344 }
345 }
346 return ArchiveEntry::kCompress;
347}
348
Adam Lesinski355f2852016-02-13 20:26:45 -0800349class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700350 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700351 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700352 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800353
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700354 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800355
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700356 private:
357 struct FileOperation {
358 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700359
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700361 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700362
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700363 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700364 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700365
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700366 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700367 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700368
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700370 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700371 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800372
Adam Lesinskic744ae82017-05-17 19:28:38 -0700373 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
374 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800375
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376 ResourceFileFlattenerOptions options_;
377 IAaptContext* context_;
378 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700379 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800380};
381
Adam Lesinskic744ae82017-05-17 19:28:38 -0700382ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
383 IAaptContext* context, proguard::KeepSet* keep_set)
384 : options_(options), context_(context), keep_set_(keep_set) {
385 SymbolTable* symm = context_->GetExternalSymbols();
386
387 // Build up the rules for degrading newer attributes to older ones.
388 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
389 // generated from the attribute definitions themselves (b/62028956).
390 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
391 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800392 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
393 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 };
395 rules_[R::attr::paddingHorizontal] =
396 util::make_unique<DegradeToManyRule>(std::move(replacements));
397 }
398
399 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
400 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800401 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
402 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700403 };
404 rules_[R::attr::paddingVertical] =
405 util::make_unique<DegradeToManyRule>(std::move(replacements));
406 }
407
408 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
409 std::vector<ReplacementAttr> replacements{
410 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800411 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800413 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700414 };
415 rules_[R::attr::layout_marginHorizontal] =
416 util::make_unique<DegradeToManyRule>(std::move(replacements));
417 }
418
419 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
420 std::vector<ReplacementAttr> replacements{
421 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800422 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800424 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425 };
426 rules_[R::attr::layout_marginVertical] =
427 util::make_unique<DegradeToManyRule>(std::move(replacements));
428 }
429}
430
Adam Lesinskibb94f322017-07-12 07:41:55 -0700431static bool IsTransitionElement(const std::string& name) {
432 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
433 name == "changeImageTransform" || name == "changeTransform" ||
434 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
435 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
436 name == "transitionManager";
437}
438
439static bool IsVectorElement(const std::string& name) {
440 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800441 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
442 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700443}
444
Adam Lesinskic744ae82017-05-17 19:28:38 -0700445template <typename T>
446std::vector<T> make_singleton_vec(T&& val) {
447 std::vector<T> vec;
448 vec.emplace_back(std::forward<T>(val));
449 return vec;
450}
451
452std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
453 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800454 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700455 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000456 const android::Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700457
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700458 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000459 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700460 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700461 }
462
Adam Lesinski00451162017-10-03 07:44:08 -0700463 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
464 // that existing projects have out-of-date references which pass compilation.
465 xml::StripAndroidStudioAttributes(doc->root.get());
466
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700467 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100468 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700469 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700470 }
471
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700472 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700473 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 }
475
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700476 if (options_.no_xml_namespaces) {
477 XmlNamespaceRemover namespace_remover;
478 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700479 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800480 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700481 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800482
Adam Lesinskibb94f322017-07-12 07:41:55 -0700483 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700484 return make_singleton_vec(std::move(file_op->xml_to_flatten));
485 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700486
Adam Lesinskibb94f322017-07-12 07:41:55 -0700487 if (options_.no_version_vectors || options_.no_version_transitions) {
488 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700489 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700490 if (el && el->namespace_uri.empty()) {
491 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
492 (options_.no_version_transitions && IsTransitionElement(el->name))) {
493 return make_singleton_vec(std::move(file_op->xml_to_flatten));
494 }
495 }
496 }
497
Adam Lesinskic744ae82017-05-17 19:28:38 -0700498 const ConfigDescription& config = file_op->config;
499 ResourceEntry* entry = file_op->entry;
500
501 XmlCompatVersioner xml_compat_versioner(&rules_);
502 const util::Range<ApiVersion> api_range{config.sdkVersion,
503 FindNextApiVersionForConfig(entry, config)};
504 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800505}
506
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800507ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
508 switch (format) {
509 case OutputFormat::kApk:
510 return ResourceFile::Type::kBinaryXml;
511 case OutputFormat::kProto:
512 return ResourceFile::Type::kProtoXml;
513 }
514 LOG_ALWAYS_FATAL("unreachable");
515 return ResourceFile::Type::kUnknown;
516}
517
Ryan Mitchell70f79722018-08-13 07:37:24 -0700518static auto kDrawableVersions = std::map<std::string, ApiVersion>{
519 { "adaptive-icon" , SDK_O },
520};
521
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700522bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800523 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700525 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800526
Adam Koskidc21dea2017-07-21 10:55:27 -0700527 proguard::CollectResourceReferences(context_, table, keep_set_);
528
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700530 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
531
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700532 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700533 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700534 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700535 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800536
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700537 // Populate the queue with all files in the ResourceTable.
538 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700539 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700540 // WARNING! Do not insert or remove any resources while executing in this scope. It will
541 // corrupt the iteration order.
542
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700543 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700544 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700545 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700547
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 if (!file) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000550 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700552 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700553 }
554
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700555 FileOperation file_op;
556 file_op.entry = entry.get();
557 file_op.dst_path = *file_ref->path;
558 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700559 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000561 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700562 (file_ref->type == ResourceFile::Type::kBinaryXml ||
563 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700564 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 if (!data) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000566 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 << "failed to open file");
568 return false;
569 }
570
Adam Lesinski00451162017-10-03 07:44:08 -0700571 if (file_ref->type == ResourceFile::Type::kProtoXml) {
572 pb::XmlNode pb_xml_node;
573 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000574 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700575 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700576 return false;
577 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700578
Adam Lesinski00451162017-10-03 07:44:08 -0700579 std::string error;
580 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
581 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000582 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700583 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700584 return false;
585 }
586 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700587 std::string error_str;
588 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700589 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000590 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700591 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700592 return false;
593 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700594 }
595
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800596 // Update the type that this file will be written as.
597 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
598
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700599 file_op.xml_to_flatten->file.config = config_value->config;
600 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000601 file_op.xml_to_flatten->file.name =
602 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700604
605 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
606 // else we end up copying the string in the std::make_pair() method,
607 // then creating a StringPiece from the copy, which would cause us
608 // to end up referencing garbage in the map.
609 const StringPiece entry_name(entry->name);
610 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
611 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 }
613 }
614
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700616 for (auto& map_entry : config_sorted_files) {
617 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700618 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700620 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700621 // Check minimum sdk versions supported for drawables
622 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
623 if (drawable_entry != kDrawableVersions.end()) {
624 if (drawable_entry->second > context_->GetMinSdkVersion()
625 && drawable_entry->second > config.sdkVersion) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000626 context_->GetDiagnostics()->Error(
627 android::DiagMessage(file_op.xml_to_flatten->file.source)
628 << "<" << drawable_entry->first << "> elements "
629 << "require a sdk version of at least " << (int16_t)drawable_entry->second);
Ryan Mitchell70f79722018-08-13 07:37:24 -0700630 error = true;
631 continue;
632 }
633 }
634
Adam Lesinskic744ae82017-05-17 19:28:38 -0700635 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
636 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700637 if (versioned_docs.empty()) {
638 error = true;
639 continue;
640 }
641
Adam Lesinskic744ae82017-05-17 19:28:38 -0700642 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
643 std::string dst_path = file_op.dst_path;
644 if (doc->file.config != file_op.config) {
645 // Only add the new versioned configurations.
646 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000647 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
Adam Lesinskic744ae82017-05-17 19:28:38 -0700648 << "auto-versioning resource from config '"
649 << config << "' -> '" << doc->file.config << "'");
650 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700651
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800652 const ResourceFile& file = doc->file;
653 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
654
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700655 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800656 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
657 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700658
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800659 // Update the output format of this XML file.
660 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700661 bool result = table->AddResource(NewResourceBuilder(file.name)
662 .SetValue(std::move(file_ref), file.config)
663 .SetAllowMangled(true)
664 .Build(),
665 context_->GetDiagnostics());
666 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700667 return false;
668 }
669 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700670
671 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
672 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 }
674 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700675 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700676 GetCompressionFlags(file_op.dst_path, options_),
677 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700678 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700680 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 }
682 return !error;
683}
684
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000685static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700686 const std::unordered_map<ResourceName, ResourceId>& id_map,
687 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800688 io::FileOutputStream fout(id_map_path);
689 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000690 diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 return false;
692 }
693
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800694 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 const ResourceName& name = entry.first;
697 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800698 printer.Print(name.to_string());
699 printer.Print(" = ");
700 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800702 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800704 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000705 diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 return false;
707 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 return true;
709}
710
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000711static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700712 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700714 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000715 diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 out_id_map->clear();
720 size_t line_no = 0;
721 for (StringPiece line : util::Tokenize(content, '\n')) {
722 line_no++;
723 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 if (line.empty()) {
725 continue;
726 }
727
728 auto iter = std::find(line.begin(), line.end(), '=');
729 if (iter == line.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000730 diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 return false;
732 }
733
734 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700735 StringPiece res_name_str =
736 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
737 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000738 diag->Error(android::DiagMessage(android::Source(path, line_no))
739 << "invalid resource name '" << res_name_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 return false;
741 }
742
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700743 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
744 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700745 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700746
Ryan Mitchell4382e442021-07-14 12:53:01 -0700747 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700748 if (!maybe_id) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000749 diag->Error(android::DiagMessage(android::Source(path, line_no))
750 << "invalid resource ID '" << res_id_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700751 return false;
752 }
753
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700754 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700755 }
756 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700757}
758
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700759class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700760 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700761 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700762 : options_(options),
763 context_(context),
764 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700765 file_collection_(util::make_unique<io::FileCollection>()) {
766 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700767
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800768 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800769 using namespace android;
770
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000771 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
772 // we're looking for the first attribute resource in the system package.
773 android::ApkAssetsCookie cookie;
774 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
775 cookie = value->cookie;
776 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800777 // No Framework assets loaded. Not a failure.
778 return;
779 }
780
781 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800782 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800783 if (manifest == nullptr) {
784 // No errors.
785 return;
786 }
787
788 std::string error;
789 std::unique_ptr<xml::XmlResource> manifest_xml =
790 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
791 if (manifest_xml == nullptr) {
792 // No errors.
793 return;
794 }
795
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700796 if (!options_.manifest_fixer_options.compile_sdk_version) {
797 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
798 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700799 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700800 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
801 switch (prim->value.dataType) {
802 case Res_value::TYPE_INT_DEC:
803 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
804 break;
805 case Res_value::TYPE_INT_HEX:
806 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
807 break;
808 default:
809 break;
810 }
811 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
812 compile_sdk_version = *str->value;
813 } else {
814 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800815 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800816 }
817 }
818
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700819 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
820 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
821 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700822 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700823 options_.manifest_fixer_options.compile_sdk_version_codename;
824 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
825 compile_sdk_version_codename = *str->value;
826 } else {
827 compile_sdk_version_codename = attr->value;
828 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800829 }
830 }
831 }
832
Adam Lesinski8780eb62017-10-31 17:44:39 -0700833 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800834 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700835 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800836 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700837 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700838 for (const std::string& path : options_.include_paths) {
839 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000840 context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700841 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700842
Adam Lesinski8780eb62017-10-31 17:44:39 -0700843 std::string error;
844 auto zip_collection = io::ZipFileCollection::Create(path, &error);
845 if (zip_collection == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000846 context_->GetDiagnostics()->Error(android::DiagMessage()
847 << "failed to open APK: " << error);
Adam Lesinski8780eb62017-10-31 17:44:39 -0700848 return false;
849 }
850
851 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
852 // Load this as a static library include.
853 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000854 android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
Adam Lesinski8780eb62017-10-31 17:44:39 -0700855 if (static_apk == nullptr) {
856 return false;
857 }
858
Adam Lesinskib522f042017-04-21 16:57:59 -0700859 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800860 // Can't include static libraries when not building a static library (they have no IDs
861 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700862 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000863 android::DiagMessage(path)
864 << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700865 return false;
866 }
867
Adam Lesinski8780eb62017-10-31 17:44:39 -0700868 ResourceTable* table = static_apk->GetResourceTable();
869
870 // If we are using --no-static-lib-packages, we need to rename the package of this table to
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700871 // our compilation package so the symbol package name does not get mangled into the entry
872 // name.
873 if (options_.no_static_lib_packages && !table->packages.empty()) {
874 auto lib_package_result = GetStaticLibraryPackage(table);
875 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000876 context_->GetDiagnostics()->Error(android::DiagMessage(path)
877 << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800878 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700880 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700881 }
882
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700883 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700884 util::make_unique<ResourceTableSymbolSource>(table));
885 static_library_includes_.push_back(std::move(static_apk));
886 } else {
887 if (!asset_source->AddAssetPath(path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000888 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinski8780eb62017-10-31 17:44:39 -0700889 << "failed to load include path " << path);
890 return false;
891 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 }
893 }
894
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800895 // Capture the shared libraries so that the final resource table can be properly flattened
896 // with support for shared libraries.
897 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700898 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800899 // Capture the included base feature package.
900 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800901 } else if (entry.first == kFrameworkPackageId) {
902 // Try to embed which version of the framework we're compiling against.
903 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
904 // when linking our synthesized 'android:compileSdkVersion' attribute.
905 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
906 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
907 if (symbol != nullptr && symbol->is_public) {
908 // The symbol is present and public, extract the android:versionName and
909 // android:versionCode from the framework AndroidManifest.xml.
910 ExtractCompileSdkVersions(asset_source->GetAssetManager());
911 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700912 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700913 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800914 }
915 }
916
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700917 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 return true;
919 }
920
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000921 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
922 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800923 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800925 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
926 if (manifest_el == nullptr) {
927 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800929
930 AppInfo app_info;
931
932 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000933 diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800934 return {};
935 }
936
937 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
938 if (!package_attr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000939 diag->Error(android::DiagMessage(xml_res->file.source)
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800940 << "<manifest> must have a 'package' attribute");
941 return {};
942 }
943 app_info.package = package_attr->value;
944
945 if (xml::Attribute* version_code_attr =
946 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700947 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800948 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000949 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800950 << "invalid android:versionCode '" << version_code_attr->value << "'");
951 return {};
952 }
953 app_info.version_code = maybe_code.value();
954 }
955
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700956 if (xml::Attribute* version_code_major_attr =
957 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700958 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700959 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000960 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
961 << "invalid android:versionCodeMajor '" << version_code_major_attr->value
962 << "'");
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700963 return {};
964 }
965 app_info.version_code_major = maybe_code.value();
966 }
967
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800968 if (xml::Attribute* revision_code_attr =
969 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700970 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800971 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000972 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800973 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
974 return {};
975 }
976 app_info.revision_code = maybe_code.value();
977 }
978
979 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
980 if (!split_name_attr->value.empty()) {
981 app_info.split_name = split_name_attr->value;
982 }
983 }
984
985 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
986 if (xml::Attribute* min_sdk =
987 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700988 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800989 }
990 }
Udam Sainib228df32019-06-18 16:50:34 -0700991
992 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
993 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
994 if (const xml::Attribute* split_name =
995 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
996 if (!split_name->value.empty()) {
997 app_info.split_name_dependencies.insert(split_name->value);
998 }
999 }
1000 }
1001 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -08001002 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001003 }
1004
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001005 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1006 // Postcondition: ResourceTable has only one package left. All others are
1007 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001008 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001009 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001010 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 };
1012
1013 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001014 for (const auto& package : final_table_.packages) {
1015 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 // We have a package that is not related to the one we're building!
1017 for (const auto& type : package->types) {
1018 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001019 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001021 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001023 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001024 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001025 context_->GetDiagnostics()->Warn(
1026 android::DiagMessage(config_value->value->GetSource())
1027 << "generated id '" << res_name << "' for external package '" << package->name
1028 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001030 context_->GetDiagnostics()->Error(
1031 android::DiagMessage(config_value->value->GetSource())
1032 << "defined resource '" << res_name << "' for external package '"
1033 << package->name << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001034 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001035 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001036 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 }
1038 }
1039 }
1040 }
1041
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001042 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1043 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001044 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001045 return !error;
1046 }
1047
1048 /**
1049 * Returns true if no IDs have been set, false otherwise.
1050 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001051 bool VerifyNoIdsSet() {
1052 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 for (const auto& entry : type->entries) {
1055 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001056 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001057 context_->GetDiagnostics()->Error(android::DiagMessage()
1058 << "resource " << res_name << " has ID "
1059 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001060 return false;
1061 }
1062 }
1063 }
1064 }
1065 return true;
1066 }
1067
Josh Houec67cb42022-06-09 19:19:21 +08001068 bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
1069 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1070 // element.
1071 const xml::Element* application = manifest->root->FindChild("", "application");
1072 if (!application) {
1073 return true;
1074 }
1075 const xml::Attribute* localeConfig =
1076 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1077 if (!localeConfig) {
1078 return true;
1079 }
1080
1081 // Deserialize XML from the compiled file
1082 if (localeConfig->compiled_value) {
1083 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1084 const auto localeconfig_entry =
1085 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1086 if (!localeconfig_entry) {
Iurii Makhnoa7ba6b62022-11-11 17:59:57 +00001087 // If locale config is resolved from external symbols - skip validation.
1088 if (context_->GetExternalSymbols()->FindByReference(*localeconfig_reference)) {
1089 return true;
1090 }
Josh Houec67cb42022-06-09 19:19:21 +08001091 context_->GetDiagnostics()->Error(
1092 android::DiagMessage(localeConfig->compiled_value->GetSource())
1093 << "no localeConfig entry");
1094 return false;
1095 }
1096 for (const auto& value : localeconfig_entry->values) {
1097 const FileReference* file_ref = ValueCast<FileReference>(value->value.get());
1098 if (!file_ref) {
1099 context_->GetDiagnostics()->Error(
1100 android::DiagMessage(localeConfig->compiled_value->GetSource())
1101 << "no file reference");
1102 return false;
1103 }
1104 io::IFile* file = file_ref->file;
1105 if (!file) {
1106 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
1107 << "file not found");
1108 return false;
1109 }
1110 std::unique_ptr<io::IData> data = file->OpenAsData();
1111 if (!data) {
1112 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1113 << "failed to open file");
1114 return false;
1115 }
1116 pb::XmlNode pb_xml_node;
1117 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
1118 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1119 << "failed to parse proto XML");
1120 return false;
1121 }
1122
1123 std::string error;
1124 std::unique_ptr<xml::XmlResource> localeConfig_xml =
1125 DeserializeXmlResourceFromPb(pb_xml_node, &error);
1126 if (!localeConfig_xml) {
1127 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1128 << "failed to deserialize proto XML: " << error);
1129 return false;
1130 }
1131 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1132 if (!localeConfig_el) {
1133 diag->Error(android::DiagMessage(file->GetSource()) << "no root tag defined");
1134 return false;
1135 }
1136 if (localeConfig_el->name != "locale-config") {
1137 diag->Error(android::DiagMessage(file->GetSource())
1138 << "invalid element name: " << localeConfig_el->name
1139 << ", expected: locale-config");
1140 return false;
1141 }
1142 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1143 if (child_el->name == "locale") {
1144 if (const xml::Attribute* locale_name_attr =
1145 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1146 const std::string& locale_name = locale_name_attr->value;
1147 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1148 // Start to verify the locale format
1149 ConfigDescription config;
1150 if (!ConfigDescription::Parse(valid_name, &config)) {
1151 diag->Error(android::DiagMessage(file->GetSource())
1152 << "invalid configuration: " << locale_name);
1153 return false;
1154 }
1155 } else {
1156 diag->Error(android::DiagMessage(file->GetSource())
1157 << "the attribute android:name is not found");
1158 return false;
1159 }
1160 } else {
1161 diag->Error(android::DiagMessage(file->GetSource())
1162 << "invalid element name: " << child_el->name << ", expected: locale");
1163 return false;
1164 }
1165 }
1166 }
1167 }
1168 return true;
1169 }
1170
1171 std::string ConvertToBCP47Tag(const std::string& locale) {
1172 std::string bcp47tag = "b+";
1173 bcp47tag += locale;
1174 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1175 return bcp47tag;
1176 }
1177
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001178 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001179 if (options_.output_to_directory) {
1180 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001181 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001182 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001183 }
1184 }
1185
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001186 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001187 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001188 switch (format) {
1189 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001190 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001191 TableFlattener flattener(options_.table_flattener_options, &buffer);
1192 if (!flattener.Consume(context_, table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001193 context_->GetDiagnostics()->Error(android::DiagMessage()
1194 << "failed to flatten resource table");
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001195 return false;
1196 }
1197
1198 io::BigBufferInputStream input_stream(&buffer);
1199 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1200 ArchiveEntry::kAlign, writer);
1201 } break;
1202
1203 case OutputFormat::kProto: {
1204 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001205 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1206 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001207 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1208 ArchiveEntry::kCompress, writer);
1209 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001210 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001211 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212 }
1213
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001214 bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate,
1215 StringPiece out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001216 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001217 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 return true;
1219 }
1220
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001221 std::string out_path;
1222 std::unique_ptr<io::FileOutputStream> fout;
1223 if (options_.generate_java_class_path) {
1224 out_path = options_.generate_java_class_path.value();
1225 file::AppendPath(&out_path, file::PackageToPath(out_package));
1226 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001227 context_->GetDiagnostics()->Error(android::DiagMessage()
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001228 << "failed to create directory '" << out_path << "'");
1229 return false;
1230 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001231
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001232 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001234 fout = util::make_unique<io::FileOutputStream>(out_path);
1235 if (fout->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001236 context_->GetDiagnostics()->Error(android::DiagMessage()
1237 << "failed writing to '" << out_path
1238 << "': " << fout->GetError());
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001239 return false;
1240 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241 }
1242
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001243 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001244 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001245 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1246 if (fout_text->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001247 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001248 << "failed writing to '" << out_text_symbols_path.value()
1249 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001250 return false;
1251 }
1252 }
1253
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001254 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001255 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001256 context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257 return false;
1258 }
1259
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001260 return true;
1261 }
1262
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001263 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001264 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001265 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1266 std::vector<std::string> packages_to_callback;
1267
1268 JavaClassGeneratorOptions template_options;
1269 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1270 template_options.javadoc_annotations = options_.javadoc_annotations;
1271
1272 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1273 template_options.use_final = false;
1274 }
1275
1276 if (context_->GetPackageType() == PackageType::kSharedLib) {
1277 template_options.use_final = false;
1278 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1279 }
1280
1281 const StringPiece actual_package = context_->GetCompilationPackage();
1282 StringPiece output_package = context_->GetCompilationPackage();
1283 if (options_.custom_java_package) {
1284 // Override the output java package to the custom one.
1285 output_package = options_.custom_java_package.value();
1286 }
1287
1288 // Generate the private symbols if required.
1289 if (options_.private_symbols) {
1290 packages_to_callback.push_back(options_.private_symbols.value());
1291
1292 // If we defined a private symbols package, we only emit Public symbols
1293 // to the original package, and private and public symbols to the private package.
1294 JavaClassGeneratorOptions options = template_options;
1295 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1296 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1297 options)) {
1298 return false;
1299 }
1300 }
1301
1302 // Generate copies of the original package R class but with different package names.
1303 // This is to support non-namespaced builds.
1304 for (const std::string& extra_package : options_.extra_java_packages) {
1305 packages_to_callback.push_back(extra_package);
1306
1307 JavaClassGeneratorOptions options = template_options;
1308 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1309 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1310 return false;
1311 }
1312 }
1313
1314 // Generate R classes for each package that was merged (static library).
1315 // Use the actual package's resources only.
1316 for (const std::string& package : table_merger_->merged_packages()) {
1317 packages_to_callback.push_back(package);
1318
1319 JavaClassGeneratorOptions options = template_options;
1320 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1321 if (!WriteJavaFile(&final_table_, package, package, options)) {
1322 return false;
1323 }
1324 }
1325
1326 // Generate the main public R class.
1327 JavaClassGeneratorOptions options = template_options;
1328
1329 // Only generate public symbols if we have a private package.
1330 if (options_.private_symbols) {
1331 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1332 }
1333
1334 if (options.rewrite_callback_options) {
1335 options.rewrite_callback_options.value().packages_to_callback =
1336 std::move(packages_to_callback);
1337 }
1338
1339 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1340 options_.generate_text_symbols_path)) {
1341 return false;
1342 }
1343
1344 return true;
1345 }
1346
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001347 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001348 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001349 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001350 return true;
1351 }
1352
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001353 std::unique_ptr<ClassDefinition> manifest_class =
1354 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001355
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001356 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001357 // Something bad happened, but we already logged it, so exit.
1358 return false;
1359 }
1360
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001361 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001362 // Empty Manifest class, no need to generate it.
1363 return true;
1364 }
1365
1366 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001367 for (const std::string& annotation : options_.javadoc_annotations) {
1368 std::string proper_annotation = "@";
1369 proper_annotation += annotation;
1370 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001371 }
1372
Adam Lesinski0d81f702017-06-27 15:51:09 -07001373 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001374 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001376 std::string out_path = options_.generate_java_class_path.value();
1377 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001380 context_->GetDiagnostics()->Error(android::DiagMessage()
1381 << "failed to create directory '" << out_path << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382 return false;
1383 }
1384
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001385 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001386
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001387 io::FileOutputStream fout(out_path);
1388 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001389 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1390 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001391 return false;
1392 }
1393
Makoto Onukide6e6f22020-06-22 10:17:02 -07001394 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1395 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001396 fout.Flush();
1397
1398 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001399 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1400 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401 return false;
1402 }
1403 return true;
1404 }
1405
Ryan Mitchell4382e442021-07-14 12:53:01 -07001406 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001407 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 if (!out) {
1409 return true;
1410 }
1411
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001412 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001413 io::FileOutputStream fout(out_path);
1414 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001415 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1416 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 return false;
1418 }
1419
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001420 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1421 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001422 fout.Flush();
1423
1424 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001425 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1426 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001427 return false;
1428 }
1429 return true;
1430 }
1431
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001432 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001433 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001434 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001435 context_->GetDiagnostics()->Note(android::DiagMessage()
1436 << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001437 }
1438
Adam Lesinski8780eb62017-10-31 17:44:39 -07001439 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1440 if (apk == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001441 context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001442 return false;
1443 }
1444
Adam Lesinski8780eb62017-10-31 17:44:39 -07001445 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001446 if (table->packages.empty()) {
1447 return true;
1448 }
1449
1450 auto lib_package_result = GetStaticLibraryPackage(table);
1451 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001452 context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001453 return false;
1454 }
1455
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001456 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001457 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001458 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001459 // Merge all resources as if they were in the compilation package. This is the old behavior
1460 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001461
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001462 // Add the package to the set of --extra-packages so we emit an R.java for each library
1463 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001465 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001466 }
1467
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001468 // Clear the package name, so as to make the resources look like they are coming from the
1469 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001470 pkg->name = "";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001471 result = table_merger_->Merge(android::Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001472
1473 } else {
1474 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001475 // preserved and resource names are mangled.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001476 result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001477 }
1478
1479 if (!result) {
1480 return false;
1481 }
1482
1483 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001484 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001485 return true;
1486 }
1487
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001488 bool MergeExportedSymbols(const android::Source& source,
Adam Lesinski2427dce2017-11-30 15:10:28 -08001489 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001490 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001491 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001492 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001493 ResourceName res_name = exported_symbol.name;
1494 if (res_name.package.empty()) {
1495 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001496 }
1497
Ryan Mitchell4382e442021-07-14 12:53:01 -07001498 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001499 if (mangled_name) {
1500 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001501 }
1502
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001503 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001504 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001505 bool result = final_table_.AddResource(
1506 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1507 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001508 if (!result) {
1509 return false;
1510 }
1511 }
1512 return true;
1513 }
1514
Adam Lesinski2427dce2017-11-30 15:10:28 -08001515 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001516 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001517 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001518 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski2427dce2017-11-30 15:10:28 -08001519 << "merging '" << compiled_file.name
1520 << "' from compiled file " << compiled_file.source);
1521 }
1522
1523 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1524 return false;
1525 }
1526 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1527 }
1528
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001529 // Takes a path to load as a ZIP file and merges the files within into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001530 // If override is true, conflicting resources are allowed to override each other, in order of last
1531 // seen.
1532 // An io::IFileCollection is created from the ZIP file and added to the set of
1533 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001534 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001535 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001536 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001537 context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001538 }
1539
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001541 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543 if (!collection) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001544 context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001545 return false;
1546 }
1547
1548 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001549 for (auto iter = collection->Iterator(); iter->HasNext();) {
1550 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001551 error = true;
1552 }
1553 }
1554
1555 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001556 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001557 return !error;
1558 }
1559
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001560 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001561 // conflicting resources are allowed to override each other, in order of last seen.
1562 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1563 // as ZIP archive and the files within are merged individually.
1564 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001565 bool MergePath(const std::string& path, bool override) {
1566 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1567 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1568 return MergeArchive(path, override);
1569 } else if (util::EndsWith(path, ".apk")) {
1570 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001571 }
1572
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001573 io::IFile* file = file_collection_->InsertFile(path);
1574 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001575 }
1576
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001577 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001578 // If override is true, conflicting resources are allowed to override each other, in order of last
1579 // seen.
1580 // All other file types are ignored. This is because these files could be coming from a zip,
1581 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001582 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001583 TRACE_CALL();
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001584 const android::Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001585
Adam Lesinski00451162017-10-03 07:44:08 -07001586 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001587 // Since AAPT compiles these file types and appends .flat to them, seeing
1588 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001589 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001590 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1591 << "uncompiled " << file_type
1592 << " file passed as argument. Must be "
1593 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001594 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001595 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1596 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001597 context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
Adam Lesinski00451162017-10-03 07:44:08 -07001598 return true;
1599 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001600 }
1601
Adam Lesinski00451162017-10-03 07:44:08 -07001602 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1603 if (input_stream == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001604 context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
Adam Lesinski00451162017-10-03 07:44:08 -07001605 return false;
1606 }
1607
1608 if (input_stream->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001609 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001610 << "failed to open file: " << input_stream->GetError());
1611 return false;
1612 }
1613
1614 ContainerReaderEntry* entry;
1615 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001616
1617 if (reader.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001618 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Mohamed Heikal10844322018-02-07 15:17:38 -05001619 << "failed to read file: " << reader.GetError());
1620 return false;
1621 }
1622
Adam Lesinski00451162017-10-03 07:44:08 -07001623 while ((entry = reader.Next()) != nullptr) {
1624 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001625 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001626 pb::ResourceTable pb_table;
1627 if (!entry->GetResTable(&pb_table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001628 context_->GetDiagnostics()->Error(
1629 android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001630 return false;
1631 }
1632
1633 ResourceTable table;
1634 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001635 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001636 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001637 << "failed to deserialize resource table: " << error);
1638 return false;
1639 }
1640
1641 if (!table_merger_->Merge(src, &table, override)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001642 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1643 << "failed to merge resource table");
Adam Lesinski00451162017-10-03 07:44:08 -07001644 return false;
1645 }
1646 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001647 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001648 pb::internal::CompiledFile pb_compiled_file;
1649 off64_t offset;
1650 size_t len;
1651 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001652 context_->GetDiagnostics()->Error(
1653 android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001654 return false;
1655 }
1656
1657 ResourceFile resource_file;
1658 std::string error;
1659 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001660 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001661 << "failed to read compiled header: " << error);
1662 return false;
1663 }
1664
1665 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1666 return false;
1667 }
1668 }
1669 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001670 return true;
1671 }
1672
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001673 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1674 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1675 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001676 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001677 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1678 if (!files) {
1679 return false;
1680 }
1681
1682 for (const std::string& file : files.value()) {
1683 std::string full_key = "assets/" + file;
1684 std::string full_path = assets_dir;
1685 file::AppendPath(&full_path, file);
1686
1687 auto iter = merged_assets.find(full_key);
1688 if (iter == merged_assets.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001689 merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1690 android::Source(std::move(full_path))));
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001691 } else if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001692 context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001693 << "asset file overrides '" << full_path << "'");
1694 }
1695 }
1696 }
1697
1698 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001699 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001700 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1701 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001702 return false;
1703 }
1704 }
1705 return true;
1706 }
1707
Rhed Jao2c434422020-11-12 10:48:03 +08001708 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1709 Reference* reference) {
1710 if (!reference || !reference->name) {
1711 return nullptr;
1712 }
1713 auto name_ref = ResourceNameRef(reference->name.value());
1714 if (name_ref.package.empty()) {
1715 name_ref.package = context->GetCompilationPackage();
1716 }
1717 const auto search_result = table->FindResource(name_ref);
1718 if (!search_result) {
1719 return nullptr;
1720 }
1721 return search_result.value().entry;
1722 }
1723
Ryan Mitchelldba64562019-06-07 17:07:37 -07001724 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001725 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001726 if (!application) {
1727 return;
1728 }
1729
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001730 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1731 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001732 if (!icon || !round_icon) {
1733 return;
1734 }
1735
1736 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001737 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001738 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1739 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001740 return;
1741 }
1742
1743 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001744 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001745 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1746 ? config_value->config.sdkVersion : icon_max_sdk;
1747 }
1748 if (icon_max_sdk < SDK_O) {
1749 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1750 return;
1751 }
1752
1753 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001754 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001755 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1756 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001757 return;
1758 }
1759
1760 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001761 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001762 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1763 ? config_value->config.sdkVersion : round_icon_max_sdk;
1764 }
1765 if (round_icon_max_sdk >= SDK_O) {
1766 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1767 // not generate an alias to the icon drawable.
1768 return;
1769 }
1770
1771 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001772 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001773 if (config_value->config.sdkVersion < SDK_O) {
1774 continue;
1775 }
1776
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001777 context_->GetDiagnostics()->Note(android::DiagMessage()
1778 << "generating " << round_icon_reference->name.value()
1779 << " with config \"" << config_value->config
1780 << "\" for round icon compatibility");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001781
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001782 CloningValueTransformer cloner(&table->string_pool);
1783 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001784 auto round_config_value =
1785 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001786 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001787 }
1788 }
1789
Rhed Jao2c434422020-11-12 10:48:03 +08001790 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1791 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1792 if (manifest_el == nullptr) {
1793 return true;
1794 }
1795 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1796 return true;
1797 }
1798 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1799 if (!attr) {
1800 return true;
1801 }
1802 const auto validate = [&](const std::string& shared_user_id) -> bool {
1803 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1804 return true;
1805 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001806 android::DiagMessage error_msg(manifest_el->line_number);
Rhed Jao2c434422020-11-12 10:48:03 +08001807 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1808 << shared_user_id << "'";
1809 if (options_.manifest_fixer_options.warn_validation) {
1810 // Treat the error only as a warning.
1811 context_->GetDiagnostics()->Warn(error_msg);
1812 return true;
1813 }
1814 context_->GetDiagnostics()->Error(error_msg);
1815 return false;
1816 };
1817 // If attr->compiled_value is not null, check if it is a ref
1818 if (attr->compiled_value) {
1819 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1820 if (ref == nullptr) {
1821 return true;
1822 }
1823 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1824 if (!shared_user_id_entry) {
1825 return true;
1826 }
1827 for (const auto& value : shared_user_id_entry->values) {
1828 const auto str_value = ValueCast<String>(value->value.get());
1829 if (str_value != nullptr && !validate(*str_value->value)) {
1830 return false;
1831 }
1832 }
1833 return true;
1834 }
1835
1836 // Fallback to checking the raw value
1837 return validate(attr->value);
1838 }
1839
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001840 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1841 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001842 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1843 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001844 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001845 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1846 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001847 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001848 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 if (!result) {
1850 return false;
1851 }
1852
Ryan Mitchelldba64562019-06-07 17:07:37 -07001853 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1854 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1855 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1856 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1857 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1858 // See (b/34829129)
1859 AliasAdaptiveIcon(manifest, table);
1860
Rhed Jao2c434422020-11-12 10:48:03 +08001861 // Verify the shared user id here to handle the case of reference value.
1862 if (!VerifySharedUserId(manifest, table)) {
1863 return false;
1864 }
1865
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 ResourceFileFlattenerOptions file_flattener_options;
1867 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001868 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1869 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001870 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001871 file_flattener_options.no_auto_version = options_.no_auto_version;
1872 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001873 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001874 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1875 file_flattener_options.update_proguard_spec =
1876 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001877 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001878 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001879
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001880 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 if (!file_flattener.Flatten(table, writer)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001882 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 return false;
1884 }
1885
Adam Lesinski490595a2017-11-07 17:08:07 -08001886 // Hack to fix b/68820737.
1887 // We need to modify the ResourceTable's package name, but that should NOT affect
1888 // anything else being generated, which includes the Java classes.
1889 // If required, the package name is modifed before flattening, and then modified back
1890 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001891 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001892 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1893 // or higher] as invalid. In order to work around this limitation, we allow the use
1894 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1895 // definition of what a valid "split" package ID is to account for this.
1896 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1897 context_->GetPackageId() != kAppPackageId &&
1898 context_->GetPackageId() != kFrameworkPackageId)
1899 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001900 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001901 // The base APK is included, and this is a feature split. If the base package is
1902 // the same as this package, then we are building an old style Android Instant Apps feature
1903 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001904 if (!table->packages.empty() &&
1905 table->packages.back()->name == context_->GetCompilationPackage()) {
1906 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001907 std::string new_package_name =
1908 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001909 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001910
1911 if (context_->IsVerbose()) {
1912 context_->GetDiagnostics()->Note(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001913 android::DiagMessage() << "rewriting resource package name for feature split to '"
1914 << new_package_name << "'");
Adam Lesinski490595a2017-11-07 17:08:07 -08001915 }
1916 package_to_rewrite->name = new_package_name;
1917 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001918 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001919
1920 bool success = FlattenTable(table, options_.output_format, writer);
1921
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001922 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001923 // Change the name back.
1924 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001925
1926 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1927 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1928 // library, do not include a mapping from the feature package name to the feature package id
1929 // in the feature's dynamic reference table.
1930 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001931 }
1932
1933 if (!success) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001934 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
Adam Lesinski490595a2017-11-07 17:08:07 -08001935 }
1936 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 }
1938
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001939 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001940 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001941 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 std::unique_ptr<xml::XmlResource> manifest_xml =
1943 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1944 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 return 1;
1946 }
1947
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001948 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001949 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001950 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 const AppInfo& app_info = maybe_app_info.value();
1952 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 }
1954
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001955 // Determine the package name under which to merge resources.
1956 if (options_.rename_resources_package) {
1957 if (!options_.custom_java_package) {
1958 // Generate the R.java under the original package name instead of the package name specified
1959 // through --rename-resources-package.
1960 options_.custom_java_package = context_->GetCompilationPackage();
1961 }
1962 context_->SetCompilationPackage(options_.rename_resources_package.value());
1963 }
1964
Adam Lesinskic6284372017-12-04 13:46:23 -08001965 // Now that the compilation package is set, load the dependencies. This will also extract
1966 // the Android framework's versionCode and versionName, if they exist.
1967 if (!LoadSymbolsFromIncludePaths()) {
1968 return 1;
1969 }
1970
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001971 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1972 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001973 return 1;
1974 }
1975
Ryan Mitchell4382e442021-07-14 12:53:01 -07001976 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001977 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001978 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001979 return 1;
1980 }
1981
Adam Lesinski490595a2017-11-07 17:08:07 -08001982 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001983 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001984
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001985 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001986 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001987
1988 // Override the package ID when it is "android".
1989 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001990 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001991
1992 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001993 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001994 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001995 android::DiagMessage() << "package 'android' can only be built as a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001996 return 1;
1997 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001998 }
1999
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002000 TableMergerOptions table_merger_options;
2001 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07002002 table_merger_options.override_styles_instead_of_overlaying =
2003 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01002004 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002005 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002007 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002008 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002009 << StringPrintf("linking package '%s' using package ID %02x",
2010 context_->GetCompilationPackage().data(),
2011 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 }
2013
Adam Lesinski2427dce2017-11-30 15:10:28 -08002014 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
2015 // in res/**/*.
2016 {
2017 XmlIdCollector collector;
2018 if (!collector.Consume(context_, manifest_xml.get())) {
2019 return false;
2020 }
2021
2022 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
2023 return false;
2024 }
2025 }
2026
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002027 for (const std::string& input : input_files) {
2028 if (!MergePath(input, false)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002029 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 return 1;
2031 }
2032 }
2033
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002034 for (const std::string& input : options_.overlay_files) {
2035 if (!MergePath(input, true)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002036 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002037 return 1;
2038 }
2039 }
2040
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002041 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002042 return 1;
2043 }
2044
Adam Lesinskib522f042017-04-21 16:57:59 -07002045 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002046 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002047 if (context_->GetPackageId() == kAndroidPackageId &&
2048 !mover.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002049 context_->GetDiagnostics()->Error(android::DiagMessage()
2050 << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051 return 1;
2052 }
2053
2054 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002055 IdAssigner id_assigner(&options_.stable_id_map);
2056 if (!id_assigner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002057 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002058 return 1;
2059 }
2060
2061 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002062 if (options_.resource_id_map_path) {
2063 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 for (auto& type : package->types) {
2065 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002066 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002067 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002068 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 }
2070 }
2071 }
2072
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002075 return 1;
2076 }
2077 }
2078 } else {
2079 // Static libs are merged with other apps, and ID collisions are bad, so
2080 // verify that
2081 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002082 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002083 return 1;
2084 }
2085 }
2086
2087 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002088 context_->SetNameManglerPolicy(
2089 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002090
2091 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 context_->GetExternalSymbols()->PrependSource(
2093 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002095 // Workaround for pre-O runtime that would treat negative resource IDs
2096 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2097 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2098 // are just identifiers.
2099 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2100 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002101 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002102 << "enabling pre-O feature split ID rewriting");
2103 }
2104 context_->GetExternalSymbols()->SetDelegate(
2105 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2106 }
2107
Adam Lesinski34a16872018-02-23 16:18:10 -08002108 // Before we process anything, remove the resources whose default values don't exist.
2109 // We want to force any references to these to fail the build.
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002110 if (!options_.no_resource_removal) {
2111 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002112 context_->GetDiagnostics()->Error(android::DiagMessage()
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002113 << "failed removing resources with no defaults");
2114 return 1;
2115 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002116 }
2117
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002118 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002119 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002120 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002121 return 1;
2122 }
2123
Adam Lesinskib522f042017-04-21 16:57:59 -07002124 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002125 if (!options_.products.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002126 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002127 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002128 }
2129 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002130 ProductFilter product_filter(options_.products);
2131 if (!product_filter.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002132 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002133 return 1;
2134 }
2135 }
2136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002137 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002138 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002139 if (!versioner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002140 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 return 1;
2142 }
2143 }
2144
Adam Lesinskib522f042017-04-21 16:57:59 -07002145 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002146 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002147 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002148 << "collapsing resource versions for minimum SDK "
2149 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 }
2151
2152 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002154 return 1;
2155 }
2156 }
2157
Winson3c918b82019-01-25 14:25:37 -08002158 if (!options_.exclude_configs_.empty()) {
2159 std::vector<ConfigDescription> excluded_configs;
2160
2161 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002162 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002163 ConfigDescription config_description;
2164
2165 if (!ConfigDescription::Parse(config_string, &config_description)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002166 context_->GetDiagnostics()->Error(
2167 android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
Winson3c918b82019-01-25 14:25:37 -08002168 return 1;
2169 }
2170
2171 excluded_configs.push_back(config_description);
2172 }
2173
2174 ResourceExcluder excluder(excluded_configs);
2175 if (!excluder.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002176 context_->GetDiagnostics()->Error(android::DiagMessage()
2177 << "failed excluding configurations");
Winson3c918b82019-01-25 14:25:37 -08002178 return 1;
2179 }
2180 }
2181
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002182 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002183 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 if (!deduper.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002185 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186 return 1;
2187 }
2188 }
2189
Adam Koskidc21dea2017-07-21 10:55:27 -07002190 proguard::KeepSet proguard_keep_set =
2191 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002192 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002193
Adam Lesinskib522f042017-04-21 16:57:59 -07002194 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002195 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002196 !options_.table_splitter_options.preferred_densities.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002197 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002198 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002199 }
2200 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002201 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2202 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002203 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002204 options_.split_constraints =
2205 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002206
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002207 if (origConstraintSize != options_.split_constraints.size()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002208 context_->GetDiagnostics()->Warn(android::DiagMessage()
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002209 << "requested to split resources prior to min sdk of "
2210 << context_->GetMinSdkVersion());
2211 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002212 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002213 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002214 return 1;
2215 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002216 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002217
2218 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002219 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002220 auto split_constraints_iter = options_.split_constraints.begin();
2221 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002222 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002223 context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002224 << "generating split with configurations '"
2225 << util::Joiner(split_constraints_iter->configs, ", ")
2226 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002227 }
2228
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002229 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002230 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002231 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002232 return 1;
2233 }
2234
2235 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002236 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002237 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002238
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002239 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002240 if (!linker.Consume(context_, split_manifest.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002241 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002242 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002243 return 1;
2244 }
2245
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002246 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2247 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002248 return 1;
2249 }
2250
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002251 ++path_iter;
2252 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002253 }
2254 }
2255
2256 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002257 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002258 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002259 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002260 return 1;
2261 }
2262
2263 bool error = false;
2264 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002265 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 // (aka, which package the AndroidManifest.xml is coming from).
2267 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002268 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002269
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002270 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002271 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002272 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002273 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002274 error = true;
2275 }
2276
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002277 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002278 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002279 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002280 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002281 }
2282
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002283 if (options_.generate_java_class_path) {
2284 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002285 error = true;
2286 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002287 }
2288
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002289 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002290 // PackageParser will fail if URIs are removed from
2291 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002292 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2293 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002294 error = true;
2295 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002296 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002297 } else {
2298 error = true;
2299 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002300 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002301
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002302 if (error) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002303 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002304 return 1;
2305 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002306
Josh Houec67cb42022-06-09 19:19:21 +08002307 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2308 return 1;
2309 };
2310
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002311 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2312 return 1;
2313 }
2314
2315 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002316 return 1;
2317 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002318
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002319 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002320 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002321 return 1;
2322 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002323 }
2324
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002325 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002326 return 1;
2327 }
2328
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002329 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2330 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002331 return 1;
2332 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002333 return 0;
2334 }
2335
2336 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002337 LinkOptions options_;
2338 LinkContext* context_;
2339 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002340
Adam Lesinski490595a2017-11-07 17:08:07 -08002341 AppInfo app_info_;
2342
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002343 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002344
2345 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002346 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002347
Adam Lesinski8780eb62017-10-31 17:44:39 -07002348 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002349 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002350 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002351
Adam Lesinski8780eb62017-10-31 17:44:39 -07002352 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2353 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2354
2355 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2356 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002357
2358 // The set of shared libraries being used, mapping their assigned package ID to package name.
2359 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002360
2361 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002362 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002363};
2364
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002365int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002366 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002367 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002368
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002369 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002370 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002371 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002372 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002373 const std::string path = arg.substr(1, arg.size() - 1);
2374 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002375 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002376 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002377 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002378 }
2379 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002380 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002381 }
2382 }
2383
2384 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002385 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002386 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002387 const std::string path = arg.substr(1, arg.size() - 1);
2388 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002389 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002390 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002391 return 1;
2392 }
2393 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002394 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002395 }
2396 }
2397
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002398 if (verbose_) {
2399 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002400 }
2401
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002402 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002403 context.GetDiagnostics()
2404 ->Error(android::DiagMessage()
2405 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002406 return 1;
2407 }
2408
Ryan Mitchell5855de72021-02-24 14:39:13 -08002409 if (shared_lib_ && options_.private_symbols) {
2410 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2411 // reference the private attribute within the styleable array will cause a link error because
2412 // the private attribute will not be emitted in the public R.java.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002413 context.GetDiagnostics()->Error(android::DiagMessage()
Ryan Mitchell5855de72021-02-24 14:39:13 -08002414 << "--shared-lib cannot currently be used in combination with"
2415 << " --private-symbols");
2416 return 1;
2417 }
2418
Izabela Orlowska84febea2019-06-03 18:34:12 +01002419 if (options_.merge_only && !static_lib_) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002420 context.GetDiagnostics()
2421 ->Error(android::DiagMessage()
2422 << "the --merge-only flag can be only used when building a static library");
Izabela Orlowska84febea2019-06-03 18:34:12 +01002423 return 1;
2424 }
Iurii Makhnoda06e4d2022-08-24 14:17:32 +00002425 if (options_.use_sparse_encoding) {
2426 options_.table_flattener_options.sparse_entries = SparseEntriesMode::Enabled;
2427 }
Izabela Orlowska84febea2019-06-03 18:34:12 +01002428
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002429 // The default build type.
2430 context.SetPackageType(PackageType::kApp);
2431 context.SetPackageId(kAppPackageId);
2432
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002433 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002434 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002435 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002436 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002437 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002438 options_.output_format = OutputFormat::kProto;
2439 } else if (proto_format_) {
2440 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002441 }
2442
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002443 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002444 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002445 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002446 android::DiagMessage() << "can't specify --package-id when not building a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002447 return 1;
2448 }
2449
Ryan Mitchell4382e442021-07-14 12:53:01 -07002450 const std::optional<uint32_t> maybe_package_id_int =
2451 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002452 if (!maybe_package_id_int) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002453 context.GetDiagnostics()->Error(android::DiagMessage()
2454 << "package ID '" << package_id_.value()
2455 << "' is not a valid integer");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002456 return 1;
2457 }
2458
2459 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002460 if (package_id_int > std::numeric_limits<uint8_t>::max()
2461 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002462 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002463 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002464 android::DiagMessage() << StringPrintf(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002465 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2466 return 1;
2467 }
2468 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2469 }
2470
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002471 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002472 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002473 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002474 for (StringPiece package : util::Split(extra_package, ':')) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002475 options_.extra_java_packages.emplace(package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002476 }
2477 }
2478
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002479 if (product_list_) {
2480 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002481 if (product != "" && product != "default") {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002482 options_.products.emplace(product);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002483 }
2484 }
2485 }
2486
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002487 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002488 if (!configs_.empty()) {
2489 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002490 if (filter == nullptr) {
2491 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002492 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002493 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002494 }
2495
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002496 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002497 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002498 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002499 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002500 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002501 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002502 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002503 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002504
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002505 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002506 for (const std::string& split_arg : split_args_) {
2507 options_.split_paths.push_back({});
2508 options_.split_constraints.push_back({});
2509 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2510 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002511 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002512 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002513 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002514
Mark Punzalan5579cad2023-10-30 13:47:51 -07002515 // Parse the feature flag values. An argument that starts with '@' points to a file to read flag
2516 // values from.
2517 std::vector<std::string> all_feature_flags_args;
2518 for (const std::string& arg : feature_flags_args_) {
2519 if (util::StartsWith(arg, "@")) {
2520 const std::string path = arg.substr(1, arg.size() - 1);
2521 std::string error;
2522 if (!file::AppendArgsFromFile(path, &all_feature_flags_args, &error)) {
2523 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2524 return 1;
2525 }
2526 } else {
2527 all_feature_flags_args.push_back(arg);
2528 }
2529 }
2530
2531 for (const std::string& arg : all_feature_flags_args) {
2532 if (ParseFeatureFlagsParameter(arg, context.GetDiagnostics(), &options_.feature_flag_values)) {
2533 return 1;
2534 }
2535 }
2536
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002537 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2538 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2539 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002540 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002541 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002542 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002543
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002544 if (no_compress_regex) {
2545 std::string regex = no_compress_regex.value();
2546 if (util::StartsWith(regex, "@")) {
2547 const std::string path = regex.substr(1, regex.size() -1);
2548 std::string error;
2549 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002550 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002551 return 1;
2552 }
2553 } else {
2554 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2555 }
2556 }
2557
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002558 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002559 options_.extensions_to_not_compress.insert({
2560 // Image extensions
2561 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2562 // Audio extensions
2563 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2564 ".xmf", ".amr", ".awb",
2565 // Audio/video extensions
2566 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2567 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002568
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002569 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002570 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002571 options_.no_auto_version = true;
2572 options_.no_version_vectors = true;
2573 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002574 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002575
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002576 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002577 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002578}
2579
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002580} // namespace aapt