blob: 642a5618b6ad9abbbcbb3b18413e673a56655bfb [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"
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +000038#include "androidfw/BigBufferStream.h"
39#include "androidfw/FileStream.h"
Jeremy Meyer56f36e82022-05-20 20:35:42 +000040#include "androidfw/IDiagnostics.h"
41#include "androidfw/Locale.h"
42#include "androidfw/StringPiece.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070043#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070044#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080045#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080046#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070047#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070049#include "format/binary/TableFlattener.h"
50#include "format/binary/XmlFlattener.h"
51#include "format/proto/ProtoDeserialize.h"
52#include "format/proto/ProtoSerialize.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"
Mark Punzalan4b564de2024-01-05 02:17:20 -080059#include "link/FeatureFlagsFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070061#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080062#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080063#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080064#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070066#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080067#include "optimize/ResourceDeduper.h"
68#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069#include "process/IResourceTableConsumer.h"
Inseob Kim5fe521e2023-09-15 16:38:50 +090070#include "process/ProductFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080072#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080073#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080075#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070076
MÃ¥rten Kongstad24c9aa62018-06-20 08:46:41 +020077using ::android::ConfigDescription;
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +000078using ::android::FileInputStream;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070079using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070080using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070081using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070082using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070083
Adam Lesinski1ab598f2015-08-14 14:26:04 -070084namespace aapt {
85
Ryan Mitchell9634efb2021-03-19 14:53:17 -070086namespace {
87
88expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
89 // Resource tables built by aapt2 always contain one package. This is a post condition of
90 // VerifyNoExternalPackages.
91 if (table->packages.size() != 1u) {
92 return unexpected("static library contains more than one package");
93 }
94 return table->packages.back().get();
95}
96
97} // namespace
98
Ryan Mitchell22dc5312020-06-01 12:17:07 -070099constexpr uint8_t kAndroidPackageId = 0x01;
100
Adam Lesinski64587af2016-02-18 18:33:06 -0800101class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700102 public:
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000103 explicit LinkContext(android::IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100104 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700105 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700106
Adam Lesinskib522f042017-04-21 16:57:59 -0700107 PackageType GetPackageType() override {
108 return package_type_;
109 }
110
111 void SetPackageType(PackageType type) {
112 package_type_ = type;
113 }
114
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000115 android::IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100116 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700118
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700119 NameMangler* GetNameMangler() override {
120 return &name_mangler_;
121 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700122
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700123 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
124 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700125 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800126
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700127 const std::string& GetCompilationPackage() override {
128 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700130
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700131 void SetCompilationPackage(StringPiece package_name) {
132 compilation_package_ = std::string(package_name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700133 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800134
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700135 uint8_t GetPackageId() override {
136 return package_id_;
137 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700138
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700139 void SetPackageId(uint8_t id) {
140 package_id_ = id;
141 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800142
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700143 SymbolTable* GetExternalSymbols() override {
144 return &symbols_;
145 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800146
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700147 bool IsVerbose() override {
148 return verbose_;
149 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800150
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700151 void SetVerbose(bool val) {
152 verbose_ = val;
Brandon Liu48d229d2023-05-04 23:54:03 +0000153 diagnostics_->SetVerbose(val);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700154 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800155
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700156 int GetMinSdkVersion() override {
157 return min_sdk_version_;
158 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700159
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700160 void SetMinSdkVersion(int minSdk) {
161 min_sdk_version_ = minSdk;
162 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700163
Udam Sainib228df32019-06-18 16:50:34 -0700164 const std::set<std::string>& GetSplitNameDependencies() override {
165 return split_name_dependencies_;
166 }
167
168 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
169 split_name_dependencies_ = split_name_dependencies;
170 }
171
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700172 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700173 DISALLOW_COPY_AND_ASSIGN(LinkContext);
174
Adam Lesinskib522f042017-04-21 16:57:59 -0700175 PackageType package_type_ = PackageType::kApp;
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000176 android::IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700177 NameMangler name_mangler_;
178 std::string compilation_package_;
179 uint8_t package_id_ = 0x0;
180 SymbolTable symbols_;
181 bool verbose_ = false;
182 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700183 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700184};
185
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700186// A custom delegate that generates compatible pre-O IDs for use with feature splits.
187// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
188// is interpreted as a negative number. Some verification was wrongly assuming negative values
189// were invalid.
190//
191// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
192// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
193// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800194//
195// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700196class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
197 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800198 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700199 }
200
201 virtual ~FeatureSplitSymbolTableDelegate() = default;
202
203 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
204 const ResourceName& name,
205 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
206 std::unique_ptr<SymbolTable::Symbol> symbol =
207 DefaultSymbolTableDelegate::FindByName(name, sources);
208 if (symbol == nullptr) {
209 return {};
210 }
211
212 // Check to see if this is an 'id' with the target package.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000213 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700214 ResourceId* id = &symbol->id.value();
215 if (id->package_id() > kAppPackageId) {
216 // Rewrite the resource ID to be compatible pre-O.
217 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
218
219 // Check that this doesn't overlap another resource.
220 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
221 // The ID overlaps, so log a message (since this is a weird failure) and fail.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000222 context_->GetDiagnostics()->Error(android::DiagMessage()
223 << "Failed to rewrite " << name
224 << " for pre-O feature split support");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700225 return {};
226 }
227
228 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000229 context_->GetDiagnostics()->Note(android::DiagMessage()
230 << "rewriting " << name << " (" << *id << ") -> ("
231 << rewritten_id << ")");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700232 }
233
234 *id = rewritten_id;
235 }
236 }
237 return symbol;
238 }
239
240 private:
241 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
242
243 IAaptContext* context_;
244};
245
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700246static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path,
247 bool keep_raw_values, bool utf16, OutputFormat format,
248 IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800249 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700250 if (context->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000251 context->GetDiagnostics()->Note(android::DiagMessage(path)
252 << "writing to archive (keep_raw_values="
253 << (keep_raw_values ? "true" : "false") << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700254 }
255
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700256 switch (format) {
257 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000258 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700259 XmlFlattenerOptions options = {};
260 options.keep_raw_values = keep_raw_values;
261 options.use_utf16 = utf16;
262 XmlFlattener flattener(&buffer, options);
263 if (!flattener.Consume(context, &xml_res)) {
264 return false;
265 }
266
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000267 android::BigBufferInputStream input_stream(&buffer);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700268 return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
269 writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700270 } break;
271
272 case OutputFormat::kProto: {
273 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800274 // Strip whitespace text nodes from tha AndroidManifest.xml
275 SerializeXmlOptions options;
276 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700277 SerializeXmlResourceToPb(xml_res, &pb_node);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700278 return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700279 } break;
280 }
281 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800282}
283
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700284// Inflates an XML file from the source path.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000285static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
286 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800287 TRACE_CALL();
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000288 android::FileInputStream fin(path);
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700289 if (fin.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000290 diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700291 return {};
292 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000293 return xml::Inflate(&fin, diag, android::Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800294}
295
Adam Lesinski355f2852016-02-13 20:26:45 -0800296struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700297 bool no_auto_version = false;
298 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900299 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700300 bool no_xml_namespaces = false;
301 bool keep_raw_values = false;
302 bool do_not_compress_anything = false;
303 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100304 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700305 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700306 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700307 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800308};
309
Adam Lesinskic744ae82017-05-17 19:28:38 -0700310// A sampling of public framework resource IDs.
311struct R {
312 struct attr {
313 enum : uint32_t {
314 paddingLeft = 0x010100d6u,
315 paddingRight = 0x010100d8u,
316 paddingHorizontal = 0x0101053du,
317
318 paddingTop = 0x010100d7u,
319 paddingBottom = 0x010100d9u,
320 paddingVertical = 0x0101053eu,
321
322 layout_marginLeft = 0x010100f7u,
323 layout_marginRight = 0x010100f9u,
324 layout_marginHorizontal = 0x0101053bu,
325
326 layout_marginTop = 0x010100f8u,
327 layout_marginBottom = 0x010100fau,
328 layout_marginVertical = 0x0101053cu,
329 };
330 };
331};
332
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700333template <typename T>
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700334uint32_t GetCompressionFlags(StringPiece str, T options) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700335 if (options.do_not_compress_anything) {
336 return 0;
337 }
338
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700339 if (options.regex_to_not_compress &&
340 std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700341 return 0;
342 }
343
344 for (const std::string& extension : options.extensions_to_not_compress) {
345 if (util::EndsWith(str, extension)) {
346 return 0;
347 }
348 }
349 return ArchiveEntry::kCompress;
350}
351
Adam Lesinski355f2852016-02-13 20:26:45 -0800352class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700353 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700354 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700355 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800356
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700357 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800358
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700359 private:
360 struct FileOperation {
361 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700362
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700363 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700364 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700365
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700366 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700367 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700368
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700370 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700371
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700372 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700373 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700374 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800375
Adam Lesinskic744ae82017-05-17 19:28:38 -0700376 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
377 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800378
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700379 ResourceFileFlattenerOptions options_;
380 IAaptContext* context_;
381 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700382 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800383};
384
Adam Lesinskic744ae82017-05-17 19:28:38 -0700385ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
386 IAaptContext* context, proguard::KeepSet* keep_set)
387 : options_(options), context_(context), keep_set_(keep_set) {
388 SymbolTable* symm = context_->GetExternalSymbols();
389
390 // Build up the rules for degrading newer attributes to older ones.
391 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
392 // generated from the attribute definitions themselves (b/62028956).
Yi Kongd6507882023-12-05 17:06:08 +0900393 if (symm->FindById(R::attr::paddingHorizontal)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800395 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
396 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700397 };
398 rules_[R::attr::paddingHorizontal] =
399 util::make_unique<DegradeToManyRule>(std::move(replacements));
400 }
401
Yi Kongd6507882023-12-05 17:06:08 +0900402 if (symm->FindById(R::attr::paddingVertical)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700403 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800404 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
405 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700406 };
407 rules_[R::attr::paddingVertical] =
408 util::make_unique<DegradeToManyRule>(std::move(replacements));
409 }
410
Yi Kongd6507882023-12-05 17:06:08 +0900411 if (symm->FindById(R::attr::layout_marginHorizontal)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 std::vector<ReplacementAttr> replacements{
413 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800414 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700415 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800416 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700417 };
418 rules_[R::attr::layout_marginHorizontal] =
419 util::make_unique<DegradeToManyRule>(std::move(replacements));
420 }
421
Yi Kongd6507882023-12-05 17:06:08 +0900422 if (symm->FindById(R::attr::layout_marginVertical)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 std::vector<ReplacementAttr> replacements{
424 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800425 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700426 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800427 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700428 };
429 rules_[R::attr::layout_marginVertical] =
430 util::make_unique<DegradeToManyRule>(std::move(replacements));
431 }
432}
433
Adam Lesinskibb94f322017-07-12 07:41:55 -0700434static bool IsTransitionElement(const std::string& name) {
435 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
436 name == "changeImageTransform" || name == "changeTransform" ||
437 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
438 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
439 name == "transitionManager";
440}
441
442static bool IsVectorElement(const std::string& name) {
443 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800444 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
445 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700446}
447
Adam Lesinskic744ae82017-05-17 19:28:38 -0700448template <typename T>
449std::vector<T> make_singleton_vec(T&& val) {
450 std::vector<T> vec;
451 vec.emplace_back(std::forward<T>(val));
452 return vec;
453}
454
455std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
456 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800457 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700458 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000459 const android::Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700460
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700461 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000462 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700463 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700464 }
465
Adam Lesinski00451162017-10-03 07:44:08 -0700466 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
467 // that existing projects have out-of-date references which pass compilation.
468 xml::StripAndroidStudioAttributes(doc->root.get());
469
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700470 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100471 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700472 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700473 }
474
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700475 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700476 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700477 }
478
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700479 if (options_.no_xml_namespaces) {
480 XmlNamespaceRemover namespace_remover;
481 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700482 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800483 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800485
Adam Lesinskibb94f322017-07-12 07:41:55 -0700486 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700487 return make_singleton_vec(std::move(file_op->xml_to_flatten));
488 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700489
Adam Lesinskibb94f322017-07-12 07:41:55 -0700490 if (options_.no_version_vectors || options_.no_version_transitions) {
491 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700492 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700493 if (el && el->namespace_uri.empty()) {
494 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
495 (options_.no_version_transitions && IsTransitionElement(el->name))) {
496 return make_singleton_vec(std::move(file_op->xml_to_flatten));
497 }
498 }
499 }
500
Adam Lesinskic744ae82017-05-17 19:28:38 -0700501 const ConfigDescription& config = file_op->config;
502 ResourceEntry* entry = file_op->entry;
503
504 XmlCompatVersioner xml_compat_versioner(&rules_);
505 const util::Range<ApiVersion> api_range{config.sdkVersion,
506 FindNextApiVersionForConfig(entry, config)};
507 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800508}
509
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800510ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
511 switch (format) {
512 case OutputFormat::kApk:
513 return ResourceFile::Type::kBinaryXml;
514 case OutputFormat::kProto:
515 return ResourceFile::Type::kProtoXml;
516 }
517 LOG_ALWAYS_FATAL("unreachable");
518 return ResourceFile::Type::kUnknown;
519}
520
Ryan Mitchell70f79722018-08-13 07:37:24 -0700521static auto kDrawableVersions = std::map<std::string, ApiVersion>{
522 { "adaptive-icon" , SDK_O },
523};
524
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700525bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800526 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700528 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800529
Adam Koskidc21dea2017-07-21 10:55:27 -0700530 proguard::CollectResourceReferences(context_, table, keep_set_);
531
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700532 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700533 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
534
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700536 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700537 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700538 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800539
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700540 // Populate the queue with all files in the ResourceTable.
541 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700542 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700543 // WARNING! Do not insert or remove any resources while executing in this scope. It will
544 // corrupt the iteration order.
545
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700546 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700548 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700550
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700551 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 if (!file) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000553 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700555 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556 }
557
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700558 FileOperation file_op;
559 file_op.entry = entry.get();
560 file_op.dst_path = *file_ref->path;
561 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700562 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000564 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700565 (file_ref->type == ResourceFile::Type::kBinaryXml ||
566 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700567 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700568 if (!data) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000569 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700570 << "failed to open file");
571 return false;
572 }
573
Adam Lesinski00451162017-10-03 07:44:08 -0700574 if (file_ref->type == ResourceFile::Type::kProtoXml) {
575 pb::XmlNode pb_xml_node;
576 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000577 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700578 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700579 return false;
580 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700581
Adam Lesinski00451162017-10-03 07:44:08 -0700582 std::string error;
583 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
584 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000585 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700586 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700587 return false;
588 }
589 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700590 std::string error_str;
591 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700592 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000593 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700594 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700595 return false;
596 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700597 }
598
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800599 // Update the type that this file will be written as.
600 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
601
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700602 file_op.xml_to_flatten->file.config = config_value->config;
603 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000604 file_op.xml_to_flatten->file.name =
605 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700606 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700607
608 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
609 // else we end up copying the string in the std::make_pair() method,
610 // then creating a StringPiece from the copy, which would cause us
611 // to end up referencing garbage in the map.
612 const StringPiece entry_name(entry->name);
613 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
614 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 }
616 }
617
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700618 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700619 for (auto& map_entry : config_sorted_files) {
620 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700621 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700622
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700623 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700624 // Check minimum sdk versions supported for drawables
625 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
626 if (drawable_entry != kDrawableVersions.end()) {
627 if (drawable_entry->second > context_->GetMinSdkVersion()
628 && drawable_entry->second > config.sdkVersion) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000629 context_->GetDiagnostics()->Error(
630 android::DiagMessage(file_op.xml_to_flatten->file.source)
631 << "<" << drawable_entry->first << "> elements "
632 << "require a sdk version of at least " << (int16_t)drawable_entry->second);
Ryan Mitchell70f79722018-08-13 07:37:24 -0700633 error = true;
634 continue;
635 }
636 }
637
Adam Lesinskic744ae82017-05-17 19:28:38 -0700638 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
639 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700640 if (versioned_docs.empty()) {
641 error = true;
642 continue;
643 }
644
Adam Lesinskic744ae82017-05-17 19:28:38 -0700645 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
646 std::string dst_path = file_op.dst_path;
647 if (doc->file.config != file_op.config) {
648 // Only add the new versioned configurations.
649 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000650 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
Adam Lesinskic744ae82017-05-17 19:28:38 -0700651 << "auto-versioning resource from config '"
652 << config << "' -> '" << doc->file.config << "'");
653 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700654
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800655 const ResourceFile& file = doc->file;
656 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
657
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700658 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800659 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
660 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700661
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800662 // Update the output format of this XML file.
663 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700664 bool result = table->AddResource(NewResourceBuilder(file.name)
665 .SetValue(std::move(file_ref), file.config)
666 .SetAllowMangled(true)
667 .Build(),
668 context_->GetDiagnostics());
669 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700670 return false;
671 }
672 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700673
674 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
675 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 }
677 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700678 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700679 GetCompressionFlags(file_op.dst_path, options_),
680 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700681 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700683 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 }
685 return !error;
686}
687
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000688static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700689 const std::unordered_map<ResourceName, ResourceId>& id_map,
690 const std::string& id_map_path) {
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000691 android::FileOutputStream fout(id_map_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800692 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000693 diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694 return false;
695 }
696
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800697 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700698 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 const ResourceName& name = entry.first;
700 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800701 printer.Print(name.to_string());
702 printer.Print(" = ");
703 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800705 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800707 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000708 diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 return false;
710 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 return true;
712}
713
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000714static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700715 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700717 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000718 diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700719 return false;
720 }
721
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700722 out_id_map->clear();
723 size_t line_no = 0;
724 for (StringPiece line : util::Tokenize(content, '\n')) {
725 line_no++;
726 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700727 if (line.empty()) {
728 continue;
729 }
730
731 auto iter = std::find(line.begin(), line.end(), '=');
732 if (iter == line.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000733 diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700734 return false;
735 }
736
737 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 StringPiece res_name_str =
739 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
740 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000741 diag->Error(android::DiagMessage(android::Source(path, line_no))
742 << "invalid resource name '" << res_name_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743 return false;
744 }
745
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700746 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
747 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700748 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700749
Ryan Mitchell4382e442021-07-14 12:53:01 -0700750 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700751 if (!maybe_id) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000752 diag->Error(android::DiagMessage(android::Source(path, line_no))
753 << "invalid resource ID '" << res_id_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700754 return false;
755 }
756
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700757 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700758 }
759 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700760}
761
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700762class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700763 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700764 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700765 : options_(options),
766 context_(context),
767 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700768 file_collection_(util::make_unique<io::FileCollection>()) {
769 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700770
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800771 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800772 using namespace android;
773
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000774 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
775 // we're looking for the first attribute resource in the system package.
776 android::ApkAssetsCookie cookie;
777 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
778 cookie = value->cookie;
779 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800780 // No Framework assets loaded. Not a failure.
781 return;
782 }
783
784 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800785 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800786 if (manifest == nullptr) {
787 // No errors.
788 return;
789 }
790
791 std::string error;
792 std::unique_ptr<xml::XmlResource> manifest_xml =
793 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
794 if (manifest_xml == nullptr) {
795 // No errors.
796 return;
797 }
798
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700799 if (!options_.manifest_fixer_options.compile_sdk_version) {
800 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
801 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700802 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700803 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
804 switch (prim->value.dataType) {
805 case Res_value::TYPE_INT_DEC:
806 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
807 break;
808 case Res_value::TYPE_INT_HEX:
809 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
810 break;
811 default:
812 break;
813 }
814 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
815 compile_sdk_version = *str->value;
816 } else {
817 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800818 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800819 }
820 }
821
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700822 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
823 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
824 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700825 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700826 options_.manifest_fixer_options.compile_sdk_version_codename;
827 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
828 compile_sdk_version_codename = *str->value;
829 } else {
830 compile_sdk_version_codename = attr->value;
831 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800832 }
833 }
834 }
835
Adam Lesinski8780eb62017-10-31 17:44:39 -0700836 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800837 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700838 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800839 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700840 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700841 for (const std::string& path : options_.include_paths) {
842 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000843 context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700844 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700845
Adam Lesinski8780eb62017-10-31 17:44:39 -0700846 std::string error;
847 auto zip_collection = io::ZipFileCollection::Create(path, &error);
848 if (zip_collection == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000849 context_->GetDiagnostics()->Error(android::DiagMessage()
850 << "failed to open APK: " << error);
Adam Lesinski8780eb62017-10-31 17:44:39 -0700851 return false;
852 }
853
854 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
855 // Load this as a static library include.
856 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000857 android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
Adam Lesinski8780eb62017-10-31 17:44:39 -0700858 if (static_apk == nullptr) {
859 return false;
860 }
861
Adam Lesinskib522f042017-04-21 16:57:59 -0700862 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800863 // Can't include static libraries when not building a static library (they have no IDs
864 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700865 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000866 android::DiagMessage(path)
867 << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 return false;
869 }
870
Adam Lesinski8780eb62017-10-31 17:44:39 -0700871 ResourceTable* table = static_apk->GetResourceTable();
872
873 // If we are using --no-static-lib-packages, we need to rename the package of this table to
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700874 // our compilation package so the symbol package name does not get mangled into the entry
875 // name.
876 if (options_.no_static_lib_packages && !table->packages.empty()) {
877 auto lib_package_result = GetStaticLibraryPackage(table);
878 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000879 context_->GetDiagnostics()->Error(android::DiagMessage(path)
880 << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800881 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700883 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700884 }
885
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700886 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700887 util::make_unique<ResourceTableSymbolSource>(table));
888 static_library_includes_.push_back(std::move(static_apk));
889 } else {
890 if (!asset_source->AddAssetPath(path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000891 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinski8780eb62017-10-31 17:44:39 -0700892 << "failed to load include path " << path);
893 return false;
894 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700895 }
896 }
897
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800898 // Capture the shared libraries so that the final resource table can be properly flattened
899 // with support for shared libraries.
900 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700901 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800902 // Capture the included base feature package.
903 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800904 } else if (entry.first == kFrameworkPackageId) {
905 // Try to embed which version of the framework we're compiling against.
906 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
907 // when linking our synthesized 'android:compileSdkVersion' attribute.
908 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
909 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
910 if (symbol != nullptr && symbol->is_public) {
911 // The symbol is present and public, extract the android:versionName and
912 // android:versionCode from the framework AndroidManifest.xml.
913 ExtractCompileSdkVersions(asset_source->GetAssetManager());
914 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700915 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700916 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800917 }
918 }
919
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700920 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 return true;
922 }
923
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000924 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
925 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800926 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700927 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800928 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
929 if (manifest_el == nullptr) {
930 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700931 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800932
933 AppInfo app_info;
934
935 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000936 diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800937 return {};
938 }
939
940 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
941 if (!package_attr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000942 diag->Error(android::DiagMessage(xml_res->file.source)
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800943 << "<manifest> must have a 'package' attribute");
944 return {};
945 }
946 app_info.package = package_attr->value;
947
948 if (xml::Attribute* version_code_attr =
949 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700950 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800951 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000952 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800953 << "invalid android:versionCode '" << version_code_attr->value << "'");
954 return {};
955 }
956 app_info.version_code = maybe_code.value();
957 }
958
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700959 if (xml::Attribute* version_code_major_attr =
960 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700961 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700962 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000963 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
964 << "invalid android:versionCodeMajor '" << version_code_major_attr->value
965 << "'");
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700966 return {};
967 }
968 app_info.version_code_major = maybe_code.value();
969 }
970
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800971 if (xml::Attribute* revision_code_attr =
972 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700973 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800974 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000975 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800976 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
977 return {};
978 }
979 app_info.revision_code = maybe_code.value();
980 }
981
982 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
983 if (!split_name_attr->value.empty()) {
984 app_info.split_name = split_name_attr->value;
985 }
986 }
987
988 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
989 if (xml::Attribute* min_sdk =
990 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700991 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800992 }
993 }
Udam Sainib228df32019-06-18 16:50:34 -0700994
995 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
996 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
997 if (const xml::Attribute* split_name =
998 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
999 if (!split_name->value.empty()) {
1000 app_info.split_name_dependencies.insert(split_name->value);
1001 }
1002 }
1003 }
1004 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -08001005 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001006 }
1007
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001008 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1009 // Postcondition: ResourceTable has only one package left. All others are
1010 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001012 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001013 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001014 };
1015
1016 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001017 for (const auto& package : final_table_.packages) {
1018 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 // We have a package that is not related to the one we're building!
1020 for (const auto& type : package->types) {
1021 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001022 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001024 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001025 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001026 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001027 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001028 context_->GetDiagnostics()->Warn(
1029 android::DiagMessage(config_value->value->GetSource())
1030 << "generated id '" << res_name << "' for external package '" << package->name
1031 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001032 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001033 context_->GetDiagnostics()->Error(
1034 android::DiagMessage(config_value->value->GetSource())
1035 << "defined resource '" << res_name << "' for external package '"
1036 << package->name << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001037 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001039 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001040 }
1041 }
1042 }
1043 }
1044
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001045 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1046 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001047 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001048 return !error;
1049 }
1050
1051 /**
1052 * Returns true if no IDs have been set, false otherwise.
1053 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001054 bool VerifyNoIdsSet() {
1055 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001056 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001057 for (const auto& entry : type->entries) {
1058 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001059 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001060 context_->GetDiagnostics()->Error(android::DiagMessage()
1061 << "resource " << res_name << " has ID "
1062 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063 return false;
1064 }
1065 }
1066 }
1067 }
1068 return true;
1069 }
1070
Josh Houec67cb42022-06-09 19:19:21 +08001071 bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
1072 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1073 // element.
1074 const xml::Element* application = manifest->root->FindChild("", "application");
1075 if (!application) {
1076 return true;
1077 }
1078 const xml::Attribute* localeConfig =
1079 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1080 if (!localeConfig) {
1081 return true;
1082 }
1083
1084 // Deserialize XML from the compiled file
1085 if (localeConfig->compiled_value) {
1086 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1087 const auto localeconfig_entry =
1088 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1089 if (!localeconfig_entry) {
Iurii Makhnoa7ba6b62022-11-11 17:59:57 +00001090 // If locale config is resolved from external symbols - skip validation.
1091 if (context_->GetExternalSymbols()->FindByReference(*localeconfig_reference)) {
1092 return true;
1093 }
Josh Houec67cb42022-06-09 19:19:21 +08001094 context_->GetDiagnostics()->Error(
1095 android::DiagMessage(localeConfig->compiled_value->GetSource())
1096 << "no localeConfig entry");
1097 return false;
1098 }
1099 for (const auto& value : localeconfig_entry->values) {
1100 const FileReference* file_ref = ValueCast<FileReference>(value->value.get());
1101 if (!file_ref) {
1102 context_->GetDiagnostics()->Error(
1103 android::DiagMessage(localeConfig->compiled_value->GetSource())
1104 << "no file reference");
1105 return false;
1106 }
1107 io::IFile* file = file_ref->file;
1108 if (!file) {
1109 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
1110 << "file not found");
1111 return false;
1112 }
1113 std::unique_ptr<io::IData> data = file->OpenAsData();
1114 if (!data) {
1115 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1116 << "failed to open file");
1117 return false;
1118 }
1119 pb::XmlNode pb_xml_node;
1120 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
1121 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1122 << "failed to parse proto XML");
1123 return false;
1124 }
1125
1126 std::string error;
1127 std::unique_ptr<xml::XmlResource> localeConfig_xml =
1128 DeserializeXmlResourceFromPb(pb_xml_node, &error);
1129 if (!localeConfig_xml) {
1130 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1131 << "failed to deserialize proto XML: " << error);
1132 return false;
1133 }
1134 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1135 if (!localeConfig_el) {
1136 diag->Error(android::DiagMessage(file->GetSource()) << "no root tag defined");
1137 return false;
1138 }
1139 if (localeConfig_el->name != "locale-config") {
1140 diag->Error(android::DiagMessage(file->GetSource())
1141 << "invalid element name: " << localeConfig_el->name
1142 << ", expected: locale-config");
1143 return false;
1144 }
1145 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1146 if (child_el->name == "locale") {
1147 if (const xml::Attribute* locale_name_attr =
1148 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1149 const std::string& locale_name = locale_name_attr->value;
1150 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1151 // Start to verify the locale format
1152 ConfigDescription config;
1153 if (!ConfigDescription::Parse(valid_name, &config)) {
1154 diag->Error(android::DiagMessage(file->GetSource())
1155 << "invalid configuration: " << locale_name);
1156 return false;
1157 }
1158 } else {
1159 diag->Error(android::DiagMessage(file->GetSource())
1160 << "the attribute android:name is not found");
1161 return false;
1162 }
1163 } else {
1164 diag->Error(android::DiagMessage(file->GetSource())
1165 << "invalid element name: " << child_el->name << ", expected: locale");
1166 return false;
1167 }
1168 }
1169 }
1170 }
1171 return true;
1172 }
1173
1174 std::string ConvertToBCP47Tag(const std::string& locale) {
1175 std::string bcp47tag = "b+";
1176 bcp47tag += locale;
1177 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1178 return bcp47tag;
1179 }
1180
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001181 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001182 if (options_.output_to_directory) {
1183 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001185 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001186 }
1187 }
1188
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001189 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001190 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001191 switch (format) {
1192 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001193 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001194 TableFlattener flattener(options_.table_flattener_options, &buffer);
1195 if (!flattener.Consume(context_, table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001196 context_->GetDiagnostics()->Error(android::DiagMessage()
1197 << "failed to flatten resource table");
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001198 return false;
1199 }
1200
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001201 android::BigBufferInputStream input_stream(&buffer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001202 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1203 ArchiveEntry::kAlign, writer);
1204 } break;
1205
1206 case OutputFormat::kProto: {
1207 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001208 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1209 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001210 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1211 ArchiveEntry::kCompress, writer);
1212 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001213 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001214 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001215 }
1216
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001217 bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate,
1218 StringPiece out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001219 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001220 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 return true;
1222 }
1223
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001224 std::string out_path;
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001225 std::unique_ptr<android::FileOutputStream> fout;
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001226 if (options_.generate_java_class_path) {
1227 out_path = options_.generate_java_class_path.value();
1228 file::AppendPath(&out_path, file::PackageToPath(out_package));
1229 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001230 context_->GetDiagnostics()->Error(android::DiagMessage()
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001231 << "failed to create directory '" << out_path << "'");
1232 return false;
1233 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001235 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001237 fout = util::make_unique<android::FileOutputStream>(out_path);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001238 if (fout->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001239 context_->GetDiagnostics()->Error(android::DiagMessage()
1240 << "failed writing to '" << out_path
1241 << "': " << fout->GetError());
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001242 return false;
1243 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001244 }
1245
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001246 std::unique_ptr<android::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001247 if (out_text_symbols_path) {
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001248 fout_text = util::make_unique<android::FileOutputStream>(out_text_symbols_path.value());
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001249 if (fout_text->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001250 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001251 << "failed writing to '" << out_text_symbols_path.value()
1252 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001253 return false;
1254 }
1255 }
1256
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001258 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001259 context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001260 return false;
1261 }
1262
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001263 return true;
1264 }
1265
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001266 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001267 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001268 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1269 std::vector<std::string> packages_to_callback;
1270
1271 JavaClassGeneratorOptions template_options;
1272 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1273 template_options.javadoc_annotations = options_.javadoc_annotations;
1274
1275 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1276 template_options.use_final = false;
1277 }
1278
1279 if (context_->GetPackageType() == PackageType::kSharedLib) {
1280 template_options.use_final = false;
1281 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1282 }
1283
1284 const StringPiece actual_package = context_->GetCompilationPackage();
1285 StringPiece output_package = context_->GetCompilationPackage();
1286 if (options_.custom_java_package) {
1287 // Override the output java package to the custom one.
1288 output_package = options_.custom_java_package.value();
1289 }
1290
1291 // Generate the private symbols if required.
1292 if (options_.private_symbols) {
1293 packages_to_callback.push_back(options_.private_symbols.value());
1294
1295 // If we defined a private symbols package, we only emit Public symbols
1296 // to the original package, and private and public symbols to the private package.
1297 JavaClassGeneratorOptions options = template_options;
1298 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1299 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1300 options)) {
1301 return false;
1302 }
1303 }
1304
1305 // Generate copies of the original package R class but with different package names.
1306 // This is to support non-namespaced builds.
1307 for (const std::string& extra_package : options_.extra_java_packages) {
1308 packages_to_callback.push_back(extra_package);
1309
1310 JavaClassGeneratorOptions options = template_options;
1311 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1312 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1313 return false;
1314 }
1315 }
1316
1317 // Generate R classes for each package that was merged (static library).
1318 // Use the actual package's resources only.
1319 for (const std::string& package : table_merger_->merged_packages()) {
1320 packages_to_callback.push_back(package);
1321
1322 JavaClassGeneratorOptions options = template_options;
1323 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1324 if (!WriteJavaFile(&final_table_, package, package, options)) {
1325 return false;
1326 }
1327 }
1328
1329 // Generate the main public R class.
1330 JavaClassGeneratorOptions options = template_options;
1331
1332 // Only generate public symbols if we have a private package.
1333 if (options_.private_symbols) {
1334 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1335 }
1336
1337 if (options.rewrite_callback_options) {
1338 options.rewrite_callback_options.value().packages_to_callback =
1339 std::move(packages_to_callback);
1340 }
1341
1342 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1343 options_.generate_text_symbols_path)) {
1344 return false;
1345 }
1346
1347 return true;
1348 }
1349
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001350 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001351 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001352 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001353 return true;
1354 }
1355
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001356 std::unique_ptr<ClassDefinition> manifest_class =
1357 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001359 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001360 // Something bad happened, but we already logged it, so exit.
1361 return false;
1362 }
1363
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001364 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001365 // Empty Manifest class, no need to generate it.
1366 return true;
1367 }
1368
1369 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001370 for (const std::string& annotation : options_.javadoc_annotations) {
1371 std::string proper_annotation = "@";
1372 proper_annotation += annotation;
1373 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374 }
1375
Adam Lesinski0d81f702017-06-27 15:51:09 -07001376 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001377 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 std::string out_path = options_.generate_java_class_path.value();
1380 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001381
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001382 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001383 context_->GetDiagnostics()->Error(android::DiagMessage()
1384 << "failed to create directory '" << out_path << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001385 return false;
1386 }
1387
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001388 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001389
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001390 android::FileOutputStream fout(out_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001391 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001392 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1393 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 return false;
1395 }
1396
Makoto Onukide6e6f22020-06-22 10:17:02 -07001397 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1398 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001399 fout.Flush();
1400
1401 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001402 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1403 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001404 return false;
1405 }
1406 return true;
1407 }
1408
Ryan Mitchell4382e442021-07-14 12:53:01 -07001409 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001410 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 if (!out) {
1412 return true;
1413 }
1414
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 const std::string& out_path = out.value();
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001416 android::FileOutputStream fout(out_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001417 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001418 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1419 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 return false;
1421 }
1422
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001423 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1424 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001425 fout.Flush();
1426
1427 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001428 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1429 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001430 return false;
1431 }
1432 return true;
1433 }
1434
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001435 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001436 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001437 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001438 context_->GetDiagnostics()->Note(android::DiagMessage()
1439 << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001440 }
1441
Adam Lesinski8780eb62017-10-31 17:44:39 -07001442 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1443 if (apk == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001444 context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001445 return false;
1446 }
1447
Adam Lesinski8780eb62017-10-31 17:44:39 -07001448 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001449 if (table->packages.empty()) {
1450 return true;
1451 }
1452
1453 auto lib_package_result = GetStaticLibraryPackage(table);
1454 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001455 context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001456 return false;
1457 }
1458
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001459 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001460 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001461 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001462 // Merge all resources as if they were in the compilation package. This is the old behavior
1463 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001465 // Add the package to the set of --extra-packages so we emit an R.java for each library
1466 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001467 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001468 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001469 }
1470
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001471 // Clear the package name, so as to make the resources look like they are coming from the
1472 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 pkg->name = "";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001474 result = table_merger_->Merge(android::Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001475
1476 } else {
1477 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001478 // preserved and resource names are mangled.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001479 result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001480 }
1481
1482 if (!result) {
1483 return false;
1484 }
1485
1486 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001487 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001488 return true;
1489 }
1490
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001491 bool MergeExportedSymbols(const android::Source& source,
Adam Lesinski2427dce2017-11-30 15:10:28 -08001492 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001493 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001494 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001495 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001496 ResourceName res_name = exported_symbol.name;
1497 if (res_name.package.empty()) {
1498 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001499 }
1500
Ryan Mitchell4382e442021-07-14 12:53:01 -07001501 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001502 if (mangled_name) {
1503 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001504 }
1505
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001506 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001507 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001508 bool result = final_table_.AddResource(
1509 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1510 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001511 if (!result) {
1512 return false;
1513 }
1514 }
1515 return true;
1516 }
1517
Adam Lesinski2427dce2017-11-30 15:10:28 -08001518 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001519 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001520 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001521 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski2427dce2017-11-30 15:10:28 -08001522 << "merging '" << compiled_file.name
1523 << "' from compiled file " << compiled_file.source);
1524 }
1525
1526 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1527 return false;
1528 }
1529 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1530 }
1531
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001532 // 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 -07001533 // If override is true, conflicting resources are allowed to override each other, in order of last
1534 // seen.
1535 // An io::IFileCollection is created from the ZIP file and added to the set of
1536 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001537 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001538 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001539 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001540 context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001541 }
1542
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001543 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001544 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001545 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001546 if (!collection) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001547 context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001548 return false;
1549 }
1550
1551 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001552 for (auto iter = collection->Iterator(); iter->HasNext();) {
1553 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001554 error = true;
1555 }
1556 }
1557
1558 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001559 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001560 return !error;
1561 }
1562
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001563 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001564 // conflicting resources are allowed to override each other, in order of last seen.
1565 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1566 // as ZIP archive and the files within are merged individually.
1567 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001568 bool MergePath(const std::string& path, bool override) {
1569 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1570 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1571 return MergeArchive(path, override);
1572 } else if (util::EndsWith(path, ".apk")) {
1573 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001574 }
1575
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001576 io::IFile* file = file_collection_->InsertFile(path);
1577 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001578 }
1579
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001580 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001581 // If override is true, conflicting resources are allowed to override each other, in order of last
1582 // seen.
1583 // All other file types are ignored. This is because these files could be coming from a zip,
1584 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001585 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001586 TRACE_CALL();
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001587 const android::Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588
Adam Lesinski00451162017-10-03 07:44:08 -07001589 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001590 // Since AAPT compiles these file types and appends .flat to them, seeing
1591 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001592 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001593 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1594 << "uncompiled " << file_type
1595 << " file passed as argument. Must be "
1596 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001597 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001598 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1599 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001600 context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
Adam Lesinski00451162017-10-03 07:44:08 -07001601 return true;
1602 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001603 }
1604
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001605 std::unique_ptr<android::InputStream> input_stream = file->OpenInputStream();
Adam Lesinski00451162017-10-03 07:44:08 -07001606 if (input_stream == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001607 context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
Adam Lesinski00451162017-10-03 07:44:08 -07001608 return false;
1609 }
1610
1611 if (input_stream->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001612 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001613 << "failed to open file: " << input_stream->GetError());
1614 return false;
1615 }
1616
1617 ContainerReaderEntry* entry;
1618 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001619
1620 if (reader.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001621 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Mohamed Heikal10844322018-02-07 15:17:38 -05001622 << "failed to read file: " << reader.GetError());
1623 return false;
1624 }
1625
Adam Lesinski00451162017-10-03 07:44:08 -07001626 while ((entry = reader.Next()) != nullptr) {
1627 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001628 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001629 pb::ResourceTable pb_table;
1630 if (!entry->GetResTable(&pb_table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001631 context_->GetDiagnostics()->Error(
1632 android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001633 return false;
1634 }
1635
1636 ResourceTable table;
1637 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001638 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001639 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001640 << "failed to deserialize resource table: " << error);
1641 return false;
1642 }
1643
1644 if (!table_merger_->Merge(src, &table, override)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001645 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1646 << "failed to merge resource table");
Adam Lesinski00451162017-10-03 07:44:08 -07001647 return false;
1648 }
1649 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001650 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001651 pb::internal::CompiledFile pb_compiled_file;
1652 off64_t offset;
1653 size_t len;
1654 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001655 context_->GetDiagnostics()->Error(
1656 android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001657 return false;
1658 }
1659
1660 ResourceFile resource_file;
1661 std::string error;
1662 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001663 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001664 << "failed to read compiled header: " << error);
1665 return false;
1666 }
1667
1668 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1669 return false;
1670 }
1671 }
1672 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001673 return true;
1674 }
1675
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001676 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1677 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1678 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001679 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001680 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1681 if (!files) {
1682 return false;
1683 }
1684
1685 for (const std::string& file : files.value()) {
1686 std::string full_key = "assets/" + file;
1687 std::string full_path = assets_dir;
1688 file::AppendPath(&full_path, file);
1689
1690 auto iter = merged_assets.find(full_key);
1691 if (iter == merged_assets.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001692 merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1693 android::Source(std::move(full_path))));
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001694 } else if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001695 context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001696 << "asset file overrides '" << full_path << "'");
1697 }
1698 }
1699 }
1700
1701 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001702 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001703 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1704 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001705 return false;
1706 }
1707 }
1708 return true;
1709 }
1710
Rhed Jao2c434422020-11-12 10:48:03 +08001711 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1712 Reference* reference) {
1713 if (!reference || !reference->name) {
1714 return nullptr;
1715 }
1716 auto name_ref = ResourceNameRef(reference->name.value());
1717 if (name_ref.package.empty()) {
1718 name_ref.package = context->GetCompilationPackage();
1719 }
1720 const auto search_result = table->FindResource(name_ref);
1721 if (!search_result) {
1722 return nullptr;
1723 }
1724 return search_result.value().entry;
1725 }
1726
Ryan Mitchelldba64562019-06-07 17:07:37 -07001727 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001728 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001729 if (!application) {
1730 return;
1731 }
1732
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001733 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1734 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001735 if (!icon || !round_icon) {
1736 return;
1737 }
1738
1739 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001740 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001741 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1742 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001743 return;
1744 }
1745
1746 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001747 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001748 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1749 ? config_value->config.sdkVersion : icon_max_sdk;
1750 }
1751 if (icon_max_sdk < SDK_O) {
1752 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1753 return;
1754 }
1755
1756 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001757 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001758 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1759 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001760 return;
1761 }
1762
1763 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001764 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001765 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1766 ? config_value->config.sdkVersion : round_icon_max_sdk;
1767 }
1768 if (round_icon_max_sdk >= SDK_O) {
1769 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1770 // not generate an alias to the icon drawable.
1771 return;
1772 }
1773
1774 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001775 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001776 if (config_value->config.sdkVersion < SDK_O) {
1777 continue;
1778 }
1779
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001780 context_->GetDiagnostics()->Note(android::DiagMessage()
1781 << "generating " << round_icon_reference->name.value()
1782 << " with config \"" << config_value->config
1783 << "\" for round icon compatibility");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001784
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001785 CloningValueTransformer cloner(&table->string_pool);
1786 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001787 auto round_config_value =
1788 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001789 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001790 }
1791 }
1792
Rhed Jao2c434422020-11-12 10:48:03 +08001793 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1794 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1795 if (manifest_el == nullptr) {
1796 return true;
1797 }
1798 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1799 return true;
1800 }
1801 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1802 if (!attr) {
1803 return true;
1804 }
1805 const auto validate = [&](const std::string& shared_user_id) -> bool {
1806 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1807 return true;
1808 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001809 android::DiagMessage error_msg(manifest_el->line_number);
Rhed Jao2c434422020-11-12 10:48:03 +08001810 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1811 << shared_user_id << "'";
1812 if (options_.manifest_fixer_options.warn_validation) {
1813 // Treat the error only as a warning.
1814 context_->GetDiagnostics()->Warn(error_msg);
1815 return true;
1816 }
1817 context_->GetDiagnostics()->Error(error_msg);
1818 return false;
1819 };
1820 // If attr->compiled_value is not null, check if it is a ref
1821 if (attr->compiled_value) {
1822 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1823 if (ref == nullptr) {
1824 return true;
1825 }
1826 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1827 if (!shared_user_id_entry) {
1828 return true;
1829 }
1830 for (const auto& value : shared_user_id_entry->values) {
1831 const auto str_value = ValueCast<String>(value->value.get());
1832 if (str_value != nullptr && !validate(*str_value->value)) {
1833 return false;
1834 }
1835 }
1836 return true;
1837 }
1838
1839 // Fallback to checking the raw value
1840 return validate(attr->value);
1841 }
1842
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001843 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1844 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001845 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1846 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001847 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001848 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1849 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001850 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001851 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852 if (!result) {
1853 return false;
1854 }
1855
Ryan Mitchelldba64562019-06-07 17:07:37 -07001856 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1857 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1858 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1859 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1860 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1861 // See (b/34829129)
1862 AliasAdaptiveIcon(manifest, table);
1863
Rhed Jao2c434422020-11-12 10:48:03 +08001864 // Verify the shared user id here to handle the case of reference value.
1865 if (!VerifySharedUserId(manifest, table)) {
1866 return false;
1867 }
1868
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 ResourceFileFlattenerOptions file_flattener_options;
1870 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1872 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001873 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001874 file_flattener_options.no_auto_version = options_.no_auto_version;
1875 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001876 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001877 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1878 file_flattener_options.update_proguard_spec =
1879 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001880 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001881 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001883 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 if (!file_flattener.Flatten(table, writer)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001885 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886 return false;
1887 }
1888
Adam Lesinski490595a2017-11-07 17:08:07 -08001889 // Hack to fix b/68820737.
1890 // We need to modify the ResourceTable's package name, but that should NOT affect
1891 // anything else being generated, which includes the Java classes.
1892 // If required, the package name is modifed before flattening, and then modified back
1893 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001894 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001895 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1896 // or higher] as invalid. In order to work around this limitation, we allow the use
1897 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1898 // definition of what a valid "split" package ID is to account for this.
1899 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1900 context_->GetPackageId() != kAppPackageId &&
1901 context_->GetPackageId() != kFrameworkPackageId)
1902 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001903 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001904 // The base APK is included, and this is a feature split. If the base package is
1905 // the same as this package, then we are building an old style Android Instant Apps feature
1906 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001907 if (!table->packages.empty() &&
1908 table->packages.back()->name == context_->GetCompilationPackage()) {
1909 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001910 std::string new_package_name =
1911 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001912 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001913
1914 if (context_->IsVerbose()) {
1915 context_->GetDiagnostics()->Note(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001916 android::DiagMessage() << "rewriting resource package name for feature split to '"
1917 << new_package_name << "'");
Adam Lesinski490595a2017-11-07 17:08:07 -08001918 }
1919 package_to_rewrite->name = new_package_name;
1920 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001921 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001922
1923 bool success = FlattenTable(table, options_.output_format, writer);
1924
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001925 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001926 // Change the name back.
1927 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001928
1929 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1930 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1931 // library, do not include a mapping from the feature package name to the feature package id
1932 // in the feature's dynamic reference table.
1933 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001934 }
1935
1936 if (!success) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001937 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
Adam Lesinski490595a2017-11-07 17:08:07 -08001938 }
1939 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 }
1941
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001943 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 std::unique_ptr<xml::XmlResource> manifest_xml =
1946 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1947 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 return 1;
1949 }
1950
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001951 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001952 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001953 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001954 const AppInfo& app_info = maybe_app_info.value();
1955 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001956 }
1957
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001958 // Determine the package name under which to merge resources.
1959 if (options_.rename_resources_package) {
1960 if (!options_.custom_java_package) {
1961 // Generate the R.java under the original package name instead of the package name specified
1962 // through --rename-resources-package.
1963 options_.custom_java_package = context_->GetCompilationPackage();
1964 }
1965 context_->SetCompilationPackage(options_.rename_resources_package.value());
1966 }
1967
Adam Lesinskic6284372017-12-04 13:46:23 -08001968 // Now that the compilation package is set, load the dependencies. This will also extract
1969 // the Android framework's versionCode and versionName, if they exist.
1970 if (!LoadSymbolsFromIncludePaths()) {
1971 return 1;
1972 }
1973
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1975 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001976 return 1;
1977 }
1978
Ryan Mitchell4382e442021-07-14 12:53:01 -07001979 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001980 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001982 return 1;
1983 }
1984
Adam Lesinski490595a2017-11-07 17:08:07 -08001985 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001986 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001987
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001988 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001989 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001990
Mark Punzalan12dc2b82024-01-24 22:58:41 -08001991 std::unique_ptr<xml::XmlResource> pre_flags_filter_manifest_xml = manifest_xml->Clone();
1992
Mark Punzalan4b564de2024-01-05 02:17:20 -08001993 FeatureFlagsFilterOptions flags_filter_options;
1994 if (context_->GetMinSdkVersion() > SDK_UPSIDE_DOWN_CAKE) {
1995 // For API version > U, PackageManager will dynamically read the flag values and disable
1996 // manifest elements accordingly when parsing the manifest.
1997 // For API version <= U, we remove disabled elements from the manifest with the filter.
1998 flags_filter_options.remove_disabled_elements = false;
1999 flags_filter_options.flags_must_have_value = false;
2000 }
2001 FeatureFlagsFilter flags_filter(options_.feature_flag_values, flags_filter_options);
2002 if (!flags_filter.Consume(context_, manifest_xml.get())) {
2003 return 1;
2004 }
2005
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002006 // Override the package ID when it is "android".
2007 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002008 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002009
2010 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07002011 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002012 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002013 android::DiagMessage() << "package 'android' can only be built as a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002014 return 1;
2015 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 }
2017
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002018 TableMergerOptions table_merger_options;
2019 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07002020 table_merger_options.override_styles_instead_of_overlaying =
2021 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01002022 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002024
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002025 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002026 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002027 << StringPrintf("linking package '%s' using package ID %02x",
2028 context_->GetCompilationPackage().data(),
2029 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 }
2031
Adam Lesinski2427dce2017-11-30 15:10:28 -08002032 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
2033 // in res/**/*.
2034 {
2035 XmlIdCollector collector;
2036 if (!collector.Consume(context_, manifest_xml.get())) {
2037 return false;
2038 }
2039
2040 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
2041 return false;
2042 }
2043 }
2044
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 for (const std::string& input : input_files) {
2046 if (!MergePath(input, false)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002047 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002048 return 1;
2049 }
2050 }
2051
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002052 for (const std::string& input : options_.overlay_files) {
2053 if (!MergePath(input, true)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002054 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002055 return 1;
2056 }
2057 }
2058
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002059 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 return 1;
2061 }
2062
Adam Lesinskib522f042017-04-21 16:57:59 -07002063 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002065 if (context_->GetPackageId() == kAndroidPackageId &&
2066 !mover.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002067 context_->GetDiagnostics()->Error(android::DiagMessage()
2068 << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 return 1;
2070 }
2071
2072 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002073 IdAssigner id_assigner(&options_.stable_id_map);
2074 if (!id_assigner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002075 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002076 return 1;
2077 }
2078
2079 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002080 if (options_.resource_id_map_path) {
2081 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082 for (auto& type : package->types) {
2083 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002084 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002085 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002086 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 }
2088 }
2089 }
2090
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002091 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002093 return 1;
2094 }
2095 }
2096 } else {
2097 // Static libs are merged with other apps, and ID collisions are bad, so
2098 // verify that
2099 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002100 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002101 return 1;
2102 }
2103 }
2104
2105 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002106 context_->SetNameManglerPolicy(
2107 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002108
2109 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002110 context_->GetExternalSymbols()->PrependSource(
2111 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002112
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002113 // Workaround for pre-O runtime that would treat negative resource IDs
2114 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2115 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2116 // are just identifiers.
2117 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2118 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002119 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002120 << "enabling pre-O feature split ID rewriting");
2121 }
2122 context_->GetExternalSymbols()->SetDelegate(
2123 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2124 }
2125
Adam Lesinski34a16872018-02-23 16:18:10 -08002126 // Before we process anything, remove the resources whose default values don't exist.
2127 // We want to force any references to these to fail the build.
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002128 if (!options_.no_resource_removal) {
2129 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002130 context_->GetDiagnostics()->Error(android::DiagMessage()
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002131 << "failed removing resources with no defaults");
2132 return 1;
2133 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002134 }
2135
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002136 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002137 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002138 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002139 return 1;
2140 }
2141
Adam Lesinskib522f042017-04-21 16:57:59 -07002142 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002143 if (!options_.products.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002144 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002145 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146 }
2147 } else {
Inseob Kim5fe521e2023-09-15 16:38:50 +09002148 ProductFilter product_filter(options_.products, /* remove_default_config_values = */ false);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002149 if (!product_filter.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002150 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151 return 1;
2152 }
2153 }
2154
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002155 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002157 if (!versioner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002158 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002159 return 1;
2160 }
2161 }
2162
Adam Lesinskib522f042017-04-21 16:57:59 -07002163 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002165 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002166 << "collapsing resource versions for minimum SDK "
2167 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 }
2169
2170 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002171 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002172 return 1;
2173 }
2174 }
2175
Winson3c918b82019-01-25 14:25:37 -08002176 if (!options_.exclude_configs_.empty()) {
2177 std::vector<ConfigDescription> excluded_configs;
2178
2179 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002180 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002181 ConfigDescription config_description;
2182
2183 if (!ConfigDescription::Parse(config_string, &config_description)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002184 context_->GetDiagnostics()->Error(
2185 android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
Winson3c918b82019-01-25 14:25:37 -08002186 return 1;
2187 }
2188
2189 excluded_configs.push_back(config_description);
2190 }
2191
2192 ResourceExcluder excluder(excluded_configs);
2193 if (!excluder.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002194 context_->GetDiagnostics()->Error(android::DiagMessage()
2195 << "failed excluding configurations");
Winson3c918b82019-01-25 14:25:37 -08002196 return 1;
2197 }
2198 }
2199
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002200 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002202 if (!deduper.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002203 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002204 return 1;
2205 }
2206 }
2207
Adam Koskidc21dea2017-07-21 10:55:27 -07002208 proguard::KeepSet proguard_keep_set =
2209 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002210 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002211
Adam Lesinskib522f042017-04-21 16:57:59 -07002212 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002213 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002214 !options_.table_splitter_options.preferred_densities.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002215 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002216 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002217 }
2218 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002219 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2220 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002221 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002222 options_.split_constraints =
2223 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002224
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002225 if (origConstraintSize != options_.split_constraints.size()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002226 context_->GetDiagnostics()->Warn(android::DiagMessage()
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002227 << "requested to split resources prior to min sdk of "
2228 << context_->GetMinSdkVersion());
2229 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002230 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002231 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002232 return 1;
2233 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002234 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002235
2236 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002237 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002238 auto split_constraints_iter = options_.split_constraints.begin();
2239 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002240 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002241 context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002242 << "generating split with configurations '"
2243 << util::Joiner(split_constraints_iter->configs, ", ")
2244 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002245 }
2246
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002247 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002248 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002249 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002250 return 1;
2251 }
2252
2253 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002254 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002255 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002256
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002257 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002258 if (!linker.Consume(context_, split_manifest.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002259 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002260 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002261 return 1;
2262 }
2263
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002264 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2265 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 return 1;
2267 }
2268
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002269 ++path_iter;
2270 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271 }
2272 }
2273
2274 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002275 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002276 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002277 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002278 return 1;
2279 }
2280
2281 bool error = false;
2282 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002283 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002284 // (aka, which package the AndroidManifest.xml is coming from).
2285 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002286 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002287
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002288 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002289 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002290 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002291 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002292 error = true;
2293 }
2294
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002295 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002296 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002297 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002298 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002299 }
2300
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002301 if (options_.generate_java_class_path) {
Mark Punzalan12dc2b82024-01-24 22:58:41 -08002302 // The FeatureFlagsFilter may remove <permission> and <permission-group> elements that
2303 // generate constants in the Manifest Java file. While we want those permissions and
2304 // permission groups removed in the SDK (i.e., if a feature flag is disabled), the
2305 // constants should still remain so that code referencing it (e.g., within a feature
2306 // flag check) will still compile. Therefore we use the manifest XML before the filter.
2307 if (!WriteManifestJavaFile(pre_flags_filter_manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002308 error = true;
2309 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002310 }
2311
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002312 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002313 // PackageParser will fail if URIs are removed from
2314 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002315 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2316 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002317 error = true;
2318 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002319 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002320 } else {
2321 error = true;
2322 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002323 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002324
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002325 if (error) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002326 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002327 return 1;
2328 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002329
Josh Houec67cb42022-06-09 19:19:21 +08002330 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2331 return 1;
2332 };
2333
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002334 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2335 return 1;
2336 }
2337
2338 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002339 return 1;
2340 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002341
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002342 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002343 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002344 return 1;
2345 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002346 }
2347
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002348 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002349 return 1;
2350 }
2351
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002352 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2353 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002354 return 1;
2355 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002356 return 0;
2357 }
2358
2359 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002360 LinkOptions options_;
2361 LinkContext* context_;
2362 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002363
Adam Lesinski490595a2017-11-07 17:08:07 -08002364 AppInfo app_info_;
2365
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002366 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002367
2368 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002369 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002370
Adam Lesinski8780eb62017-10-31 17:44:39 -07002371 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002372 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002373 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002374
Adam Lesinski8780eb62017-10-31 17:44:39 -07002375 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2376 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2377
2378 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2379 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002380
2381 // The set of shared libraries being used, mapping their assigned package ID to package name.
2382 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002383
2384 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002385 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002386};
2387
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002388int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002389 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002390 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002391
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002392 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002393 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002394 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002395 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002396 const std::string path = arg.substr(1, arg.size() - 1);
2397 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002398 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002399 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002400 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002401 }
2402 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002403 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002404 }
2405 }
2406
2407 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002408 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002409 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002410 const std::string path = arg.substr(1, arg.size() - 1);
2411 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002412 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002413 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002414 return 1;
2415 }
2416 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002417 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002418 }
2419 }
2420
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002421 if (verbose_) {
2422 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002423 }
2424
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002425 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002426 context.GetDiagnostics()
2427 ->Error(android::DiagMessage()
2428 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002429 return 1;
2430 }
2431
Ryan Mitchell5855de72021-02-24 14:39:13 -08002432 if (shared_lib_ && options_.private_symbols) {
2433 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2434 // reference the private attribute within the styleable array will cause a link error because
2435 // the private attribute will not be emitted in the public R.java.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002436 context.GetDiagnostics()->Error(android::DiagMessage()
Ryan Mitchell5855de72021-02-24 14:39:13 -08002437 << "--shared-lib cannot currently be used in combination with"
2438 << " --private-symbols");
2439 return 1;
2440 }
2441
Izabela Orlowska84febea2019-06-03 18:34:12 +01002442 if (options_.merge_only && !static_lib_) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002443 context.GetDiagnostics()
2444 ->Error(android::DiagMessage()
2445 << "the --merge-only flag can be only used when building a static library");
Izabela Orlowska84febea2019-06-03 18:34:12 +01002446 return 1;
2447 }
Iurii Makhnoda06e4d2022-08-24 14:17:32 +00002448 if (options_.use_sparse_encoding) {
2449 options_.table_flattener_options.sparse_entries = SparseEntriesMode::Enabled;
2450 }
Izabela Orlowska84febea2019-06-03 18:34:12 +01002451
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002452 // The default build type.
2453 context.SetPackageType(PackageType::kApp);
2454 context.SetPackageId(kAppPackageId);
2455
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002456 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002457 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002458 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002459 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002460 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002461 options_.output_format = OutputFormat::kProto;
2462 } else if (proto_format_) {
2463 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002464 }
2465
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002466 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002467 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002468 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002469 android::DiagMessage() << "can't specify --package-id when not building a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002470 return 1;
2471 }
2472
Ryan Mitchell4382e442021-07-14 12:53:01 -07002473 const std::optional<uint32_t> maybe_package_id_int =
2474 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002475 if (!maybe_package_id_int) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002476 context.GetDiagnostics()->Error(android::DiagMessage()
2477 << "package ID '" << package_id_.value()
2478 << "' is not a valid integer");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002479 return 1;
2480 }
2481
2482 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002483 if (package_id_int > std::numeric_limits<uint8_t>::max()
2484 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002485 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002486 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002487 android::DiagMessage() << StringPrintf(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002488 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2489 return 1;
2490 }
2491 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2492 }
2493
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002494 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002495 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002496 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002497 for (StringPiece package : util::Split(extra_package, ':')) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002498 options_.extra_java_packages.emplace(package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002499 }
2500 }
2501
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002502 if (product_list_) {
2503 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002504 if (product != "" && product != "default") {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002505 options_.products.emplace(product);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002506 }
2507 }
2508 }
2509
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002510 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002511 if (!configs_.empty()) {
2512 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002513 if (filter == nullptr) {
2514 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002515 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002516 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002517 }
2518
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002519 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002520 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002521 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002522 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002523 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002524 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002525 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002526 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002527
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002528 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002529 for (const std::string& split_arg : split_args_) {
2530 options_.split_paths.push_back({});
2531 options_.split_constraints.push_back({});
2532 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2533 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002534 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002535 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002536 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002537
Mark Punzalan5579cad2023-10-30 13:47:51 -07002538 // Parse the feature flag values. An argument that starts with '@' points to a file to read flag
2539 // values from.
2540 std::vector<std::string> all_feature_flags_args;
2541 for (const std::string& arg : feature_flags_args_) {
2542 if (util::StartsWith(arg, "@")) {
2543 const std::string path = arg.substr(1, arg.size() - 1);
2544 std::string error;
2545 if (!file::AppendArgsFromFile(path, &all_feature_flags_args, &error)) {
2546 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2547 return 1;
2548 }
2549 } else {
2550 all_feature_flags_args.push_back(arg);
2551 }
2552 }
2553
2554 for (const std::string& arg : all_feature_flags_args) {
Mark Punzalan4b564de2024-01-05 02:17:20 -08002555 if (!ParseFeatureFlagsParameter(arg, context.GetDiagnostics(), &options_.feature_flag_values)) {
Mark Punzalan5579cad2023-10-30 13:47:51 -07002556 return 1;
2557 }
2558 }
2559
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002560 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2561 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2562 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002563 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002564 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002565 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002566
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002567 if (no_compress_regex) {
2568 std::string regex = no_compress_regex.value();
2569 if (util::StartsWith(regex, "@")) {
2570 const std::string path = regex.substr(1, regex.size() -1);
2571 std::string error;
2572 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002573 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002574 return 1;
2575 }
2576 } else {
2577 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2578 }
2579 }
2580
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002581 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002582 options_.extensions_to_not_compress.insert({
2583 // Image extensions
2584 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2585 // Audio extensions
2586 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2587 ".xmf", ".amr", ".awb",
2588 // Audio/video extensions
2589 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2590 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002591
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002592 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002593 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002594 options_.no_auto_version = true;
2595 options_.no_version_vectors = true;
2596 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002597 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002598
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002599 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002600 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002601}
2602
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002603} // namespace aapt