blob: 56f52885b36dce51f24b7f132ba5c69c2043a4cd [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"
Jeremy Meyer423c0f52024-08-02 12:06:54 -070060#include "link/FlagDisabledResourceRemover.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070062#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080063#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080064#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080065#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070067#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080068#include "optimize/ResourceDeduper.h"
69#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070070#include "process/IResourceTableConsumer.h"
Inseob Kim5fe521e2023-09-15 16:38:50 +090071#include "process/ProductFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080073#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080074#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070075#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080076#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070077
MÃ¥rten Kongstad24c9aa62018-06-20 08:46:41 +020078using ::android::ConfigDescription;
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +000079using ::android::FileInputStream;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070080using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070081using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070082using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070083using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070084
Adam Lesinski1ab598f2015-08-14 14:26:04 -070085namespace aapt {
86
Ryan Mitchell9634efb2021-03-19 14:53:17 -070087namespace {
88
89expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
90 // Resource tables built by aapt2 always contain one package. This is a post condition of
91 // VerifyNoExternalPackages.
92 if (table->packages.size() != 1u) {
93 return unexpected("static library contains more than one package");
94 }
95 return table->packages.back().get();
96}
97
98} // namespace
99
Ryan Mitchell22dc5312020-06-01 12:17:07 -0700100constexpr uint8_t kAndroidPackageId = 0x01;
101
Adam Lesinski64587af2016-02-18 18:33:06 -0800102class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 public:
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000104 explicit LinkContext(android::IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100105 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700106 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700107
Adam Lesinskib522f042017-04-21 16:57:59 -0700108 PackageType GetPackageType() override {
109 return package_type_;
110 }
111
112 void SetPackageType(PackageType type) {
113 package_type_ = type;
114 }
115
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000116 android::IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100117 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700118 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700119
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700120 NameMangler* GetNameMangler() override {
121 return &name_mangler_;
122 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700123
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700124 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
125 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800127
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700128 const std::string& GetCompilationPackage() override {
129 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700130 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700131
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700132 void SetCompilationPackage(StringPiece package_name) {
133 compilation_package_ = std::string(package_name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700134 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800135
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 uint8_t GetPackageId() override {
137 return package_id_;
138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700140 void SetPackageId(uint8_t id) {
141 package_id_ = id;
142 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800143
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700144 SymbolTable* GetExternalSymbols() override {
145 return &symbols_;
146 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800147
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 bool IsVerbose() override {
149 return verbose_;
150 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800151
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700152 void SetVerbose(bool val) {
153 verbose_ = val;
Brandon Liu48d229d2023-05-04 23:54:03 +0000154 diagnostics_->SetVerbose(val);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700155 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800156
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700157 int GetMinSdkVersion() override {
158 return min_sdk_version_;
159 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700160
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700161 void SetMinSdkVersion(int minSdk) {
162 min_sdk_version_ = minSdk;
163 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700164
Udam Sainib228df32019-06-18 16:50:34 -0700165 const std::set<std::string>& GetSplitNameDependencies() override {
166 return split_name_dependencies_;
167 }
168
169 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
170 split_name_dependencies_ = split_name_dependencies;
171 }
172
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700173 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700174 DISALLOW_COPY_AND_ASSIGN(LinkContext);
175
Adam Lesinskib522f042017-04-21 16:57:59 -0700176 PackageType package_type_ = PackageType::kApp;
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000177 android::IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700178 NameMangler name_mangler_;
179 std::string compilation_package_;
180 uint8_t package_id_ = 0x0;
181 SymbolTable symbols_;
182 bool verbose_ = false;
183 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700184 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700185};
186
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700187// A custom delegate that generates compatible pre-O IDs for use with feature splits.
188// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
189// is interpreted as a negative number. Some verification was wrongly assuming negative values
190// were invalid.
191//
192// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
193// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
194// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800195//
196// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700197class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
198 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800199 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700200 }
201
202 virtual ~FeatureSplitSymbolTableDelegate() = default;
203
204 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
205 const ResourceName& name,
206 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
207 std::unique_ptr<SymbolTable::Symbol> symbol =
208 DefaultSymbolTableDelegate::FindByName(name, sources);
209 if (symbol == nullptr) {
210 return {};
211 }
212
213 // Check to see if this is an 'id' with the target package.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000214 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700215 ResourceId* id = &symbol->id.value();
216 if (id->package_id() > kAppPackageId) {
217 // Rewrite the resource ID to be compatible pre-O.
218 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
219
220 // Check that this doesn't overlap another resource.
221 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
222 // The ID overlaps, so log a message (since this is a weird failure) and fail.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000223 context_->GetDiagnostics()->Error(android::DiagMessage()
224 << "Failed to rewrite " << name
225 << " for pre-O feature split support");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700226 return {};
227 }
228
229 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000230 context_->GetDiagnostics()->Note(android::DiagMessage()
231 << "rewriting " << name << " (" << *id << ") -> ("
232 << rewritten_id << ")");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700233 }
234
235 *id = rewritten_id;
236 }
237 }
238 return symbol;
239 }
240
241 private:
242 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
243
244 IAaptContext* context_;
245};
246
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700247static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path,
248 bool keep_raw_values, bool utf16, OutputFormat format,
249 IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800250 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700251 if (context->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000252 context->GetDiagnostics()->Note(android::DiagMessage(path)
253 << "writing to archive (keep_raw_values="
254 << (keep_raw_values ? "true" : "false") << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700255 }
256
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700257 switch (format) {
258 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000259 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700260 XmlFlattenerOptions options = {};
261 options.keep_raw_values = keep_raw_values;
262 options.use_utf16 = utf16;
263 XmlFlattener flattener(&buffer, options);
264 if (!flattener.Consume(context, &xml_res)) {
265 return false;
266 }
267
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000268 android::BigBufferInputStream input_stream(&buffer);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700269 return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
270 writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700271 } break;
272
273 case OutputFormat::kProto: {
274 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800275 // Strip whitespace text nodes from tha AndroidManifest.xml
276 SerializeXmlOptions options;
277 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700278 SerializeXmlResourceToPb(xml_res, &pb_node);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700279 return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700280 } break;
281 }
282 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800283}
284
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700285// Inflates an XML file from the source path.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000286static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
287 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800288 TRACE_CALL();
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000289 android::FileInputStream fin(path);
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700290 if (fin.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000291 diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700292 return {};
293 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000294 return xml::Inflate(&fin, diag, android::Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800295}
296
Adam Lesinski355f2852016-02-13 20:26:45 -0800297struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700298 bool no_auto_version = false;
299 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900300 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700301 bool no_xml_namespaces = false;
302 bool keep_raw_values = false;
303 bool do_not_compress_anything = false;
304 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100305 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700306 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700307 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700308 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800309};
310
Adam Lesinskic744ae82017-05-17 19:28:38 -0700311// A sampling of public framework resource IDs.
312struct R {
313 struct attr {
314 enum : uint32_t {
315 paddingLeft = 0x010100d6u,
316 paddingRight = 0x010100d8u,
317 paddingHorizontal = 0x0101053du,
318
319 paddingTop = 0x010100d7u,
320 paddingBottom = 0x010100d9u,
321 paddingVertical = 0x0101053eu,
322
323 layout_marginLeft = 0x010100f7u,
324 layout_marginRight = 0x010100f9u,
325 layout_marginHorizontal = 0x0101053bu,
326
327 layout_marginTop = 0x010100f8u,
328 layout_marginBottom = 0x010100fau,
329 layout_marginVertical = 0x0101053cu,
330 };
331 };
332};
333
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700334template <typename T>
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700335uint32_t GetCompressionFlags(StringPiece str, T options) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700336 if (options.do_not_compress_anything) {
337 return 0;
338 }
339
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700340 if (options.regex_to_not_compress &&
341 std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700342 return 0;
343 }
344
345 for (const std::string& extension : options.extensions_to_not_compress) {
346 if (util::EndsWith(str, extension)) {
347 return 0;
348 }
349 }
350 return ArchiveEntry::kCompress;
351}
352
Adam Lesinski355f2852016-02-13 20:26:45 -0800353class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700355 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700356 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800357
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700358 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800359
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 private:
361 struct FileOperation {
362 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700365 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700368 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700369
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700370 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700372
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700373 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700374 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700375 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800376
Adam Lesinskic744ae82017-05-17 19:28:38 -0700377 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
378 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800379
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700380 ResourceFileFlattenerOptions options_;
381 IAaptContext* context_;
382 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700383 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800384};
385
Adam Lesinskic744ae82017-05-17 19:28:38 -0700386ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
387 IAaptContext* context, proguard::KeepSet* keep_set)
388 : options_(options), context_(context), keep_set_(keep_set) {
389 SymbolTable* symm = context_->GetExternalSymbols();
390
391 // Build up the rules for degrading newer attributes to older ones.
392 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
393 // generated from the attribute definitions themselves (b/62028956).
Yi Kongd6507882023-12-05 17:06:08 +0900394 if (symm->FindById(R::attr::paddingHorizontal)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700395 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800396 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
397 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700398 };
399 rules_[R::attr::paddingHorizontal] =
400 util::make_unique<DegradeToManyRule>(std::move(replacements));
401 }
402
Yi Kongd6507882023-12-05 17:06:08 +0900403 if (symm->FindById(R::attr::paddingVertical)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700404 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800405 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
406 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700407 };
408 rules_[R::attr::paddingVertical] =
409 util::make_unique<DegradeToManyRule>(std::move(replacements));
410 }
411
Yi Kongd6507882023-12-05 17:06:08 +0900412 if (symm->FindById(R::attr::layout_marginHorizontal)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700413 std::vector<ReplacementAttr> replacements{
414 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800415 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700416 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800417 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700418 };
419 rules_[R::attr::layout_marginHorizontal] =
420 util::make_unique<DegradeToManyRule>(std::move(replacements));
421 }
422
Yi Kongd6507882023-12-05 17:06:08 +0900423 if (symm->FindById(R::attr::layout_marginVertical)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700424 std::vector<ReplacementAttr> replacements{
425 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800426 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700427 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800428 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700429 };
430 rules_[R::attr::layout_marginVertical] =
431 util::make_unique<DegradeToManyRule>(std::move(replacements));
432 }
433}
434
Adam Lesinskibb94f322017-07-12 07:41:55 -0700435static bool IsTransitionElement(const std::string& name) {
436 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
437 name == "changeImageTransform" || name == "changeTransform" ||
438 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
439 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
440 name == "transitionManager";
441}
442
443static bool IsVectorElement(const std::string& name) {
444 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800445 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
446 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700447}
448
Adam Lesinskic744ae82017-05-17 19:28:38 -0700449template <typename T>
450std::vector<T> make_singleton_vec(T&& val) {
451 std::vector<T> vec;
452 vec.emplace_back(std::forward<T>(val));
453 return vec;
454}
455
456std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
457 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800458 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700459 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000460 const android::Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700461
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700462 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000463 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700464 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700465 }
466
Adam Lesinski00451162017-10-03 07:44:08 -0700467 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
468 // that existing projects have out-of-date references which pass compilation.
469 xml::StripAndroidStudioAttributes(doc->root.get());
470
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700471 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100472 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700473 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 }
475
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700476 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700477 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700478 }
479
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700480 if (options_.no_xml_namespaces) {
481 XmlNamespaceRemover namespace_remover;
482 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800484 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700485 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800486
Adam Lesinskibb94f322017-07-12 07:41:55 -0700487 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700488 return make_singleton_vec(std::move(file_op->xml_to_flatten));
489 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700490
Adam Lesinskibb94f322017-07-12 07:41:55 -0700491 if (options_.no_version_vectors || options_.no_version_transitions) {
492 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700493 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 if (el && el->namespace_uri.empty()) {
495 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
496 (options_.no_version_transitions && IsTransitionElement(el->name))) {
497 return make_singleton_vec(std::move(file_op->xml_to_flatten));
498 }
499 }
500 }
501
Adam Lesinskic744ae82017-05-17 19:28:38 -0700502 const ConfigDescription& config = file_op->config;
503 ResourceEntry* entry = file_op->entry;
504
505 XmlCompatVersioner xml_compat_versioner(&rules_);
506 const util::Range<ApiVersion> api_range{config.sdkVersion,
507 FindNextApiVersionForConfig(entry, config)};
508 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800509}
510
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800511ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
512 switch (format) {
513 case OutputFormat::kApk:
514 return ResourceFile::Type::kBinaryXml;
515 case OutputFormat::kProto:
516 return ResourceFile::Type::kProtoXml;
517 }
518 LOG_ALWAYS_FATAL("unreachable");
519 return ResourceFile::Type::kUnknown;
520}
521
Ryan Mitchell70f79722018-08-13 07:37:24 -0700522static auto kDrawableVersions = std::map<std::string, ApiVersion>{
523 { "adaptive-icon" , SDK_O },
524};
525
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700526bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800527 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700528 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700529 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800530
Adam Koskidc21dea2017-07-21 10:55:27 -0700531 proguard::CollectResourceReferences(context_, table, keep_set_);
532
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700534 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
535
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700536 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700537 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700538 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700539 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800540
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 // Populate the queue with all files in the ResourceTable.
542 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700543 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700544 // WARNING! Do not insert or remove any resources while executing in this scope. It will
545 // corrupt the iteration order.
546
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700547 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700549 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700550 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700551
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700552 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700553 if (!file) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000554 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700556 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 }
558
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 FileOperation file_op;
560 file_op.entry = entry.get();
561 file_op.dst_path = *file_ref->path;
562 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700563 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000565 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700566 (file_ref->type == ResourceFile::Type::kBinaryXml ||
567 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700568 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 if (!data) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000570 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571 << "failed to open file");
572 return false;
573 }
574
Adam Lesinski00451162017-10-03 07:44:08 -0700575 if (file_ref->type == ResourceFile::Type::kProtoXml) {
576 pb::XmlNode pb_xml_node;
577 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000578 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700579 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700580 return false;
581 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700582
Adam Lesinski00451162017-10-03 07:44:08 -0700583 std::string error;
584 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
585 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000586 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700587 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700588 return false;
589 }
590 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700591 std::string error_str;
592 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700593 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000594 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700595 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700596 return false;
597 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700598 }
599
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800600 // Update the type that this file will be written as.
601 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
602
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700603 file_op.xml_to_flatten->file.config = config_value->config;
604 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000605 file_op.xml_to_flatten->file.name =
606 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700607 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700608
609 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
610 // else we end up copying the string in the std::make_pair() method,
611 // then creating a StringPiece from the copy, which would cause us
612 // to end up referencing garbage in the map.
613 const StringPiece entry_name(entry->name);
614 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
615 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 }
617 }
618
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700620 for (auto& map_entry : config_sorted_files) {
621 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700622 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700624 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700625 // Check minimum sdk versions supported for drawables
626 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
627 if (drawable_entry != kDrawableVersions.end()) {
628 if (drawable_entry->second > context_->GetMinSdkVersion()
629 && drawable_entry->second > config.sdkVersion) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000630 context_->GetDiagnostics()->Error(
631 android::DiagMessage(file_op.xml_to_flatten->file.source)
632 << "<" << drawable_entry->first << "> elements "
633 << "require a sdk version of at least " << (int16_t)drawable_entry->second);
Ryan Mitchell70f79722018-08-13 07:37:24 -0700634 error = true;
635 continue;
636 }
637 }
638
Adam Lesinskic744ae82017-05-17 19:28:38 -0700639 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
640 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700641 if (versioned_docs.empty()) {
642 error = true;
643 continue;
644 }
645
Adam Lesinskic744ae82017-05-17 19:28:38 -0700646 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
647 std::string dst_path = file_op.dst_path;
648 if (doc->file.config != file_op.config) {
649 // Only add the new versioned configurations.
650 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000651 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
Adam Lesinskic744ae82017-05-17 19:28:38 -0700652 << "auto-versioning resource from config '"
653 << config << "' -> '" << doc->file.config << "'");
654 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700655
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800656 const ResourceFile& file = doc->file;
657 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
658
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700659 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800660 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
661 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700662
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800663 // Update the output format of this XML file.
664 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700665 bool result = table->AddResource(NewResourceBuilder(file.name)
666 .SetValue(std::move(file_ref), file.config)
667 .SetAllowMangled(true)
668 .Build(),
669 context_->GetDiagnostics());
670 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700671 return false;
672 }
673 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700674
675 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
676 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 }
678 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700679 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700680 GetCompressionFlags(file_op.dst_path, options_),
681 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700682 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700684 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700685 }
686 return !error;
687}
688
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000689static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700690 const std::unordered_map<ResourceName, ResourceId>& id_map,
691 const std::string& id_map_path) {
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +0000692 android::FileOutputStream fout(id_map_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800693 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000694 diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700695 return false;
696 }
697
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800698 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 const ResourceName& name = entry.first;
701 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800702 printer.Print(name.to_string());
703 printer.Print(" = ");
704 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800706 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800708 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000709 diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 return false;
711 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700712 return true;
713}
714
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000715static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700716 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700718 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000719 diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 return false;
721 }
722
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 out_id_map->clear();
724 size_t line_no = 0;
725 for (StringPiece line : util::Tokenize(content, '\n')) {
726 line_no++;
727 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700728 if (line.empty()) {
729 continue;
730 }
731
732 auto iter = std::find(line.begin(), line.end(), '=');
733 if (iter == line.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000734 diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 return false;
736 }
737
738 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 StringPiece res_name_str =
740 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
741 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000742 diag->Error(android::DiagMessage(android::Source(path, line_no))
743 << "invalid resource name '" << res_name_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700744 return false;
745 }
746
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700747 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
748 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700749 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700750
Ryan Mitchell4382e442021-07-14 12:53:01 -0700751 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700752 if (!maybe_id) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000753 diag->Error(android::DiagMessage(android::Source(path, line_no))
754 << "invalid resource ID '" << res_id_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700755 return false;
756 }
757
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700758 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700759 }
760 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700761}
762
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700763class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700764 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700765 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700766 : options_(options),
767 context_(context),
768 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700769 file_collection_(util::make_unique<io::FileCollection>()) {
770 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700771
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800772 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800773 using namespace android;
774
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000775 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
776 // we're looking for the first attribute resource in the system package.
777 android::ApkAssetsCookie cookie;
778 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
779 cookie = value->cookie;
780 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800781 // No Framework assets loaded. Not a failure.
782 return;
783 }
784
785 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800786 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800787 if (manifest == nullptr) {
788 // No errors.
789 return;
790 }
791
792 std::string error;
793 std::unique_ptr<xml::XmlResource> manifest_xml =
794 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
795 if (manifest_xml == nullptr) {
796 // No errors.
797 return;
798 }
799
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700800 if (!options_.manifest_fixer_options.compile_sdk_version) {
801 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
802 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700803 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700804 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
805 switch (prim->value.dataType) {
806 case Res_value::TYPE_INT_DEC:
807 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
808 break;
809 case Res_value::TYPE_INT_HEX:
810 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
811 break;
812 default:
813 break;
814 }
815 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
816 compile_sdk_version = *str->value;
817 } else {
818 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800819 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800820 }
821 }
822
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700823 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
824 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
825 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700826 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700827 options_.manifest_fixer_options.compile_sdk_version_codename;
828 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
829 compile_sdk_version_codename = *str->value;
830 } else {
831 compile_sdk_version_codename = attr->value;
832 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800833 }
834 }
835 }
836
Adam Lesinski8780eb62017-10-31 17:44:39 -0700837 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800838 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700839 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800840 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700841 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700842 for (const std::string& path : options_.include_paths) {
843 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000844 context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700845 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700846
Adam Lesinski8780eb62017-10-31 17:44:39 -0700847 std::string error;
848 auto zip_collection = io::ZipFileCollection::Create(path, &error);
849 if (zip_collection == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000850 context_->GetDiagnostics()->Error(android::DiagMessage()
851 << "failed to open APK: " << error);
Adam Lesinski8780eb62017-10-31 17:44:39 -0700852 return false;
853 }
854
855 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
856 // Load this as a static library include.
857 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000858 android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
Adam Lesinski8780eb62017-10-31 17:44:39 -0700859 if (static_apk == nullptr) {
860 return false;
861 }
862
Adam Lesinskib522f042017-04-21 16:57:59 -0700863 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800864 // Can't include static libraries when not building a static library (they have no IDs
865 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700866 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000867 android::DiagMessage(path)
868 << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700869 return false;
870 }
871
Adam Lesinski8780eb62017-10-31 17:44:39 -0700872 ResourceTable* table = static_apk->GetResourceTable();
873
874 // 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 -0700875 // our compilation package so the symbol package name does not get mangled into the entry
876 // name.
877 if (options_.no_static_lib_packages && !table->packages.empty()) {
878 auto lib_package_result = GetStaticLibraryPackage(table);
879 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000880 context_->GetDiagnostics()->Error(android::DiagMessage(path)
881 << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800882 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700883 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700884 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700885 }
886
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700887 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700888 util::make_unique<ResourceTableSymbolSource>(table));
889 static_library_includes_.push_back(std::move(static_apk));
890 } else {
891 if (!asset_source->AddAssetPath(path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000892 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinski8780eb62017-10-31 17:44:39 -0700893 << "failed to load include path " << path);
894 return false;
895 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 }
897 }
898
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800899 // Capture the shared libraries so that the final resource table can be properly flattened
900 // with support for shared libraries.
901 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700902 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800903 // Capture the included base feature package.
904 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800905 } else if (entry.first == kFrameworkPackageId) {
906 // Try to embed which version of the framework we're compiling against.
907 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
908 // when linking our synthesized 'android:compileSdkVersion' attribute.
909 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
910 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
911 if (symbol != nullptr && symbol->is_public) {
912 // The symbol is present and public, extract the android:versionName and
913 // android:versionCode from the framework AndroidManifest.xml.
914 ExtractCompileSdkVersions(asset_source->GetAssetManager());
915 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700916 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700917 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800918 }
919 }
920
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700921 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700922 return true;
923 }
924
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000925 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
926 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800927 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800929 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
930 if (manifest_el == nullptr) {
931 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800933
934 AppInfo app_info;
935
936 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000937 diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800938 return {};
939 }
940
941 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
942 if (!package_attr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000943 diag->Error(android::DiagMessage(xml_res->file.source)
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800944 << "<manifest> must have a 'package' attribute");
945 return {};
946 }
947 app_info.package = package_attr->value;
948
949 if (xml::Attribute* version_code_attr =
950 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700951 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800952 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000953 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800954 << "invalid android:versionCode '" << version_code_attr->value << "'");
955 return {};
956 }
957 app_info.version_code = maybe_code.value();
958 }
959
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700960 if (xml::Attribute* version_code_major_attr =
961 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700962 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700963 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000964 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
965 << "invalid android:versionCodeMajor '" << version_code_major_attr->value
966 << "'");
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700967 return {};
968 }
969 app_info.version_code_major = maybe_code.value();
970 }
971
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800972 if (xml::Attribute* revision_code_attr =
973 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700974 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800975 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000976 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800977 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
978 return {};
979 }
980 app_info.revision_code = maybe_code.value();
981 }
982
983 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
984 if (!split_name_attr->value.empty()) {
985 app_info.split_name = split_name_attr->value;
986 }
987 }
988
989 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
990 if (xml::Attribute* min_sdk =
991 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700992 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800993 }
994 }
Udam Sainib228df32019-06-18 16:50:34 -0700995
996 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
997 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
998 if (const xml::Attribute* split_name =
999 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1000 if (!split_name->value.empty()) {
1001 app_info.split_name_dependencies.insert(split_name->value);
1002 }
1003 }
1004 }
1005 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -08001006 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001007 }
1008
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001009 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1010 // Postcondition: ResourceTable has only one package left. All others are
1011 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001012 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001013 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001014 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001015 };
1016
1017 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001018 for (const auto& package : final_table_.packages) {
1019 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020 // We have a package that is not related to the one we're building!
1021 for (const auto& type : package->types) {
1022 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001023 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001024
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001025 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001026 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001027 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001028 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001029 context_->GetDiagnostics()->Warn(
1030 android::DiagMessage(config_value->value->GetSource())
1031 << "generated id '" << res_name << "' for external package '" << package->name
1032 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001034 context_->GetDiagnostics()->Error(
1035 android::DiagMessage(config_value->value->GetSource())
1036 << "defined resource '" << res_name << "' for external package '"
1037 << package->name << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001038 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001040 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001041 }
1042 }
1043 }
1044 }
1045
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001046 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1047 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001048 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001049 return !error;
1050 }
1051
1052 /**
1053 * Returns true if no IDs have been set, false otherwise.
1054 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001055 bool VerifyNoIdsSet() {
1056 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001057 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001058 for (const auto& entry : type->entries) {
1059 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001060 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001061 context_->GetDiagnostics()->Error(android::DiagMessage()
1062 << "resource " << res_name << " has ID "
1063 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001064 return false;
1065 }
1066 }
1067 }
1068 }
1069 return true;
1070 }
1071
Josh Houec67cb42022-06-09 19:19:21 +08001072 bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
1073 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1074 // element.
1075 const xml::Element* application = manifest->root->FindChild("", "application");
1076 if (!application) {
1077 return true;
1078 }
1079 const xml::Attribute* localeConfig =
1080 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1081 if (!localeConfig) {
1082 return true;
1083 }
1084
1085 // Deserialize XML from the compiled file
1086 if (localeConfig->compiled_value) {
1087 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1088 const auto localeconfig_entry =
1089 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1090 if (!localeconfig_entry) {
Iurii Makhnoa7ba6b62022-11-11 17:59:57 +00001091 // If locale config is resolved from external symbols - skip validation.
1092 if (context_->GetExternalSymbols()->FindByReference(*localeconfig_reference)) {
1093 return true;
1094 }
Josh Houec67cb42022-06-09 19:19:21 +08001095 context_->GetDiagnostics()->Error(
1096 android::DiagMessage(localeConfig->compiled_value->GetSource())
1097 << "no localeConfig entry");
1098 return false;
1099 }
1100 for (const auto& value : localeconfig_entry->values) {
1101 const FileReference* file_ref = ValueCast<FileReference>(value->value.get());
1102 if (!file_ref) {
1103 context_->GetDiagnostics()->Error(
1104 android::DiagMessage(localeConfig->compiled_value->GetSource())
1105 << "no file reference");
1106 return false;
1107 }
1108 io::IFile* file = file_ref->file;
1109 if (!file) {
1110 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
1111 << "file not found");
1112 return false;
1113 }
1114 std::unique_ptr<io::IData> data = file->OpenAsData();
1115 if (!data) {
1116 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1117 << "failed to open file");
1118 return false;
1119 }
1120 pb::XmlNode pb_xml_node;
1121 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
1122 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1123 << "failed to parse proto XML");
1124 return false;
1125 }
1126
1127 std::string error;
1128 std::unique_ptr<xml::XmlResource> localeConfig_xml =
1129 DeserializeXmlResourceFromPb(pb_xml_node, &error);
1130 if (!localeConfig_xml) {
1131 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1132 << "failed to deserialize proto XML: " << error);
1133 return false;
1134 }
1135 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1136 if (!localeConfig_el) {
1137 diag->Error(android::DiagMessage(file->GetSource()) << "no root tag defined");
1138 return false;
1139 }
1140 if (localeConfig_el->name != "locale-config") {
1141 diag->Error(android::DiagMessage(file->GetSource())
1142 << "invalid element name: " << localeConfig_el->name
1143 << ", expected: locale-config");
1144 return false;
1145 }
1146 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1147 if (child_el->name == "locale") {
1148 if (const xml::Attribute* locale_name_attr =
1149 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1150 const std::string& locale_name = locale_name_attr->value;
1151 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1152 // Start to verify the locale format
1153 ConfigDescription config;
1154 if (!ConfigDescription::Parse(valid_name, &config)) {
1155 diag->Error(android::DiagMessage(file->GetSource())
1156 << "invalid configuration: " << locale_name);
1157 return false;
1158 }
1159 } else {
1160 diag->Error(android::DiagMessage(file->GetSource())
1161 << "the attribute android:name is not found");
1162 return false;
1163 }
1164 } else {
1165 diag->Error(android::DiagMessage(file->GetSource())
1166 << "invalid element name: " << child_el->name << ", expected: locale");
1167 return false;
1168 }
1169 }
1170 }
1171 }
1172 return true;
1173 }
1174
1175 std::string ConvertToBCP47Tag(const std::string& locale) {
1176 std::string bcp47tag = "b+";
1177 bcp47tag += locale;
1178 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1179 return bcp47tag;
1180 }
1181
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001182 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001183 if (options_.output_to_directory) {
1184 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001185 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001186 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001187 }
1188 }
1189
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001190 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001191 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001192 switch (format) {
1193 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001194 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001195 TableFlattener flattener(options_.table_flattener_options, &buffer);
1196 if (!flattener.Consume(context_, table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001197 context_->GetDiagnostics()->Error(android::DiagMessage()
1198 << "failed to flatten resource table");
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001199 return false;
1200 }
1201
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001202 android::BigBufferInputStream input_stream(&buffer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001203 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1204 ArchiveEntry::kAlign, writer);
1205 } break;
1206
1207 case OutputFormat::kProto: {
1208 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001209 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1210 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001211 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1212 ArchiveEntry::kCompress, writer);
1213 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001215 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216 }
1217
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001218 bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate,
1219 StringPiece out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001220 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001221 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222 return true;
1223 }
1224
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001225 std::string out_path;
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001226 std::unique_ptr<android::FileOutputStream> fout;
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001227 if (options_.generate_java_class_path) {
1228 out_path = options_.generate_java_class_path.value();
1229 file::AppendPath(&out_path, file::PackageToPath(out_package));
1230 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001231 context_->GetDiagnostics()->Error(android::DiagMessage()
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001232 << "failed to create directory '" << out_path << "'");
1233 return false;
1234 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001236 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001238 fout = util::make_unique<android::FileOutputStream>(out_path);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001239 if (fout->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001240 context_->GetDiagnostics()->Error(android::DiagMessage()
1241 << "failed writing to '" << out_path
1242 << "': " << fout->GetError());
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001243 return false;
1244 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001245 }
1246
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001247 std::unique_ptr<android::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001248 if (out_text_symbols_path) {
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001249 fout_text = util::make_unique<android::FileOutputStream>(out_text_symbols_path.value());
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001250 if (fout_text->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001251 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001252 << "failed writing to '" << out_text_symbols_path.value()
1253 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001254 return false;
1255 }
1256 }
1257
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001259 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001260 context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 return false;
1262 }
1263
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 return true;
1265 }
1266
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001267 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001268 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001269 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1270 std::vector<std::string> packages_to_callback;
1271
1272 JavaClassGeneratorOptions template_options;
1273 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1274 template_options.javadoc_annotations = options_.javadoc_annotations;
1275
1276 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1277 template_options.use_final = false;
1278 }
1279
1280 if (context_->GetPackageType() == PackageType::kSharedLib) {
1281 template_options.use_final = false;
1282 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1283 }
1284
1285 const StringPiece actual_package = context_->GetCompilationPackage();
1286 StringPiece output_package = context_->GetCompilationPackage();
1287 if (options_.custom_java_package) {
1288 // Override the output java package to the custom one.
1289 output_package = options_.custom_java_package.value();
1290 }
1291
1292 // Generate the private symbols if required.
1293 if (options_.private_symbols) {
1294 packages_to_callback.push_back(options_.private_symbols.value());
1295
1296 // If we defined a private symbols package, we only emit Public symbols
1297 // to the original package, and private and public symbols to the private package.
1298 JavaClassGeneratorOptions options = template_options;
1299 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1300 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1301 options)) {
1302 return false;
1303 }
1304 }
1305
1306 // Generate copies of the original package R class but with different package names.
1307 // This is to support non-namespaced builds.
1308 for (const std::string& extra_package : options_.extra_java_packages) {
1309 packages_to_callback.push_back(extra_package);
1310
1311 JavaClassGeneratorOptions options = template_options;
1312 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1313 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1314 return false;
1315 }
1316 }
1317
1318 // Generate R classes for each package that was merged (static library).
1319 // Use the actual package's resources only.
1320 for (const std::string& package : table_merger_->merged_packages()) {
1321 packages_to_callback.push_back(package);
1322
1323 JavaClassGeneratorOptions options = template_options;
1324 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1325 if (!WriteJavaFile(&final_table_, package, package, options)) {
1326 return false;
1327 }
1328 }
1329
1330 // Generate the main public R class.
1331 JavaClassGeneratorOptions options = template_options;
1332
1333 // Only generate public symbols if we have a private package.
1334 if (options_.private_symbols) {
1335 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1336 }
1337
1338 if (options.rewrite_callback_options) {
1339 options.rewrite_callback_options.value().packages_to_callback =
1340 std::move(packages_to_callback);
1341 }
1342
1343 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1344 options_.generate_text_symbols_path)) {
1345 return false;
1346 }
1347
1348 return true;
1349 }
1350
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001351 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001352 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001353 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001354 return true;
1355 }
1356
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001357 std::unique_ptr<ClassDefinition> manifest_class =
1358 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001360 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001361 // Something bad happened, but we already logged it, so exit.
1362 return false;
1363 }
1364
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001365 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001366 // Empty Manifest class, no need to generate it.
1367 return true;
1368 }
1369
1370 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001371 for (const std::string& annotation : options_.javadoc_annotations) {
1372 std::string proper_annotation = "@";
1373 proper_annotation += annotation;
1374 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 }
1376
Adam Lesinski0d81f702017-06-27 15:51:09 -07001377 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001378 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001379
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001380 std::string out_path = options_.generate_java_class_path.value();
1381 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001383 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001384 context_->GetDiagnostics()->Error(android::DiagMessage()
1385 << "failed to create directory '" << out_path << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001386 return false;
1387 }
1388
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001390
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001391 android::FileOutputStream fout(out_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001392 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001393 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1394 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001395 return false;
1396 }
1397
Makoto Onukide6e6f22020-06-22 10:17:02 -07001398 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1399 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001400 fout.Flush();
1401
1402 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001403 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1404 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001405 return false;
1406 }
1407 return true;
1408 }
1409
Ryan Mitchell4382e442021-07-14 12:53:01 -07001410 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001411 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001412 if (!out) {
1413 return true;
1414 }
1415
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001416 const std::string& out_path = out.value();
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001417 android::FileOutputStream fout(out_path);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001418 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001419 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1420 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001421 return false;
1422 }
1423
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001424 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1425 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001426 fout.Flush();
1427
1428 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001429 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1430 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001431 return false;
1432 }
1433 return true;
1434 }
1435
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001436 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001437 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001438 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001439 context_->GetDiagnostics()->Note(android::DiagMessage()
1440 << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001441 }
1442
Adam Lesinski8780eb62017-10-31 17:44:39 -07001443 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1444 if (apk == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001445 context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001446 return false;
1447 }
1448
Adam Lesinski8780eb62017-10-31 17:44:39 -07001449 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001450 if (table->packages.empty()) {
1451 return true;
1452 }
1453
1454 auto lib_package_result = GetStaticLibraryPackage(table);
1455 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001456 context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001457 return false;
1458 }
1459
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001460 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001461 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001462 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001463 // Merge all resources as if they were in the compilation package. This is the old behavior
1464 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001466 // Add the package to the set of --extra-packages so we emit an R.java for each library
1467 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001469 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001470 }
1471
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001472 // Clear the package name, so as to make the resources look like they are coming from the
1473 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001474 pkg->name = "";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001475 result = table_merger_->Merge(android::Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476
1477 } else {
1478 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001479 // preserved and resource names are mangled.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001480 result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001481 }
1482
1483 if (!result) {
1484 return false;
1485 }
1486
1487 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001488 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001489 return true;
1490 }
1491
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001492 bool MergeExportedSymbols(const android::Source& source,
Adam Lesinski2427dce2017-11-30 15:10:28 -08001493 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001494 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001496 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001497 ResourceName res_name = exported_symbol.name;
1498 if (res_name.package.empty()) {
1499 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500 }
1501
Ryan Mitchell4382e442021-07-14 12:53:01 -07001502 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001503 if (mangled_name) {
1504 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001505 }
1506
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001507 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001508 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001509 bool result = final_table_.AddResource(
1510 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1511 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001512 if (!result) {
1513 return false;
1514 }
1515 }
1516 return true;
1517 }
1518
Adam Lesinski2427dce2017-11-30 15:10:28 -08001519 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001520 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001521 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001522 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski2427dce2017-11-30 15:10:28 -08001523 << "merging '" << compiled_file.name
1524 << "' from compiled file " << compiled_file.source);
1525 }
1526
1527 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1528 return false;
1529 }
1530 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1531 }
1532
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001533 // 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 -07001534 // If override is true, conflicting resources are allowed to override each other, in order of last
1535 // seen.
1536 // An io::IFileCollection is created from the ZIP file and added to the set of
1537 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001539 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001541 context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001542 }
1543
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001544 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001545 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001546 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001547 if (!collection) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001548 context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001549 return false;
1550 }
1551
1552 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001553 for (auto iter = collection->Iterator(); iter->HasNext();) {
1554 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001555 error = true;
1556 }
1557 }
1558
1559 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001560 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001561 return !error;
1562 }
1563
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001564 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001565 // conflicting resources are allowed to override each other, in order of last seen.
1566 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1567 // as ZIP archive and the files within are merged individually.
1568 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001569 bool MergePath(const std::string& path, bool override) {
1570 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1571 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1572 return MergeArchive(path, override);
1573 } else if (util::EndsWith(path, ".apk")) {
1574 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001575 }
1576
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001577 io::IFile* file = file_collection_->InsertFile(path);
1578 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001579 }
1580
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001581 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001582 // If override is true, conflicting resources are allowed to override each other, in order of last
1583 // seen.
1584 // All other file types are ignored. This is because these files could be coming from a zip,
1585 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001586 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001587 TRACE_CALL();
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001588 const android::Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001589
Adam Lesinski00451162017-10-03 07:44:08 -07001590 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001591 // Since AAPT compiles these file types and appends .flat to them, seeing
1592 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001593 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001594 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1595 << "uncompiled " << file_type
1596 << " file passed as argument. Must be "
1597 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001598 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001599 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1600 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001601 context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
Adam Lesinski00451162017-10-03 07:44:08 -07001602 return true;
1603 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604 }
1605
Jeremy Meyerb4f83ff2023-11-30 19:29:50 +00001606 std::unique_ptr<android::InputStream> input_stream = file->OpenInputStream();
Adam Lesinski00451162017-10-03 07:44:08 -07001607 if (input_stream == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001608 context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
Adam Lesinski00451162017-10-03 07:44:08 -07001609 return false;
1610 }
1611
1612 if (input_stream->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001613 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001614 << "failed to open file: " << input_stream->GetError());
1615 return false;
1616 }
1617
1618 ContainerReaderEntry* entry;
1619 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001620
1621 if (reader.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001622 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Mohamed Heikal10844322018-02-07 15:17:38 -05001623 << "failed to read file: " << reader.GetError());
1624 return false;
1625 }
1626
Adam Lesinski00451162017-10-03 07:44:08 -07001627 while ((entry = reader.Next()) != nullptr) {
1628 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001629 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001630 pb::ResourceTable pb_table;
1631 if (!entry->GetResTable(&pb_table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001632 context_->GetDiagnostics()->Error(
1633 android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001634 return false;
1635 }
1636
1637 ResourceTable table;
1638 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001639 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001640 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001641 << "failed to deserialize resource table: " << error);
1642 return false;
1643 }
1644
1645 if (!table_merger_->Merge(src, &table, override)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001646 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1647 << "failed to merge resource table");
Adam Lesinski00451162017-10-03 07:44:08 -07001648 return false;
1649 }
1650 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001651 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001652 pb::internal::CompiledFile pb_compiled_file;
1653 off64_t offset;
1654 size_t len;
1655 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001656 context_->GetDiagnostics()->Error(
1657 android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001658 return false;
1659 }
1660
1661 ResourceFile resource_file;
1662 std::string error;
1663 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001664 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001665 << "failed to read compiled header: " << error);
1666 return false;
1667 }
1668
1669 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1670 return false;
1671 }
1672 }
1673 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 return true;
1675 }
1676
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001677 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1678 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1679 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001680 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001681 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1682 if (!files) {
1683 return false;
1684 }
1685
1686 for (const std::string& file : files.value()) {
1687 std::string full_key = "assets/" + file;
1688 std::string full_path = assets_dir;
1689 file::AppendPath(&full_path, file);
1690
1691 auto iter = merged_assets.find(full_key);
1692 if (iter == merged_assets.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001693 merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1694 android::Source(std::move(full_path))));
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001695 } else if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001696 context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001697 << "asset file overrides '" << full_path << "'");
1698 }
1699 }
1700 }
1701
1702 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001703 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001704 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1705 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001706 return false;
1707 }
1708 }
1709 return true;
1710 }
1711
Rhed Jao2c434422020-11-12 10:48:03 +08001712 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1713 Reference* reference) {
1714 if (!reference || !reference->name) {
1715 return nullptr;
1716 }
1717 auto name_ref = ResourceNameRef(reference->name.value());
1718 if (name_ref.package.empty()) {
1719 name_ref.package = context->GetCompilationPackage();
1720 }
1721 const auto search_result = table->FindResource(name_ref);
1722 if (!search_result) {
1723 return nullptr;
1724 }
1725 return search_result.value().entry;
1726 }
1727
Ryan Mitchelldba64562019-06-07 17:07:37 -07001728 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001729 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001730 if (!application) {
1731 return;
1732 }
1733
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001734 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1735 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001736 if (!icon || !round_icon) {
1737 return;
1738 }
1739
1740 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001741 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001742 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1743 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001744 return;
1745 }
1746
1747 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001748 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001749 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1750 ? config_value->config.sdkVersion : icon_max_sdk;
1751 }
1752 if (icon_max_sdk < SDK_O) {
1753 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1754 return;
1755 }
1756
1757 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001758 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001759 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1760 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001761 return;
1762 }
1763
1764 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001765 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001766 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1767 ? config_value->config.sdkVersion : round_icon_max_sdk;
1768 }
1769 if (round_icon_max_sdk >= SDK_O) {
1770 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1771 // not generate an alias to the icon drawable.
1772 return;
1773 }
1774
1775 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001776 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001777 if (config_value->config.sdkVersion < SDK_O) {
1778 continue;
1779 }
1780
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001781 context_->GetDiagnostics()->Note(android::DiagMessage()
1782 << "generating " << round_icon_reference->name.value()
1783 << " with config \"" << config_value->config
1784 << "\" for round icon compatibility");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001785
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001786 CloningValueTransformer cloner(&table->string_pool);
1787 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001788 auto round_config_value =
1789 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001790 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001791 }
1792 }
1793
Rhed Jao2c434422020-11-12 10:48:03 +08001794 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1795 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1796 if (manifest_el == nullptr) {
1797 return true;
1798 }
1799 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1800 return true;
1801 }
1802 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1803 if (!attr) {
1804 return true;
1805 }
1806 const auto validate = [&](const std::string& shared_user_id) -> bool {
1807 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1808 return true;
1809 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001810 android::DiagMessage error_msg(manifest_el->line_number);
Rhed Jao2c434422020-11-12 10:48:03 +08001811 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1812 << shared_user_id << "'";
1813 if (options_.manifest_fixer_options.warn_validation) {
1814 // Treat the error only as a warning.
1815 context_->GetDiagnostics()->Warn(error_msg);
1816 return true;
1817 }
1818 context_->GetDiagnostics()->Error(error_msg);
1819 return false;
1820 };
1821 // If attr->compiled_value is not null, check if it is a ref
1822 if (attr->compiled_value) {
1823 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1824 if (ref == nullptr) {
1825 return true;
1826 }
1827 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1828 if (!shared_user_id_entry) {
1829 return true;
1830 }
1831 for (const auto& value : shared_user_id_entry->values) {
1832 const auto str_value = ValueCast<String>(value->value.get());
1833 if (str_value != nullptr && !validate(*str_value->value)) {
1834 return false;
1835 }
1836 }
1837 return true;
1838 }
1839
1840 // Fallback to checking the raw value
1841 return validate(attr->value);
1842 }
1843
Jeremy Meyer16c83af2024-07-26 16:21:49 -07001844 class FlagDisabledStringVisitor : public DescendingValueVisitor {
1845 public:
1846 using DescendingValueVisitor::Visit;
1847
1848 explicit FlagDisabledStringVisitor(android::StringPool& string_pool)
1849 : string_pool_(string_pool) {
1850 }
1851
1852 void Visit(RawString* value) override {
1853 value->value = string_pool_.MakeRef("");
1854 }
1855
1856 void Visit(String* value) override {
1857 value->value = string_pool_.MakeRef("");
1858 }
1859
1860 void Visit(StyledString* value) override {
1861 value->value = string_pool_.MakeRef(android::StyleString{{""}, {}});
1862 }
1863
1864 private:
1865 DISALLOW_COPY_AND_ASSIGN(FlagDisabledStringVisitor);
1866 android::StringPool& string_pool_;
1867 };
1868
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001869 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1870 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1872 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001873 TRACE_CALL();
Jeremy Meyer16c83af2024-07-26 16:21:49 -07001874
1875 FlagDisabledStringVisitor visitor(table->string_pool);
1876
1877 for (auto& package : table->packages) {
1878 for (auto& type : package->types) {
1879 for (auto& entry : type->entries) {
1880 for (auto& config_value : entry->values) {
1881 if (config_value->flag_status == FlagStatus::Disabled) {
1882 config_value->value->Accept(&visitor);
1883 }
1884 }
1885 }
1886 }
1887 }
1888
Jeremy Meyer423c0f52024-08-02 12:06:54 -07001889 if (!FlagDisabledResourceRemover{}.Consume(context_, table)) {
1890 context_->GetDiagnostics()->Error(android::DiagMessage()
1891 << "failed removing resources behind disabled flags");
1892 return 1;
1893 }
1894
Ryan Mitchell479fa392019-01-02 17:15:39 -08001895 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1896 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001897 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001898 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001899 if (!result) {
1900 return false;
1901 }
1902
Ryan Mitchelldba64562019-06-07 17:07:37 -07001903 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1904 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1905 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1906 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1907 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1908 // See (b/34829129)
1909 AliasAdaptiveIcon(manifest, table);
1910
Rhed Jao2c434422020-11-12 10:48:03 +08001911 // Verify the shared user id here to handle the case of reference value.
1912 if (!VerifySharedUserId(manifest, table)) {
1913 return false;
1914 }
1915
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001916 ResourceFileFlattenerOptions file_flattener_options;
1917 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001918 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1919 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001920 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 file_flattener_options.no_auto_version = options_.no_auto_version;
1922 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001923 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001924 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1925 file_flattener_options.update_proguard_spec =
1926 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001927 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001928 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001929
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001930 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 if (!file_flattener.Flatten(table, writer)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001932 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 return false;
1934 }
1935
Adam Lesinski490595a2017-11-07 17:08:07 -08001936 // Hack to fix b/68820737.
1937 // We need to modify the ResourceTable's package name, but that should NOT affect
1938 // anything else being generated, which includes the Java classes.
1939 // If required, the package name is modifed before flattening, and then modified back
1940 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001941 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001942 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1943 // or higher] as invalid. In order to work around this limitation, we allow the use
1944 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1945 // definition of what a valid "split" package ID is to account for this.
1946 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1947 context_->GetPackageId() != kAppPackageId &&
1948 context_->GetPackageId() != kFrameworkPackageId)
1949 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001950 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001951 // The base APK is included, and this is a feature split. If the base package is
1952 // the same as this package, then we are building an old style Android Instant Apps feature
1953 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001954 if (!table->packages.empty() &&
1955 table->packages.back()->name == context_->GetCompilationPackage()) {
1956 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001957 std::string new_package_name =
1958 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001959 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001960
1961 if (context_->IsVerbose()) {
1962 context_->GetDiagnostics()->Note(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001963 android::DiagMessage() << "rewriting resource package name for feature split to '"
1964 << new_package_name << "'");
Adam Lesinski490595a2017-11-07 17:08:07 -08001965 }
1966 package_to_rewrite->name = new_package_name;
1967 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001968 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001969
1970 bool success = FlattenTable(table, options_.output_format, writer);
1971
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001972 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001973 // Change the name back.
1974 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001975
1976 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1977 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1978 // library, do not include a mapping from the feature package name to the feature package id
1979 // in the feature's dynamic reference table.
1980 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001981 }
1982
1983 if (!success) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001984 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
Adam Lesinski490595a2017-11-07 17:08:07 -08001985 }
1986 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001987 }
1988
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001990 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001991 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 std::unique_ptr<xml::XmlResource> manifest_xml =
1993 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1994 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001995 return 1;
1996 }
1997
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001998 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001999 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002000 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 const AppInfo& app_info = maybe_app_info.value();
2002 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002003 }
2004
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07002005 // Determine the package name under which to merge resources.
2006 if (options_.rename_resources_package) {
2007 if (!options_.custom_java_package) {
2008 // Generate the R.java under the original package name instead of the package name specified
2009 // through --rename-resources-package.
2010 options_.custom_java_package = context_->GetCompilationPackage();
2011 }
2012 context_->SetCompilationPackage(options_.rename_resources_package.value());
2013 }
2014
Adam Lesinskic6284372017-12-04 13:46:23 -08002015 // Now that the compilation package is set, load the dependencies. This will also extract
2016 // the Android framework's versionCode and versionName, if they exist.
2017 if (!LoadSymbolsFromIncludePaths()) {
2018 return 1;
2019 }
2020
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
2022 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002023 return 1;
2024 }
2025
Ryan Mitchell4382e442021-07-14 12:53:01 -07002026 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002027 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 return 1;
2030 }
2031
Adam Lesinski490595a2017-11-07 17:08:07 -08002032 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07002033 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002035 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07002036 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002037
Mark Punzalan12dc2b82024-01-24 22:58:41 -08002038 std::unique_ptr<xml::XmlResource> pre_flags_filter_manifest_xml = manifest_xml->Clone();
2039
Mark Punzalan4b564de2024-01-05 02:17:20 -08002040 FeatureFlagsFilterOptions flags_filter_options;
2041 if (context_->GetMinSdkVersion() > SDK_UPSIDE_DOWN_CAKE) {
2042 // For API version > U, PackageManager will dynamically read the flag values and disable
2043 // manifest elements accordingly when parsing the manifest.
2044 // For API version <= U, we remove disabled elements from the manifest with the filter.
2045 flags_filter_options.remove_disabled_elements = false;
2046 flags_filter_options.flags_must_have_value = false;
2047 }
2048 FeatureFlagsFilter flags_filter(options_.feature_flag_values, flags_filter_options);
2049 if (!flags_filter.Consume(context_, manifest_xml.get())) {
2050 return 1;
2051 }
2052
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002053 // Override the package ID when it is "android".
2054 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002055 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002056
2057 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07002058 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002059 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002060 android::DiagMessage() << "package 'android' can only be built as a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002061 return 1;
2062 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002063 }
2064
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002065 TableMergerOptions table_merger_options;
2066 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07002067 table_merger_options.override_styles_instead_of_overlaying =
2068 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01002069 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002070 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002071
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002072 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002073 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002074 << StringPrintf("linking package '%s' using package ID %02x",
2075 context_->GetCompilationPackage().data(),
2076 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 }
2078
Adam Lesinski2427dce2017-11-30 15:10:28 -08002079 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
2080 // in res/**/*.
2081 {
2082 XmlIdCollector collector;
2083 if (!collector.Consume(context_, manifest_xml.get())) {
2084 return false;
2085 }
2086
2087 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
2088 return false;
2089 }
2090 }
2091
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 for (const std::string& input : input_files) {
2093 if (!MergePath(input, false)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002094 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002095 return 1;
2096 }
2097 }
2098
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 for (const std::string& input : options_.overlay_files) {
2100 if (!MergePath(input, true)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002101 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 return 1;
2103 }
2104 }
2105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 return 1;
2108 }
2109
Adam Lesinskib522f042017-04-21 16:57:59 -07002110 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002112 if (context_->GetPackageId() == kAndroidPackageId &&
2113 !mover.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002114 context_->GetDiagnostics()->Error(android::DiagMessage()
2115 << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002116 return 1;
2117 }
2118
2119 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 IdAssigner id_assigner(&options_.stable_id_map);
2121 if (!id_assigner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002122 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 return 1;
2124 }
2125
2126 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 if (options_.resource_id_map_path) {
2128 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002129 for (auto& type : package->types) {
2130 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002131 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002132 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002133 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002134 }
2135 }
2136 }
2137
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002138 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002139 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 return 1;
2141 }
2142 }
2143 } else {
2144 // Static libs are merged with other apps, and ID collisions are bad, so
2145 // verify that
2146 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002147 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002148 return 1;
2149 }
2150 }
2151
2152 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002153 context_->SetNameManglerPolicy(
2154 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155
2156 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002157 context_->GetExternalSymbols()->PrependSource(
2158 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002159
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002160 // Workaround for pre-O runtime that would treat negative resource IDs
2161 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2162 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2163 // are just identifiers.
2164 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2165 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002166 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002167 << "enabling pre-O feature split ID rewriting");
2168 }
2169 context_->GetExternalSymbols()->SetDelegate(
2170 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2171 }
2172
Adam Lesinski34a16872018-02-23 16:18:10 -08002173 // Before we process anything, remove the resources whose default values don't exist.
2174 // We want to force any references to these to fail the build.
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002175 if (!options_.no_resource_removal) {
2176 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002177 context_->GetDiagnostics()->Error(android::DiagMessage()
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002178 << "failed removing resources with no defaults");
2179 return 1;
2180 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002181 }
2182
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002183 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002184 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002185 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186 return 1;
2187 }
2188
Adam Lesinskib522f042017-04-21 16:57:59 -07002189 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002190 if (!options_.products.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002191 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002192 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002193 }
2194 } else {
Inseob Kim5fe521e2023-09-15 16:38:50 +09002195 ProductFilter product_filter(options_.products, /* remove_default_config_values = */ false);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002196 if (!product_filter.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002197 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002198 return 1;
2199 }
2200 }
2201
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002202 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002203 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002204 if (!versioner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002205 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002206 return 1;
2207 }
2208 }
2209
Adam Lesinskib522f042017-04-21 16:57:59 -07002210 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002211 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002212 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002213 << "collapsing resource versions for minimum SDK "
2214 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002215 }
2216
2217 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002218 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002219 return 1;
2220 }
2221 }
2222
Winson3c918b82019-01-25 14:25:37 -08002223 if (!options_.exclude_configs_.empty()) {
2224 std::vector<ConfigDescription> excluded_configs;
2225
2226 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002227 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002228 ConfigDescription config_description;
2229
2230 if (!ConfigDescription::Parse(config_string, &config_description)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002231 context_->GetDiagnostics()->Error(
2232 android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
Winson3c918b82019-01-25 14:25:37 -08002233 return 1;
2234 }
2235
2236 excluded_configs.push_back(config_description);
2237 }
2238
2239 ResourceExcluder excluder(excluded_configs);
2240 if (!excluder.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002241 context_->GetDiagnostics()->Error(android::DiagMessage()
2242 << "failed excluding configurations");
Winson3c918b82019-01-25 14:25:37 -08002243 return 1;
2244 }
2245 }
2246
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002247 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002248 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002249 if (!deduper.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002250 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002251 return 1;
2252 }
2253 }
2254
Adam Koskidc21dea2017-07-21 10:55:27 -07002255 proguard::KeepSet proguard_keep_set =
2256 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002257 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002258
Adam Lesinskib522f042017-04-21 16:57:59 -07002259 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002260 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002261 !options_.table_splitter_options.preferred_densities.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002262 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002263 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002264 }
2265 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002266 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2267 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002268 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002269 options_.split_constraints =
2270 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002272 if (origConstraintSize != options_.split_constraints.size()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002273 context_->GetDiagnostics()->Warn(android::DiagMessage()
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002274 << "requested to split resources prior to min sdk of "
2275 << context_->GetMinSdkVersion());
2276 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002277 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002278 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002279 return 1;
2280 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002281 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002282
2283 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002284 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002285 auto split_constraints_iter = options_.split_constraints.begin();
2286 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002287 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002288 context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002289 << "generating split with configurations '"
2290 << util::Joiner(split_constraints_iter->configs, ", ")
2291 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002292 }
2293
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002294 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002295 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002296 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002297 return 1;
2298 }
2299
2300 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002301 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002302 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002303
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002304 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002305 if (!linker.Consume(context_, split_manifest.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002306 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002307 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002308 return 1;
2309 }
2310
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002311 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2312 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002313 return 1;
2314 }
2315
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002316 ++path_iter;
2317 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002318 }
2319 }
2320
2321 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002322 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002323 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002324 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002325 return 1;
2326 }
2327
2328 bool error = false;
2329 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002330 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002331 // (aka, which package the AndroidManifest.xml is coming from).
2332 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002333 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002334
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002335 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002336 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002337 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002338 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002339 error = true;
2340 }
2341
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002342 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002343 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002344 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002345 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002346 }
2347
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002348 if (options_.generate_java_class_path) {
Mark Punzalan12dc2b82024-01-24 22:58:41 -08002349 // The FeatureFlagsFilter may remove <permission> and <permission-group> elements that
2350 // generate constants in the Manifest Java file. While we want those permissions and
2351 // permission groups removed in the SDK (i.e., if a feature flag is disabled), the
2352 // constants should still remain so that code referencing it (e.g., within a feature
2353 // flag check) will still compile. Therefore we use the manifest XML before the filter.
2354 if (!WriteManifestJavaFile(pre_flags_filter_manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002355 error = true;
2356 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002357 }
2358
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002359 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002360 // PackageParser will fail if URIs are removed from
2361 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002362 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2363 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002364 error = true;
2365 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002366 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002367 } else {
2368 error = true;
2369 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002370 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002371
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002372 if (error) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002373 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002374 return 1;
2375 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002376
Josh Houec67cb42022-06-09 19:19:21 +08002377 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2378 return 1;
2379 };
2380
Jeremy Meyer423c0f52024-08-02 12:06:54 -07002381 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
2382 if (!GenerateJavaClasses()) {
2383 return 1;
2384 }
2385 }
2386
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002387 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2388 return 1;
2389 }
2390
2391 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002392 return 1;
2393 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002394
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002395 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002396 return 1;
2397 }
2398
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002399 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2400 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002401 return 1;
2402 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002403 return 0;
2404 }
2405
2406 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002407 LinkOptions options_;
2408 LinkContext* context_;
2409 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002410
Adam Lesinski490595a2017-11-07 17:08:07 -08002411 AppInfo app_info_;
2412
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002413 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002414
2415 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002416 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002417
Adam Lesinski8780eb62017-10-31 17:44:39 -07002418 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002419 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002420 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002421
Adam Lesinski8780eb62017-10-31 17:44:39 -07002422 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2423 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2424
2425 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2426 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002427
2428 // The set of shared libraries being used, mapping their assigned package ID to package name.
2429 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002430
2431 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002432 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002433};
2434
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002435int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002436 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002437 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002438
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002439 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002440 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002441 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002442 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002443 const std::string path = arg.substr(1, arg.size() - 1);
2444 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002445 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002446 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002447 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002448 }
2449 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002450 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002451 }
2452 }
2453
2454 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002455 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002456 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002457 const std::string path = arg.substr(1, arg.size() - 1);
2458 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002459 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002460 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002461 return 1;
2462 }
2463 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002464 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002465 }
2466 }
2467
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002468 if (verbose_) {
2469 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002470 }
2471
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002472 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002473 context.GetDiagnostics()
2474 ->Error(android::DiagMessage()
2475 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002476 return 1;
2477 }
2478
Ryan Mitchell5855de72021-02-24 14:39:13 -08002479 if (shared_lib_ && options_.private_symbols) {
2480 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2481 // reference the private attribute within the styleable array will cause a link error because
2482 // the private attribute will not be emitted in the public R.java.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002483 context.GetDiagnostics()->Error(android::DiagMessage()
Ryan Mitchell5855de72021-02-24 14:39:13 -08002484 << "--shared-lib cannot currently be used in combination with"
2485 << " --private-symbols");
2486 return 1;
2487 }
2488
Izabela Orlowska84febea2019-06-03 18:34:12 +01002489 if (options_.merge_only && !static_lib_) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002490 context.GetDiagnostics()
2491 ->Error(android::DiagMessage()
2492 << "the --merge-only flag can be only used when building a static library");
Izabela Orlowska84febea2019-06-03 18:34:12 +01002493 return 1;
2494 }
Iurii Makhnoda06e4d2022-08-24 14:17:32 +00002495 if (options_.use_sparse_encoding) {
2496 options_.table_flattener_options.sparse_entries = SparseEntriesMode::Enabled;
2497 }
Izabela Orlowska84febea2019-06-03 18:34:12 +01002498
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002499 // The default build type.
2500 context.SetPackageType(PackageType::kApp);
2501 context.SetPackageId(kAppPackageId);
2502
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002503 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002504 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002505 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002506 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002507 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002508 options_.output_format = OutputFormat::kProto;
2509 } else if (proto_format_) {
2510 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002511 }
2512
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002513 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002514 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002515 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002516 android::DiagMessage() << "can't specify --package-id when not building a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002517 return 1;
2518 }
2519
Ryan Mitchell4382e442021-07-14 12:53:01 -07002520 const std::optional<uint32_t> maybe_package_id_int =
2521 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002522 if (!maybe_package_id_int) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002523 context.GetDiagnostics()->Error(android::DiagMessage()
2524 << "package ID '" << package_id_.value()
2525 << "' is not a valid integer");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002526 return 1;
2527 }
2528
2529 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002530 if (package_id_int > std::numeric_limits<uint8_t>::max()
2531 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002532 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002533 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002534 android::DiagMessage() << StringPrintf(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002535 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2536 return 1;
2537 }
2538 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2539 }
2540
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002541 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002542 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002543 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002544 for (StringPiece package : util::Split(extra_package, ':')) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002545 options_.extra_java_packages.emplace(package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002546 }
2547 }
2548
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002549 if (product_list_) {
2550 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002551 if (product != "" && product != "default") {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002552 options_.products.emplace(product);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002553 }
2554 }
2555 }
2556
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002557 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002558 if (!configs_.empty()) {
2559 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002560 if (filter == nullptr) {
2561 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002562 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002563 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002564 }
2565
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002566 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002567 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002568 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002569 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002570 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002571 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002572 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002573 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002574
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002575 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002576 for (const std::string& split_arg : split_args_) {
2577 options_.split_paths.push_back({});
2578 options_.split_constraints.push_back({});
2579 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2580 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002581 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002582 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002583 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002584
Mark Punzalan5579cad2023-10-30 13:47:51 -07002585 // Parse the feature flag values. An argument that starts with '@' points to a file to read flag
2586 // values from.
2587 std::vector<std::string> all_feature_flags_args;
2588 for (const std::string& arg : feature_flags_args_) {
2589 if (util::StartsWith(arg, "@")) {
2590 const std::string path = arg.substr(1, arg.size() - 1);
2591 std::string error;
2592 if (!file::AppendArgsFromFile(path, &all_feature_flags_args, &error)) {
2593 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
2594 return 1;
2595 }
2596 } else {
2597 all_feature_flags_args.push_back(arg);
2598 }
2599 }
2600
2601 for (const std::string& arg : all_feature_flags_args) {
Mark Punzalan4b564de2024-01-05 02:17:20 -08002602 if (!ParseFeatureFlagsParameter(arg, context.GetDiagnostics(), &options_.feature_flag_values)) {
Mark Punzalan5579cad2023-10-30 13:47:51 -07002603 return 1;
2604 }
2605 }
2606
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002607 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2608 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2609 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002610 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002611 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002612 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002613
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002614 if (no_compress_regex) {
2615 std::string regex = no_compress_regex.value();
2616 if (util::StartsWith(regex, "@")) {
2617 const std::string path = regex.substr(1, regex.size() -1);
2618 std::string error;
2619 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002620 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002621 return 1;
2622 }
2623 } else {
2624 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2625 }
2626 }
2627
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002628 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002629 options_.extensions_to_not_compress.insert({
2630 // Image extensions
2631 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2632 // Audio extensions
2633 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2634 ".xmf", ".amr", ".awb",
2635 // Audio/video extensions
2636 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2637 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002638
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002639 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002640 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002641 options_.no_auto_version = true;
2642 options_.no_version_vectors = true;
2643 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002644 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002645
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002646 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002647 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002648}
2649
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002650} // namespace aapt