blob: 159c6fd9ef5879784df23457372b281b17b4e801 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
20
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050021#include <algorithm>
Jeremy Meyer56f36e82022-05-20 20:35:42 +000022#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
Adam Lesinski1ab598f2015-08-14 14:26:04 -070027#include "AppInfo.h"
28#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070029#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080031#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070032#include "ResourceValues.h"
33#include "ValueVisitor.h"
Jeremy Meyer56f36e82022-05-20 20:35:42 +000034#include "android-base/errors.h"
35#include "android-base/expected.h"
36#include "android-base/file.h"
37#include "android-base/stringprintf.h"
38#include "androidfw/IDiagnostics.h"
39#include "androidfw/Locale.h"
40#include "androidfw/StringPiece.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070041#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070042#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080043#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080044#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070046#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070047#include "format/binary/TableFlattener.h"
48#include "format/binary/XmlFlattener.h"
49#include "format/proto/ProtoDeserialize.h"
50#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070051#include "io/BigBufferStream.h"
52#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070054#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080055#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070056#include "java/JavaClassGenerator.h"
57#include "java/ManifestClassGenerator.h"
58#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070060#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080061#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080062#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080063#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070065#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080066#include "optimize/ResourceDeduper.h"
67#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "process/IResourceTableConsumer.h"
Inseob Kim5fe521e2023-09-15 16:38:50 +090069#include "process/ProductFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070070#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080071#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080072#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080074#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070075
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070076using ::aapt::io::FileInputStream;
MÃ¥rten Kongstad24c9aa62018-06-20 08:46:41 +020077using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070078using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070079using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070080using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070081using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070082
Adam Lesinski1ab598f2015-08-14 14:26:04 -070083namespace aapt {
84
Ryan Mitchell9634efb2021-03-19 14:53:17 -070085namespace {
86
87expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
88 // Resource tables built by aapt2 always contain one package. This is a post condition of
89 // VerifyNoExternalPackages.
90 if (table->packages.size() != 1u) {
91 return unexpected("static library contains more than one package");
92 }
93 return table->packages.back().get();
94}
95
96} // namespace
97
Ryan Mitchell22dc5312020-06-01 12:17:07 -070098constexpr uint8_t kAndroidPackageId = 0x01;
99
Adam Lesinski64587af2016-02-18 18:33:06 -0800100class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700101 public:
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000102 explicit LinkContext(android::IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100103 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700104 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700105
Adam Lesinskib522f042017-04-21 16:57:59 -0700106 PackageType GetPackageType() override {
107 return package_type_;
108 }
109
110 void SetPackageType(PackageType type) {
111 package_type_ = type;
112 }
113
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000114 android::IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100115 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700116 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700117
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700118 NameMangler* GetNameMangler() override {
119 return &name_mangler_;
120 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700121
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700122 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
123 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700124 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800125
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700126 const std::string& GetCompilationPackage() override {
127 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700128 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700129
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700130 void SetCompilationPackage(StringPiece package_name) {
131 compilation_package_ = std::string(package_name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700132 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800133
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700134 uint8_t GetPackageId() override {
135 return package_id_;
136 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700137
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 void SetPackageId(uint8_t id) {
139 package_id_ = id;
140 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800141
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700142 SymbolTable* GetExternalSymbols() override {
143 return &symbols_;
144 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800145
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700146 bool IsVerbose() override {
147 return verbose_;
148 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800149
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 void SetVerbose(bool val) {
151 verbose_ = val;
Brandon Liu48d229d2023-05-04 23:54:03 +0000152 diagnostics_->SetVerbose(val);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700153 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800154
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700155 int GetMinSdkVersion() override {
156 return min_sdk_version_;
157 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700158
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700159 void SetMinSdkVersion(int minSdk) {
160 min_sdk_version_ = minSdk;
161 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700162
Udam Sainib228df32019-06-18 16:50:34 -0700163 const std::set<std::string>& GetSplitNameDependencies() override {
164 return split_name_dependencies_;
165 }
166
167 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
168 split_name_dependencies_ = split_name_dependencies;
169 }
170
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700171 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700172 DISALLOW_COPY_AND_ASSIGN(LinkContext);
173
Adam Lesinskib522f042017-04-21 16:57:59 -0700174 PackageType package_type_ = PackageType::kApp;
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000175 android::IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700176 NameMangler name_mangler_;
177 std::string compilation_package_;
178 uint8_t package_id_ = 0x0;
179 SymbolTable symbols_;
180 bool verbose_ = false;
181 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700182 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700183};
184
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700185// A custom delegate that generates compatible pre-O IDs for use with feature splits.
186// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
187// is interpreted as a negative number. Some verification was wrongly assuming negative values
188// were invalid.
189//
190// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
191// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
192// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800193//
194// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700195class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
196 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800197 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700198 }
199
200 virtual ~FeatureSplitSymbolTableDelegate() = default;
201
202 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
203 const ResourceName& name,
204 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
205 std::unique_ptr<SymbolTable::Symbol> symbol =
206 DefaultSymbolTableDelegate::FindByName(name, sources);
207 if (symbol == nullptr) {
208 return {};
209 }
210
211 // Check to see if this is an 'id' with the target package.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000212 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700213 ResourceId* id = &symbol->id.value();
214 if (id->package_id() > kAppPackageId) {
215 // Rewrite the resource ID to be compatible pre-O.
216 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
217
218 // Check that this doesn't overlap another resource.
219 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
220 // The ID overlaps, so log a message (since this is a weird failure) and fail.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000221 context_->GetDiagnostics()->Error(android::DiagMessage()
222 << "Failed to rewrite " << name
223 << " for pre-O feature split support");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700224 return {};
225 }
226
227 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000228 context_->GetDiagnostics()->Note(android::DiagMessage()
229 << "rewriting " << name << " (" << *id << ") -> ("
230 << rewritten_id << ")");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700231 }
232
233 *id = rewritten_id;
234 }
235 }
236 return symbol;
237 }
238
239 private:
240 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
241
242 IAaptContext* context_;
243};
244
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700245static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path,
246 bool keep_raw_values, bool utf16, OutputFormat format,
247 IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800248 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700249 if (context->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000250 context->GetDiagnostics()->Note(android::DiagMessage(path)
251 << "writing to archive (keep_raw_values="
252 << (keep_raw_values ? "true" : "false") << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700253 }
254
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700255 switch (format) {
256 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000257 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700258 XmlFlattenerOptions options = {};
259 options.keep_raw_values = keep_raw_values;
260 options.use_utf16 = utf16;
261 XmlFlattener flattener(&buffer, options);
262 if (!flattener.Consume(context, &xml_res)) {
263 return false;
264 }
265
266 io::BigBufferInputStream input_stream(&buffer);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700267 return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress,
268 writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700269 } break;
270
271 case OutputFormat::kProto: {
272 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800273 // Strip whitespace text nodes from tha AndroidManifest.xml
274 SerializeXmlOptions options;
275 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700276 SerializeXmlResourceToPb(xml_res, &pb_node);
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700277 return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700278 } break;
279 }
280 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800281}
282
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700283// Inflates an XML file from the source path.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000284static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
285 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800286 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700287 FileInputStream fin(path);
288 if (fin.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000289 diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700290 return {};
291 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000292 return xml::Inflate(&fin, diag, android::Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800293}
294
Adam Lesinski355f2852016-02-13 20:26:45 -0800295struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700296 bool no_auto_version = false;
297 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900298 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700299 bool no_xml_namespaces = false;
300 bool keep_raw_values = false;
301 bool do_not_compress_anything = false;
302 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100303 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700304 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700305 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700306 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800307};
308
Adam Lesinskic744ae82017-05-17 19:28:38 -0700309// A sampling of public framework resource IDs.
310struct R {
311 struct attr {
312 enum : uint32_t {
313 paddingLeft = 0x010100d6u,
314 paddingRight = 0x010100d8u,
315 paddingHorizontal = 0x0101053du,
316
317 paddingTop = 0x010100d7u,
318 paddingBottom = 0x010100d9u,
319 paddingVertical = 0x0101053eu,
320
321 layout_marginLeft = 0x010100f7u,
322 layout_marginRight = 0x010100f9u,
323 layout_marginHorizontal = 0x0101053bu,
324
325 layout_marginTop = 0x010100f8u,
326 layout_marginBottom = 0x010100fau,
327 layout_marginVertical = 0x0101053cu,
328 };
329 };
330};
331
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700332template <typename T>
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700333uint32_t GetCompressionFlags(StringPiece str, T options) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700334 if (options.do_not_compress_anything) {
335 return 0;
336 }
337
Yurii Zubrytskyia5775142022-11-02 17:49:49 -0700338 if (options.regex_to_not_compress &&
339 std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700340 return 0;
341 }
342
343 for (const std::string& extension : options.extensions_to_not_compress) {
344 if (util::EndsWith(str, extension)) {
345 return 0;
346 }
347 }
348 return ArchiveEntry::kCompress;
349}
350
Adam Lesinski355f2852016-02-13 20:26:45 -0800351class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700352 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700353 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700354 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800355
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700356 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 private:
359 struct FileOperation {
360 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700361
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700362 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700363 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700364
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700365 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700366 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700367
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700368 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700369 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700370
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700371 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700372 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700373 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800374
Adam Lesinskic744ae82017-05-17 19:28:38 -0700375 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
376 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800377
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700378 ResourceFileFlattenerOptions options_;
379 IAaptContext* context_;
380 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700381 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800382};
383
Adam Lesinskic744ae82017-05-17 19:28:38 -0700384ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
385 IAaptContext* context, proguard::KeepSet* keep_set)
386 : options_(options), context_(context), keep_set_(keep_set) {
387 SymbolTable* symm = context_->GetExternalSymbols();
388
389 // Build up the rules for degrading newer attributes to older ones.
390 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
391 // generated from the attribute definitions themselves (b/62028956).
392 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
393 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800394 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
395 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700396 };
397 rules_[R::attr::paddingHorizontal] =
398 util::make_unique<DegradeToManyRule>(std::move(replacements));
399 }
400
401 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
402 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800403 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
404 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700405 };
406 rules_[R::attr::paddingVertical] =
407 util::make_unique<DegradeToManyRule>(std::move(replacements));
408 }
409
410 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
411 std::vector<ReplacementAttr> replacements{
412 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800413 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700414 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800415 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700416 };
417 rules_[R::attr::layout_marginHorizontal] =
418 util::make_unique<DegradeToManyRule>(std::move(replacements));
419 }
420
421 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
422 std::vector<ReplacementAttr> replacements{
423 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800424 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800426 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700427 };
428 rules_[R::attr::layout_marginVertical] =
429 util::make_unique<DegradeToManyRule>(std::move(replacements));
430 }
431}
432
Adam Lesinskibb94f322017-07-12 07:41:55 -0700433static bool IsTransitionElement(const std::string& name) {
434 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
435 name == "changeImageTransform" || name == "changeTransform" ||
436 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
437 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
438 name == "transitionManager";
439}
440
441static bool IsVectorElement(const std::string& name) {
442 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800443 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
444 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700445}
446
Adam Lesinskic744ae82017-05-17 19:28:38 -0700447template <typename T>
448std::vector<T> make_singleton_vec(T&& val) {
449 std::vector<T> vec;
450 vec.emplace_back(std::forward<T>(val));
451 return vec;
452}
453
454std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
455 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800456 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700457 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000458 const android::Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700459
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700460 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000461 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700462 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700463 }
464
Adam Lesinski00451162017-10-03 07:44:08 -0700465 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
466 // that existing projects have out-of-date references which pass compilation.
467 xml::StripAndroidStudioAttributes(doc->root.get());
468
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700469 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100470 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700471 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700474 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700475 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700476 }
477
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700478 if (options_.no_xml_namespaces) {
479 XmlNamespaceRemover namespace_remover;
480 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700481 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800482 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700483 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800484
Adam Lesinskibb94f322017-07-12 07:41:55 -0700485 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700486 return make_singleton_vec(std::move(file_op->xml_to_flatten));
487 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700488
Adam Lesinskibb94f322017-07-12 07:41:55 -0700489 if (options_.no_version_vectors || options_.no_version_transitions) {
490 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700491 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700492 if (el && el->namespace_uri.empty()) {
493 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
494 (options_.no_version_transitions && IsTransitionElement(el->name))) {
495 return make_singleton_vec(std::move(file_op->xml_to_flatten));
496 }
497 }
498 }
499
Adam Lesinskic744ae82017-05-17 19:28:38 -0700500 const ConfigDescription& config = file_op->config;
501 ResourceEntry* entry = file_op->entry;
502
503 XmlCompatVersioner xml_compat_versioner(&rules_);
504 const util::Range<ApiVersion> api_range{config.sdkVersion,
505 FindNextApiVersionForConfig(entry, config)};
506 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800507}
508
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800509ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
510 switch (format) {
511 case OutputFormat::kApk:
512 return ResourceFile::Type::kBinaryXml;
513 case OutputFormat::kProto:
514 return ResourceFile::Type::kProtoXml;
515 }
516 LOG_ALWAYS_FATAL("unreachable");
517 return ResourceFile::Type::kUnknown;
518}
519
Ryan Mitchell70f79722018-08-13 07:37:24 -0700520static auto kDrawableVersions = std::map<std::string, ApiVersion>{
521 { "adaptive-icon" , SDK_O },
522};
523
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700524bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800525 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700526 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700527 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800528
Adam Koskidc21dea2017-07-21 10:55:27 -0700529 proguard::CollectResourceReferences(context_, table, keep_set_);
530
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700531 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700532 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
533
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700534 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700535 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700536 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700537 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800538
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700539 // Populate the queue with all files in the ResourceTable.
540 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700541 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700542 // WARNING! Do not insert or remove any resources while executing in this scope. It will
543 // corrupt the iteration order.
544
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700545 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700547 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700548 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700549
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 if (!file) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000552 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700553 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700554 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 }
556
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700557 FileOperation file_op;
558 file_op.entry = entry.get();
559 file_op.dst_path = *file_ref->path;
560 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700561 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000563 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700564 (file_ref->type == ResourceFile::Type::kBinaryXml ||
565 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700566 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 if (!data) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000568 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 << "failed to open file");
570 return false;
571 }
572
Adam Lesinski00451162017-10-03 07:44:08 -0700573 if (file_ref->type == ResourceFile::Type::kProtoXml) {
574 pb::XmlNode pb_xml_node;
575 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000576 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700577 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700578 return false;
579 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700580
Adam Lesinski00451162017-10-03 07:44:08 -0700581 std::string error;
582 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
583 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000584 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700585 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700586 return false;
587 }
588 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700589 std::string error_str;
590 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700591 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000592 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700593 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700594 return false;
595 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596 }
597
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800598 // Update the type that this file will be written as.
599 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
600
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700601 file_op.xml_to_flatten->file.config = config_value->config;
602 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000603 file_op.xml_to_flatten->file.name =
604 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700605 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700606
607 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
608 // else we end up copying the string in the std::make_pair() method,
609 // then creating a StringPiece from the copy, which would cause us
610 // to end up referencing garbage in the map.
611 const StringPiece entry_name(entry->name);
612 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
613 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700614 }
615 }
616
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700617 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700618 for (auto& map_entry : config_sorted_files) {
619 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700620 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700621
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700622 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700623 // Check minimum sdk versions supported for drawables
624 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
625 if (drawable_entry != kDrawableVersions.end()) {
626 if (drawable_entry->second > context_->GetMinSdkVersion()
627 && drawable_entry->second > config.sdkVersion) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000628 context_->GetDiagnostics()->Error(
629 android::DiagMessage(file_op.xml_to_flatten->file.source)
630 << "<" << drawable_entry->first << "> elements "
631 << "require a sdk version of at least " << (int16_t)drawable_entry->second);
Ryan Mitchell70f79722018-08-13 07:37:24 -0700632 error = true;
633 continue;
634 }
635 }
636
Adam Lesinskic744ae82017-05-17 19:28:38 -0700637 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
638 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700639 if (versioned_docs.empty()) {
640 error = true;
641 continue;
642 }
643
Adam Lesinskic744ae82017-05-17 19:28:38 -0700644 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
645 std::string dst_path = file_op.dst_path;
646 if (doc->file.config != file_op.config) {
647 // Only add the new versioned configurations.
648 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000649 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
Adam Lesinskic744ae82017-05-17 19:28:38 -0700650 << "auto-versioning resource from config '"
651 << config << "' -> '" << doc->file.config << "'");
652 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800654 const ResourceFile& file = doc->file;
655 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
656
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700657 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800658 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
659 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700660
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800661 // Update the output format of this XML file.
662 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700663 bool result = table->AddResource(NewResourceBuilder(file.name)
664 .SetValue(std::move(file_ref), file.config)
665 .SetAllowMangled(true)
666 .Build(),
667 context_->GetDiagnostics());
668 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700669 return false;
670 }
671 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700672
673 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
674 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 }
676 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700677 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700678 GetCompressionFlags(file_op.dst_path, options_),
679 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700680 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700682 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 }
684 return !error;
685}
686
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000687static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700688 const std::unordered_map<ResourceName, ResourceId>& id_map,
689 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800690 io::FileOutputStream fout(id_map_path);
691 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000692 diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 return false;
694 }
695
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800696 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 const ResourceName& name = entry.first;
699 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800700 printer.Print(name.to_string());
701 printer.Print(" = ");
702 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800704 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800706 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000707 diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700708 return false;
709 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 return true;
711}
712
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000713static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700714 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700716 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000717 diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700718 return false;
719 }
720
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 out_id_map->clear();
722 size_t line_no = 0;
723 for (StringPiece line : util::Tokenize(content, '\n')) {
724 line_no++;
725 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700726 if (line.empty()) {
727 continue;
728 }
729
730 auto iter = std::find(line.begin(), line.end(), '=');
731 if (iter == line.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000732 diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700733 return false;
734 }
735
736 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700737 StringPiece res_name_str =
738 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
739 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000740 diag->Error(android::DiagMessage(android::Source(path, line_no))
741 << "invalid resource name '" << res_name_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 return false;
743 }
744
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
746 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700747 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748
Ryan Mitchell4382e442021-07-14 12:53:01 -0700749 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700750 if (!maybe_id) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000751 diag->Error(android::DiagMessage(android::Source(path, line_no))
752 << "invalid resource ID '" << res_id_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700753 return false;
754 }
755
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700756 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 }
758 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700759}
760
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700761class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700762 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700763 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700764 : options_(options),
765 context_(context),
766 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700767 file_collection_(util::make_unique<io::FileCollection>()) {
768 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700769
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800770 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800771 using namespace android;
772
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000773 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
774 // we're looking for the first attribute resource in the system package.
775 android::ApkAssetsCookie cookie;
776 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
777 cookie = value->cookie;
778 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800779 // No Framework assets loaded. Not a failure.
780 return;
781 }
782
783 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800784 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800785 if (manifest == nullptr) {
786 // No errors.
787 return;
788 }
789
790 std::string error;
791 std::unique_ptr<xml::XmlResource> manifest_xml =
792 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
793 if (manifest_xml == nullptr) {
794 // No errors.
795 return;
796 }
797
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700798 if (!options_.manifest_fixer_options.compile_sdk_version) {
799 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
800 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700801 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700802 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
803 switch (prim->value.dataType) {
804 case Res_value::TYPE_INT_DEC:
805 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
806 break;
807 case Res_value::TYPE_INT_HEX:
808 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
809 break;
810 default:
811 break;
812 }
813 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
814 compile_sdk_version = *str->value;
815 } else {
816 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800817 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800818 }
819 }
820
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700821 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
822 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
823 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700824 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700825 options_.manifest_fixer_options.compile_sdk_version_codename;
826 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
827 compile_sdk_version_codename = *str->value;
828 } else {
829 compile_sdk_version_codename = attr->value;
830 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800831 }
832 }
833 }
834
Adam Lesinski8780eb62017-10-31 17:44:39 -0700835 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800836 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700837 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800838 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700839 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700840 for (const std::string& path : options_.include_paths) {
841 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000842 context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700843 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700844
Adam Lesinski8780eb62017-10-31 17:44:39 -0700845 std::string error;
846 auto zip_collection = io::ZipFileCollection::Create(path, &error);
847 if (zip_collection == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000848 context_->GetDiagnostics()->Error(android::DiagMessage()
849 << "failed to open APK: " << error);
Adam Lesinski8780eb62017-10-31 17:44:39 -0700850 return false;
851 }
852
853 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
854 // Load this as a static library include.
855 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000856 android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
Adam Lesinski8780eb62017-10-31 17:44:39 -0700857 if (static_apk == nullptr) {
858 return false;
859 }
860
Adam Lesinskib522f042017-04-21 16:57:59 -0700861 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800862 // Can't include static libraries when not building a static library (they have no IDs
863 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700864 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000865 android::DiagMessage(path)
866 << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700867 return false;
868 }
869
Adam Lesinski8780eb62017-10-31 17:44:39 -0700870 ResourceTable* table = static_apk->GetResourceTable();
871
872 // 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 -0700873 // our compilation package so the symbol package name does not get mangled into the entry
874 // name.
875 if (options_.no_static_lib_packages && !table->packages.empty()) {
876 auto lib_package_result = GetStaticLibraryPackage(table);
877 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000878 context_->GetDiagnostics()->Error(android::DiagMessage(path)
879 << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800880 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700881 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700882 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700883 }
884
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700885 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700886 util::make_unique<ResourceTableSymbolSource>(table));
887 static_library_includes_.push_back(std::move(static_apk));
888 } else {
889 if (!asset_source->AddAssetPath(path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000890 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinski8780eb62017-10-31 17:44:39 -0700891 << "failed to load include path " << path);
892 return false;
893 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700894 }
895 }
896
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800897 // Capture the shared libraries so that the final resource table can be properly flattened
898 // with support for shared libraries.
899 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700900 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800901 // Capture the included base feature package.
902 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800903 } else if (entry.first == kFrameworkPackageId) {
904 // Try to embed which version of the framework we're compiling against.
905 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
906 // when linking our synthesized 'android:compileSdkVersion' attribute.
907 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
908 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
909 if (symbol != nullptr && symbol->is_public) {
910 // The symbol is present and public, extract the android:versionName and
911 // android:versionCode from the framework AndroidManifest.xml.
912 ExtractCompileSdkVersions(asset_source->GetAssetManager());
913 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700914 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700915 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800916 }
917 }
918
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700919 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700920 return true;
921 }
922
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000923 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
924 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800925 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700926 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800927 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
928 if (manifest_el == nullptr) {
929 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700930 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800931
932 AppInfo app_info;
933
934 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000935 diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800936 return {};
937 }
938
939 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
940 if (!package_attr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000941 diag->Error(android::DiagMessage(xml_res->file.source)
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800942 << "<manifest> must have a 'package' attribute");
943 return {};
944 }
945 app_info.package = package_attr->value;
946
947 if (xml::Attribute* version_code_attr =
948 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700949 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800950 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000951 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800952 << "invalid android:versionCode '" << version_code_attr->value << "'");
953 return {};
954 }
955 app_info.version_code = maybe_code.value();
956 }
957
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700958 if (xml::Attribute* version_code_major_attr =
959 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700960 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700961 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000962 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
963 << "invalid android:versionCodeMajor '" << version_code_major_attr->value
964 << "'");
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700965 return {};
966 }
967 app_info.version_code_major = maybe_code.value();
968 }
969
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800970 if (xml::Attribute* revision_code_attr =
971 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700972 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800973 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000974 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800975 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
976 return {};
977 }
978 app_info.revision_code = maybe_code.value();
979 }
980
981 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
982 if (!split_name_attr->value.empty()) {
983 app_info.split_name = split_name_attr->value;
984 }
985 }
986
987 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
988 if (xml::Attribute* min_sdk =
989 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700990 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800991 }
992 }
Udam Sainib228df32019-06-18 16:50:34 -0700993
994 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
995 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
996 if (const xml::Attribute* split_name =
997 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
998 if (!split_name->value.empty()) {
999 app_info.split_name_dependencies.insert(split_name->value);
1000 }
1001 }
1002 }
1003 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -08001004 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001005 }
1006
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001007 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1008 // Postcondition: ResourceTable has only one package left. All others are
1009 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001010 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001011 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001012 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 };
1014
1015 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 for (const auto& package : final_table_.packages) {
1017 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001018 // We have a package that is not related to the one we're building!
1019 for (const auto& type : package->types) {
1020 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001021 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001023 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001024 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001025 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001026 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001027 context_->GetDiagnostics()->Warn(
1028 android::DiagMessage(config_value->value->GetSource())
1029 << "generated id '" << res_name << "' for external package '" << package->name
1030 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001031 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001032 context_->GetDiagnostics()->Error(
1033 android::DiagMessage(config_value->value->GetSource())
1034 << "defined resource '" << res_name << "' for external package '"
1035 << package->name << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001036 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001038 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 }
1040 }
1041 }
1042 }
1043
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001044 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1045 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001046 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 return !error;
1048 }
1049
1050 /**
1051 * Returns true if no IDs have been set, false otherwise.
1052 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001053 bool VerifyNoIdsSet() {
1054 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001056 for (const auto& entry : type->entries) {
1057 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001058 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001059 context_->GetDiagnostics()->Error(android::DiagMessage()
1060 << "resource " << res_name << " has ID "
1061 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001062 return false;
1063 }
1064 }
1065 }
1066 }
1067 return true;
1068 }
1069
Josh Houec67cb42022-06-09 19:19:21 +08001070 bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
1071 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1072 // element.
1073 const xml::Element* application = manifest->root->FindChild("", "application");
1074 if (!application) {
1075 return true;
1076 }
1077 const xml::Attribute* localeConfig =
1078 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1079 if (!localeConfig) {
1080 return true;
1081 }
1082
1083 // Deserialize XML from the compiled file
1084 if (localeConfig->compiled_value) {
1085 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1086 const auto localeconfig_entry =
1087 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1088 if (!localeconfig_entry) {
Iurii Makhnoa7ba6b62022-11-11 17:59:57 +00001089 // If locale config is resolved from external symbols - skip validation.
1090 if (context_->GetExternalSymbols()->FindByReference(*localeconfig_reference)) {
1091 return true;
1092 }
Josh Houec67cb42022-06-09 19:19:21 +08001093 context_->GetDiagnostics()->Error(
1094 android::DiagMessage(localeConfig->compiled_value->GetSource())
1095 << "no localeConfig entry");
1096 return false;
1097 }
1098 for (const auto& value : localeconfig_entry->values) {
1099 const FileReference* file_ref = ValueCast<FileReference>(value->value.get());
1100 if (!file_ref) {
1101 context_->GetDiagnostics()->Error(
1102 android::DiagMessage(localeConfig->compiled_value->GetSource())
1103 << "no file reference");
1104 return false;
1105 }
1106 io::IFile* file = file_ref->file;
1107 if (!file) {
1108 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
1109 << "file not found");
1110 return false;
1111 }
1112 std::unique_ptr<io::IData> data = file->OpenAsData();
1113 if (!data) {
1114 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1115 << "failed to open file");
1116 return false;
1117 }
1118 pb::XmlNode pb_xml_node;
1119 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
1120 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1121 << "failed to parse proto XML");
1122 return false;
1123 }
1124
1125 std::string error;
1126 std::unique_ptr<xml::XmlResource> localeConfig_xml =
1127 DeserializeXmlResourceFromPb(pb_xml_node, &error);
1128 if (!localeConfig_xml) {
1129 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
1130 << "failed to deserialize proto XML: " << error);
1131 return false;
1132 }
1133 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1134 if (!localeConfig_el) {
1135 diag->Error(android::DiagMessage(file->GetSource()) << "no root tag defined");
1136 return false;
1137 }
1138 if (localeConfig_el->name != "locale-config") {
1139 diag->Error(android::DiagMessage(file->GetSource())
1140 << "invalid element name: " << localeConfig_el->name
1141 << ", expected: locale-config");
1142 return false;
1143 }
1144 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1145 if (child_el->name == "locale") {
1146 if (const xml::Attribute* locale_name_attr =
1147 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1148 const std::string& locale_name = locale_name_attr->value;
1149 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1150 // Start to verify the locale format
1151 ConfigDescription config;
1152 if (!ConfigDescription::Parse(valid_name, &config)) {
1153 diag->Error(android::DiagMessage(file->GetSource())
1154 << "invalid configuration: " << locale_name);
1155 return false;
1156 }
1157 } else {
1158 diag->Error(android::DiagMessage(file->GetSource())
1159 << "the attribute android:name is not found");
1160 return false;
1161 }
1162 } else {
1163 diag->Error(android::DiagMessage(file->GetSource())
1164 << "invalid element name: " << child_el->name << ", expected: locale");
1165 return false;
1166 }
1167 }
1168 }
1169 }
1170 return true;
1171 }
1172
1173 std::string ConvertToBCP47Tag(const std::string& locale) {
1174 std::string bcp47tag = "b+";
1175 bcp47tag += locale;
1176 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1177 return bcp47tag;
1178 }
1179
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001180 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001181 if (options_.output_to_directory) {
1182 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001183 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001184 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001185 }
1186 }
1187
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001188 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001189 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001190 switch (format) {
1191 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001192 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001193 TableFlattener flattener(options_.table_flattener_options, &buffer);
1194 if (!flattener.Consume(context_, table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001195 context_->GetDiagnostics()->Error(android::DiagMessage()
1196 << "failed to flatten resource table");
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001197 return false;
1198 }
1199
1200 io::BigBufferInputStream input_stream(&buffer);
1201 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1202 ArchiveEntry::kAlign, writer);
1203 } break;
1204
1205 case OutputFormat::kProto: {
1206 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001207 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1208 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001209 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1210 ArchiveEntry::kCompress, writer);
1211 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001213 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 }
1215
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07001216 bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate,
1217 StringPiece out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001218 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001219 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001220 return true;
1221 }
1222
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001223 std::string out_path;
1224 std::unique_ptr<io::FileOutputStream> fout;
1225 if (options_.generate_java_class_path) {
1226 out_path = options_.generate_java_class_path.value();
1227 file::AppendPath(&out_path, file::PackageToPath(out_package));
1228 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001229 context_->GetDiagnostics()->Error(android::DiagMessage()
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001230 << "failed to create directory '" << out_path << "'");
1231 return false;
1232 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001234 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001236 fout = util::make_unique<io::FileOutputStream>(out_path);
1237 if (fout->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001238 context_->GetDiagnostics()->Error(android::DiagMessage()
1239 << "failed writing to '" << out_path
1240 << "': " << fout->GetError());
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001241 return false;
1242 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 }
1244
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001245 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001246 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001247 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1248 if (fout_text->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001249 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001250 << "failed writing to '" << out_text_symbols_path.value()
1251 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001252 return false;
1253 }
1254 }
1255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001257 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001258 context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 return false;
1260 }
1261
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 return true;
1263 }
1264
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001265 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001266 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001267 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1268 std::vector<std::string> packages_to_callback;
1269
1270 JavaClassGeneratorOptions template_options;
1271 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1272 template_options.javadoc_annotations = options_.javadoc_annotations;
1273
1274 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1275 template_options.use_final = false;
1276 }
1277
1278 if (context_->GetPackageType() == PackageType::kSharedLib) {
1279 template_options.use_final = false;
1280 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1281 }
1282
1283 const StringPiece actual_package = context_->GetCompilationPackage();
1284 StringPiece output_package = context_->GetCompilationPackage();
1285 if (options_.custom_java_package) {
1286 // Override the output java package to the custom one.
1287 output_package = options_.custom_java_package.value();
1288 }
1289
1290 // Generate the private symbols if required.
1291 if (options_.private_symbols) {
1292 packages_to_callback.push_back(options_.private_symbols.value());
1293
1294 // If we defined a private symbols package, we only emit Public symbols
1295 // to the original package, and private and public symbols to the private package.
1296 JavaClassGeneratorOptions options = template_options;
1297 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1298 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1299 options)) {
1300 return false;
1301 }
1302 }
1303
1304 // Generate copies of the original package R class but with different package names.
1305 // This is to support non-namespaced builds.
1306 for (const std::string& extra_package : options_.extra_java_packages) {
1307 packages_to_callback.push_back(extra_package);
1308
1309 JavaClassGeneratorOptions options = template_options;
1310 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1311 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1312 return false;
1313 }
1314 }
1315
1316 // Generate R classes for each package that was merged (static library).
1317 // Use the actual package's resources only.
1318 for (const std::string& package : table_merger_->merged_packages()) {
1319 packages_to_callback.push_back(package);
1320
1321 JavaClassGeneratorOptions options = template_options;
1322 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1323 if (!WriteJavaFile(&final_table_, package, package, options)) {
1324 return false;
1325 }
1326 }
1327
1328 // Generate the main public R class.
1329 JavaClassGeneratorOptions options = template_options;
1330
1331 // Only generate public symbols if we have a private package.
1332 if (options_.private_symbols) {
1333 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1334 }
1335
1336 if (options.rewrite_callback_options) {
1337 options.rewrite_callback_options.value().packages_to_callback =
1338 std::move(packages_to_callback);
1339 }
1340
1341 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1342 options_.generate_text_symbols_path)) {
1343 return false;
1344 }
1345
1346 return true;
1347 }
1348
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001349 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001350 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001351 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001352 return true;
1353 }
1354
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001355 std::unique_ptr<ClassDefinition> manifest_class =
1356 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001357
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001358 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359 // Something bad happened, but we already logged it, so exit.
1360 return false;
1361 }
1362
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001363 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001364 // Empty Manifest class, no need to generate it.
1365 return true;
1366 }
1367
1368 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001369 for (const std::string& annotation : options_.javadoc_annotations) {
1370 std::string proper_annotation = "@";
1371 proper_annotation += annotation;
1372 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001373 }
1374
Adam Lesinski0d81f702017-06-27 15:51:09 -07001375 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001376 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001377
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001378 std::string out_path = options_.generate_java_class_path.value();
1379 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001380
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001381 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001382 context_->GetDiagnostics()->Error(android::DiagMessage()
1383 << "failed to create directory '" << out_path << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001384 return false;
1385 }
1386
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001387 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001388
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001389 io::FileOutputStream fout(out_path);
1390 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001391 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1392 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001393 return false;
1394 }
1395
Makoto Onukide6e6f22020-06-22 10:17:02 -07001396 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1397 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001398 fout.Flush();
1399
1400 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001401 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1402 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 return false;
1404 }
1405 return true;
1406 }
1407
Ryan Mitchell4382e442021-07-14 12:53:01 -07001408 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001409 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 if (!out) {
1411 return true;
1412 }
1413
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001415 io::FileOutputStream fout(out_path);
1416 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001417 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1418 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001419 return false;
1420 }
1421
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001422 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1423 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001424 fout.Flush();
1425
1426 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001427 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1428 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429 return false;
1430 }
1431 return true;
1432 }
1433
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001434 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001435 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001436 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001437 context_->GetDiagnostics()->Note(android::DiagMessage()
1438 << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001439 }
1440
Adam Lesinski8780eb62017-10-31 17:44:39 -07001441 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1442 if (apk == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001443 context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001444 return false;
1445 }
1446
Adam Lesinski8780eb62017-10-31 17:44:39 -07001447 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001448 if (table->packages.empty()) {
1449 return true;
1450 }
1451
1452 auto lib_package_result = GetStaticLibraryPackage(table);
1453 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001454 context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001455 return false;
1456 }
1457
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001458 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001459 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001460 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001461 // Merge all resources as if they were in the compilation package. This is the old behavior
1462 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001463
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001464 // Add the package to the set of --extra-packages so we emit an R.java for each library
1465 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001466 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001467 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468 }
1469
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001470 // Clear the package name, so as to make the resources look like they are coming from the
1471 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001472 pkg->name = "";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001473 result = table_merger_->Merge(android::Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001474
1475 } else {
1476 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001477 // preserved and resource names are mangled.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001478 result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001479 }
1480
1481 if (!result) {
1482 return false;
1483 }
1484
1485 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001486 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001487 return true;
1488 }
1489
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001490 bool MergeExportedSymbols(const android::Source& source,
Adam Lesinski2427dce2017-11-30 15:10:28 -08001491 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001492 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001493 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001494 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001495 ResourceName res_name = exported_symbol.name;
1496 if (res_name.package.empty()) {
1497 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001498 }
1499
Ryan Mitchell4382e442021-07-14 12:53:01 -07001500 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001501 if (mangled_name) {
1502 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001503 }
1504
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001505 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001506 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001507 bool result = final_table_.AddResource(
1508 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1509 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001510 if (!result) {
1511 return false;
1512 }
1513 }
1514 return true;
1515 }
1516
Adam Lesinski2427dce2017-11-30 15:10:28 -08001517 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001518 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001519 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001520 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski2427dce2017-11-30 15:10:28 -08001521 << "merging '" << compiled_file.name
1522 << "' from compiled file " << compiled_file.source);
1523 }
1524
1525 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1526 return false;
1527 }
1528 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1529 }
1530
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001531 // 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 -07001532 // If override is true, conflicting resources are allowed to override each other, in order of last
1533 // seen.
1534 // An io::IFileCollection is created from the ZIP file and added to the set of
1535 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001536 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001537 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001539 context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 }
1541
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001543 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001544 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001545 if (!collection) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001546 context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001547 return false;
1548 }
1549
1550 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001551 for (auto iter = collection->Iterator(); iter->HasNext();) {
1552 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001553 error = true;
1554 }
1555 }
1556
1557 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001558 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001559 return !error;
1560 }
1561
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001562 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001563 // conflicting resources are allowed to override each other, in order of last seen.
1564 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1565 // as ZIP archive and the files within are merged individually.
1566 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001567 bool MergePath(const std::string& path, bool override) {
1568 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1569 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1570 return MergeArchive(path, override);
1571 } else if (util::EndsWith(path, ".apk")) {
1572 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001573 }
1574
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001575 io::IFile* file = file_collection_->InsertFile(path);
1576 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 }
1578
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001579 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001580 // If override is true, conflicting resources are allowed to override each other, in order of last
1581 // seen.
1582 // All other file types are ignored. This is because these files could be coming from a zip,
1583 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001584 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001585 TRACE_CALL();
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001586 const android::Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001587
Adam Lesinski00451162017-10-03 07:44:08 -07001588 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001589 // Since AAPT compiles these file types and appends .flat to them, seeing
1590 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001591 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001592 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1593 << "uncompiled " << file_type
1594 << " file passed as argument. Must be "
1595 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001596 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001597 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1598 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001599 context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
Adam Lesinski00451162017-10-03 07:44:08 -07001600 return true;
1601 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001602 }
1603
Adam Lesinski00451162017-10-03 07:44:08 -07001604 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1605 if (input_stream == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001606 context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
Adam Lesinski00451162017-10-03 07:44:08 -07001607 return false;
1608 }
1609
1610 if (input_stream->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001611 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001612 << "failed to open file: " << input_stream->GetError());
1613 return false;
1614 }
1615
1616 ContainerReaderEntry* entry;
1617 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001618
1619 if (reader.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001620 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Mohamed Heikal10844322018-02-07 15:17:38 -05001621 << "failed to read file: " << reader.GetError());
1622 return false;
1623 }
1624
Adam Lesinski00451162017-10-03 07:44:08 -07001625 while ((entry = reader.Next()) != nullptr) {
1626 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001627 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001628 pb::ResourceTable pb_table;
1629 if (!entry->GetResTable(&pb_table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001630 context_->GetDiagnostics()->Error(
1631 android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001632 return false;
1633 }
1634
1635 ResourceTable table;
1636 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001637 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001638 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001639 << "failed to deserialize resource table: " << error);
1640 return false;
1641 }
1642
1643 if (!table_merger_->Merge(src, &table, override)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001644 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1645 << "failed to merge resource table");
Adam Lesinski00451162017-10-03 07:44:08 -07001646 return false;
1647 }
1648 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001649 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001650 pb::internal::CompiledFile pb_compiled_file;
1651 off64_t offset;
1652 size_t len;
1653 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001654 context_->GetDiagnostics()->Error(
1655 android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001656 return false;
1657 }
1658
1659 ResourceFile resource_file;
1660 std::string error;
1661 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001662 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001663 << "failed to read compiled header: " << error);
1664 return false;
1665 }
1666
1667 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1668 return false;
1669 }
1670 }
1671 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001672 return true;
1673 }
1674
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001675 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1676 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1677 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001678 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001679 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1680 if (!files) {
1681 return false;
1682 }
1683
1684 for (const std::string& file : files.value()) {
1685 std::string full_key = "assets/" + file;
1686 std::string full_path = assets_dir;
1687 file::AppendPath(&full_path, file);
1688
1689 auto iter = merged_assets.find(full_key);
1690 if (iter == merged_assets.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001691 merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1692 android::Source(std::move(full_path))));
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001693 } else if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001694 context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001695 << "asset file overrides '" << full_path << "'");
1696 }
1697 }
1698 }
1699
1700 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001701 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001702 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1703 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001704 return false;
1705 }
1706 }
1707 return true;
1708 }
1709
Rhed Jao2c434422020-11-12 10:48:03 +08001710 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1711 Reference* reference) {
1712 if (!reference || !reference->name) {
1713 return nullptr;
1714 }
1715 auto name_ref = ResourceNameRef(reference->name.value());
1716 if (name_ref.package.empty()) {
1717 name_ref.package = context->GetCompilationPackage();
1718 }
1719 const auto search_result = table->FindResource(name_ref);
1720 if (!search_result) {
1721 return nullptr;
1722 }
1723 return search_result.value().entry;
1724 }
1725
Ryan Mitchelldba64562019-06-07 17:07:37 -07001726 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001727 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001728 if (!application) {
1729 return;
1730 }
1731
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001732 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1733 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001734 if (!icon || !round_icon) {
1735 return;
1736 }
1737
1738 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001739 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001740 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1741 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001742 return;
1743 }
1744
1745 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001746 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001747 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1748 ? config_value->config.sdkVersion : icon_max_sdk;
1749 }
1750 if (icon_max_sdk < SDK_O) {
1751 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1752 return;
1753 }
1754
1755 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001756 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001757 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1758 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001759 return;
1760 }
1761
1762 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001763 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001764 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1765 ? config_value->config.sdkVersion : round_icon_max_sdk;
1766 }
1767 if (round_icon_max_sdk >= SDK_O) {
1768 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1769 // not generate an alias to the icon drawable.
1770 return;
1771 }
1772
1773 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001774 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001775 if (config_value->config.sdkVersion < SDK_O) {
1776 continue;
1777 }
1778
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001779 context_->GetDiagnostics()->Note(android::DiagMessage()
1780 << "generating " << round_icon_reference->name.value()
1781 << " with config \"" << config_value->config
1782 << "\" for round icon compatibility");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001783
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001784 CloningValueTransformer cloner(&table->string_pool);
1785 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001786 auto round_config_value =
1787 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001788 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001789 }
1790 }
1791
Rhed Jao2c434422020-11-12 10:48:03 +08001792 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1793 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1794 if (manifest_el == nullptr) {
1795 return true;
1796 }
1797 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1798 return true;
1799 }
1800 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1801 if (!attr) {
1802 return true;
1803 }
1804 const auto validate = [&](const std::string& shared_user_id) -> bool {
1805 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1806 return true;
1807 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001808 android::DiagMessage error_msg(manifest_el->line_number);
Rhed Jao2c434422020-11-12 10:48:03 +08001809 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1810 << shared_user_id << "'";
1811 if (options_.manifest_fixer_options.warn_validation) {
1812 // Treat the error only as a warning.
1813 context_->GetDiagnostics()->Warn(error_msg);
1814 return true;
1815 }
1816 context_->GetDiagnostics()->Error(error_msg);
1817 return false;
1818 };
1819 // If attr->compiled_value is not null, check if it is a ref
1820 if (attr->compiled_value) {
1821 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1822 if (ref == nullptr) {
1823 return true;
1824 }
1825 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1826 if (!shared_user_id_entry) {
1827 return true;
1828 }
1829 for (const auto& value : shared_user_id_entry->values) {
1830 const auto str_value = ValueCast<String>(value->value.get());
1831 if (str_value != nullptr && !validate(*str_value->value)) {
1832 return false;
1833 }
1834 }
1835 return true;
1836 }
1837
1838 // Fallback to checking the raw value
1839 return validate(attr->value);
1840 }
1841
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001842 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1843 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001844 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1845 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001846 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001847 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1848 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001849 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001850 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851 if (!result) {
1852 return false;
1853 }
1854
Ryan Mitchelldba64562019-06-07 17:07:37 -07001855 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1856 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1857 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1858 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1859 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1860 // See (b/34829129)
1861 AliasAdaptiveIcon(manifest, table);
1862
Rhed Jao2c434422020-11-12 10:48:03 +08001863 // Verify the shared user id here to handle the case of reference value.
1864 if (!VerifySharedUserId(manifest, table)) {
1865 return false;
1866 }
1867
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 ResourceFileFlattenerOptions file_flattener_options;
1869 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001870 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1871 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001872 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001873 file_flattener_options.no_auto_version = options_.no_auto_version;
1874 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001875 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1877 file_flattener_options.update_proguard_spec =
1878 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001879 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001880 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001881
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001882 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001883 if (!file_flattener.Flatten(table, writer)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001884 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885 return false;
1886 }
1887
Adam Lesinski490595a2017-11-07 17:08:07 -08001888 // Hack to fix b/68820737.
1889 // We need to modify the ResourceTable's package name, but that should NOT affect
1890 // anything else being generated, which includes the Java classes.
1891 // If required, the package name is modifed before flattening, and then modified back
1892 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001893 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001894 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1895 // or higher] as invalid. In order to work around this limitation, we allow the use
1896 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1897 // definition of what a valid "split" package ID is to account for this.
1898 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1899 context_->GetPackageId() != kAppPackageId &&
1900 context_->GetPackageId() != kFrameworkPackageId)
1901 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001902 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001903 // The base APK is included, and this is a feature split. If the base package is
1904 // the same as this package, then we are building an old style Android Instant Apps feature
1905 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001906 if (!table->packages.empty() &&
1907 table->packages.back()->name == context_->GetCompilationPackage()) {
1908 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001909 std::string new_package_name =
1910 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001911 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001912
1913 if (context_->IsVerbose()) {
1914 context_->GetDiagnostics()->Note(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001915 android::DiagMessage() << "rewriting resource package name for feature split to '"
1916 << new_package_name << "'");
Adam Lesinski490595a2017-11-07 17:08:07 -08001917 }
1918 package_to_rewrite->name = new_package_name;
1919 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001920 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001921
1922 bool success = FlattenTable(table, options_.output_format, writer);
1923
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001924 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001925 // Change the name back.
1926 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001927
1928 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1929 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1930 // library, do not include a mapping from the feature package name to the feature package id
1931 // in the feature's dynamic reference table.
1932 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001933 }
1934
1935 if (!success) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001936 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
Adam Lesinski490595a2017-11-07 17:08:07 -08001937 }
1938 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001939 }
1940
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001942 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001944 std::unique_ptr<xml::XmlResource> manifest_xml =
1945 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1946 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947 return 1;
1948 }
1949
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001950 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001951 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 const AppInfo& app_info = maybe_app_info.value();
1954 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001955 }
1956
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001957 // Determine the package name under which to merge resources.
1958 if (options_.rename_resources_package) {
1959 if (!options_.custom_java_package) {
1960 // Generate the R.java under the original package name instead of the package name specified
1961 // through --rename-resources-package.
1962 options_.custom_java_package = context_->GetCompilationPackage();
1963 }
1964 context_->SetCompilationPackage(options_.rename_resources_package.value());
1965 }
1966
Adam Lesinskic6284372017-12-04 13:46:23 -08001967 // Now that the compilation package is set, load the dependencies. This will also extract
1968 // the Android framework's versionCode and versionName, if they exist.
1969 if (!LoadSymbolsFromIncludePaths()) {
1970 return 1;
1971 }
1972
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001973 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1974 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 return 1;
1976 }
1977
Ryan Mitchell4382e442021-07-14 12:53:01 -07001978 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001979 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001981 return 1;
1982 }
1983
Adam Lesinski490595a2017-11-07 17:08:07 -08001984 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001985 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001987 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001988 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001989
1990 // Override the package ID when it is "android".
1991 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001992 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001993
1994 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001995 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001996 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001997 android::DiagMessage() << "package 'android' can only be built as a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001998 return 1;
1999 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 }
2001
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002002 TableMergerOptions table_merger_options;
2003 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07002004 table_merger_options.override_styles_instead_of_overlaying =
2005 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01002006 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002007 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002008
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002010 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002011 << StringPrintf("linking package '%s' using package ID %02x",
2012 context_->GetCompilationPackage().data(),
2013 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002014 }
2015
Adam Lesinski2427dce2017-11-30 15:10:28 -08002016 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
2017 // in res/**/*.
2018 {
2019 XmlIdCollector collector;
2020 if (!collector.Consume(context_, manifest_xml.get())) {
2021 return false;
2022 }
2023
2024 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
2025 return false;
2026 }
2027 }
2028
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 for (const std::string& input : input_files) {
2030 if (!MergePath(input, false)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002031 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002032 return 1;
2033 }
2034 }
2035
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002036 for (const std::string& input : options_.overlay_files) {
2037 if (!MergePath(input, true)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002038 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002039 return 1;
2040 }
2041 }
2042
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002043 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002044 return 1;
2045 }
2046
Adam Lesinskib522f042017-04-21 16:57:59 -07002047 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002048 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002049 if (context_->GetPackageId() == kAndroidPackageId &&
2050 !mover.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002051 context_->GetDiagnostics()->Error(android::DiagMessage()
2052 << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002053 return 1;
2054 }
2055
2056 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002057 IdAssigner id_assigner(&options_.stable_id_map);
2058 if (!id_assigner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002059 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 return 1;
2061 }
2062
2063 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 if (options_.resource_id_map_path) {
2065 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002066 for (auto& type : package->types) {
2067 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002068 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002070 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002071 }
2072 }
2073 }
2074
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002075 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002076 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 return 1;
2078 }
2079 }
2080 } else {
2081 // Static libs are merged with other apps, and ID collisions are bad, so
2082 // verify that
2083 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002084 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002085 return 1;
2086 }
2087 }
2088
2089 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002090 context_->SetNameManglerPolicy(
2091 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092
2093 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 context_->GetExternalSymbols()->PrependSource(
2095 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002097 // Workaround for pre-O runtime that would treat negative resource IDs
2098 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2099 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2100 // are just identifiers.
2101 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2102 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002103 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002104 << "enabling pre-O feature split ID rewriting");
2105 }
2106 context_->GetExternalSymbols()->SetDelegate(
2107 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2108 }
2109
Adam Lesinski34a16872018-02-23 16:18:10 -08002110 // Before we process anything, remove the resources whose default values don't exist.
2111 // We want to force any references to these to fail the build.
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002112 if (!options_.no_resource_removal) {
2113 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002114 context_->GetDiagnostics()->Error(android::DiagMessage()
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002115 << "failed removing resources with no defaults");
2116 return 1;
2117 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002118 }
2119
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002120 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002121 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002122 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 return 1;
2124 }
2125
Adam Lesinskib522f042017-04-21 16:57:59 -07002126 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 if (!options_.products.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002128 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002129 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002130 }
2131 } else {
Inseob Kim5fe521e2023-09-15 16:38:50 +09002132 ProductFilter product_filter(options_.products, /* remove_default_config_values = */ false);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002133 if (!product_filter.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002134 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 return 1;
2136 }
2137 }
2138
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002139 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002141 if (!versioner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002142 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002143 return 1;
2144 }
2145 }
2146
Adam Lesinskib522f042017-04-21 16:57:59 -07002147 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002149 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002150 << "collapsing resource versions for minimum SDK "
2151 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002152 }
2153
2154 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002155 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156 return 1;
2157 }
2158 }
2159
Winson3c918b82019-01-25 14:25:37 -08002160 if (!options_.exclude_configs_.empty()) {
2161 std::vector<ConfigDescription> excluded_configs;
2162
2163 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002164 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002165 ConfigDescription config_description;
2166
2167 if (!ConfigDescription::Parse(config_string, &config_description)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002168 context_->GetDiagnostics()->Error(
2169 android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
Winson3c918b82019-01-25 14:25:37 -08002170 return 1;
2171 }
2172
2173 excluded_configs.push_back(config_description);
2174 }
2175
2176 ResourceExcluder excluder(excluded_configs);
2177 if (!excluder.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002178 context_->GetDiagnostics()->Error(android::DiagMessage()
2179 << "failed excluding configurations");
Winson3c918b82019-01-25 14:25:37 -08002180 return 1;
2181 }
2182 }
2183
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002186 if (!deduper.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002187 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002188 return 1;
2189 }
2190 }
2191
Adam Koskidc21dea2017-07-21 10:55:27 -07002192 proguard::KeepSet proguard_keep_set =
2193 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002194 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002195
Adam Lesinskib522f042017-04-21 16:57:59 -07002196 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002197 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002198 !options_.table_splitter_options.preferred_densities.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002199 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002200 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201 }
2202 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002203 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2204 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002205 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002206 options_.split_constraints =
2207 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002208
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002209 if (origConstraintSize != options_.split_constraints.size()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002210 context_->GetDiagnostics()->Warn(android::DiagMessage()
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002211 << "requested to split resources prior to min sdk of "
2212 << context_->GetMinSdkVersion());
2213 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002214 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002215 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002216 return 1;
2217 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002218 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002219
2220 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002221 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002222 auto split_constraints_iter = options_.split_constraints.begin();
2223 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002224 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002225 context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002226 << "generating split with configurations '"
2227 << util::Joiner(split_constraints_iter->configs, ", ")
2228 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002229 }
2230
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002231 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002232 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002233 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002234 return 1;
2235 }
2236
2237 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002238 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002239 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002240
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002241 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002242 if (!linker.Consume(context_, split_manifest.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002243 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002244 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002245 return 1;
2246 }
2247
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002248 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2249 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002250 return 1;
2251 }
2252
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002253 ++path_iter;
2254 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002255 }
2256 }
2257
2258 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002259 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002260 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002261 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002262 return 1;
2263 }
2264
2265 bool error = false;
2266 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002267 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002268 // (aka, which package the AndroidManifest.xml is coming from).
2269 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002270 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002272 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002273 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002274 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002275 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002276 error = true;
2277 }
2278
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002279 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002280 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002281 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002282 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002283 }
2284
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002285 if (options_.generate_java_class_path) {
2286 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002287 error = true;
2288 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002289 }
2290
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002291 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002292 // PackageParser will fail if URIs are removed from
2293 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002294 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2295 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002296 error = true;
2297 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002298 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002299 } else {
2300 error = true;
2301 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002302 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002303
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002304 if (error) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002305 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002306 return 1;
2307 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002308
Josh Houec67cb42022-06-09 19:19:21 +08002309 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2310 return 1;
2311 };
2312
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002313 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2314 return 1;
2315 }
2316
2317 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002318 return 1;
2319 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002320
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002321 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002322 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002323 return 1;
2324 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002325 }
2326
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002327 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002328 return 1;
2329 }
2330
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002331 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2332 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002333 return 1;
2334 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335 return 0;
2336 }
2337
2338 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002339 LinkOptions options_;
2340 LinkContext* context_;
2341 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002342
Adam Lesinski490595a2017-11-07 17:08:07 -08002343 AppInfo app_info_;
2344
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002345 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002346
2347 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002348 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002349
Adam Lesinski8780eb62017-10-31 17:44:39 -07002350 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002351 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002352 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002353
Adam Lesinski8780eb62017-10-31 17:44:39 -07002354 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2355 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2356
2357 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2358 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002359
2360 // The set of shared libraries being used, mapping their assigned package ID to package name.
2361 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002362
2363 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002364 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002365};
2366
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002367int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002368 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002369 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002370
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002371 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002372 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002373 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002374 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002375 const std::string path = arg.substr(1, arg.size() - 1);
2376 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002377 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002378 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002379 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002380 }
2381 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002382 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002383 }
2384 }
2385
2386 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002387 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002388 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002389 const std::string path = arg.substr(1, arg.size() - 1);
2390 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002391 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002392 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002393 return 1;
2394 }
2395 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002396 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002397 }
2398 }
2399
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002400 if (verbose_) {
2401 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002402 }
2403
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002404 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002405 context.GetDiagnostics()
2406 ->Error(android::DiagMessage()
2407 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002408 return 1;
2409 }
2410
Ryan Mitchell5855de72021-02-24 14:39:13 -08002411 if (shared_lib_ && options_.private_symbols) {
2412 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2413 // reference the private attribute within the styleable array will cause a link error because
2414 // the private attribute will not be emitted in the public R.java.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002415 context.GetDiagnostics()->Error(android::DiagMessage()
Ryan Mitchell5855de72021-02-24 14:39:13 -08002416 << "--shared-lib cannot currently be used in combination with"
2417 << " --private-symbols");
2418 return 1;
2419 }
2420
Izabela Orlowska84febea2019-06-03 18:34:12 +01002421 if (options_.merge_only && !static_lib_) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002422 context.GetDiagnostics()
2423 ->Error(android::DiagMessage()
2424 << "the --merge-only flag can be only used when building a static library");
Izabela Orlowska84febea2019-06-03 18:34:12 +01002425 return 1;
2426 }
Iurii Makhnoda06e4d2022-08-24 14:17:32 +00002427 if (options_.use_sparse_encoding) {
2428 options_.table_flattener_options.sparse_entries = SparseEntriesMode::Enabled;
2429 }
Izabela Orlowska84febea2019-06-03 18:34:12 +01002430
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002431 // The default build type.
2432 context.SetPackageType(PackageType::kApp);
2433 context.SetPackageId(kAppPackageId);
2434
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002435 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002436 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002437 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002438 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002439 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002440 options_.output_format = OutputFormat::kProto;
2441 } else if (proto_format_) {
2442 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002443 }
2444
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002445 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002446 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002447 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002448 android::DiagMessage() << "can't specify --package-id when not building a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002449 return 1;
2450 }
2451
Ryan Mitchell4382e442021-07-14 12:53:01 -07002452 const std::optional<uint32_t> maybe_package_id_int =
2453 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002454 if (!maybe_package_id_int) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002455 context.GetDiagnostics()->Error(android::DiagMessage()
2456 << "package ID '" << package_id_.value()
2457 << "' is not a valid integer");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002458 return 1;
2459 }
2460
2461 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002462 if (package_id_int > std::numeric_limits<uint8_t>::max()
2463 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002464 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002465 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002466 android::DiagMessage() << StringPrintf(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002467 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2468 return 1;
2469 }
2470 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2471 }
2472
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002473 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002474 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002475 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002476 for (StringPiece package : util::Split(extra_package, ':')) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002477 options_.extra_java_packages.emplace(package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002478 }
2479 }
2480
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002481 if (product_list_) {
2482 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002483 if (product != "" && product != "default") {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -07002484 options_.products.emplace(product);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002485 }
2486 }
2487 }
2488
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002489 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002490 if (!configs_.empty()) {
2491 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002492 if (filter == nullptr) {
2493 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002494 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002495 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002496 }
2497
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002498 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002499 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002500 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002501 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002502 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002503 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002504 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002505 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002506
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002507 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002508 for (const std::string& split_arg : split_args_) {
2509 options_.split_paths.push_back({});
2510 options_.split_constraints.push_back({});
2511 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2512 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002513 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002514 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002515 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002516
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002517 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2518 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2519 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002520 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002521 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002522 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002523
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002524 if (no_compress_regex) {
2525 std::string regex = no_compress_regex.value();
2526 if (util::StartsWith(regex, "@")) {
2527 const std::string path = regex.substr(1, regex.size() -1);
2528 std::string error;
2529 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002530 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002531 return 1;
2532 }
2533 } else {
2534 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2535 }
2536 }
2537
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002538 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002539 options_.extensions_to_not_compress.insert({
2540 // Image extensions
2541 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2542 // Audio extensions
2543 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2544 ".xmf", ".amr", ".awb",
2545 // Audio/video extensions
2546 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2547 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002548
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002549 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002550 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002551 options_.no_auto_version = true;
2552 options_.no_version_vectors = true;
2553 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002554 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002555
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002556 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002557 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002558}
2559
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002560} // namespace aapt