blob: 82f2e8f7ed73f67c471e4b1eb2802e68324e2266 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
20
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050021#include <algorithm>
Jeremy Meyer56f36e82022-05-20 20:35:42 +000022#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
Adam Lesinski1ab598f2015-08-14 14:26:04 -070027#include "AppInfo.h"
28#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070029#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080031#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070032#include "ResourceValues.h"
33#include "ValueVisitor.h"
Jeremy Meyer56f36e82022-05-20 20:35:42 +000034#include "android-base/errors.h"
35#include "android-base/expected.h"
36#include "android-base/file.h"
37#include "android-base/stringprintf.h"
38#include "androidfw/IDiagnostics.h"
39#include "androidfw/Locale.h"
40#include "androidfw/StringPiece.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070041#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070042#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080043#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080044#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070046#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070047#include "format/binary/TableFlattener.h"
48#include "format/binary/XmlFlattener.h"
49#include "format/proto/ProtoDeserialize.h"
50#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070051#include "io/BigBufferStream.h"
52#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070054#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080055#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070056#include "java/JavaClassGenerator.h"
57#include "java/ManifestClassGenerator.h"
58#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070060#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080061#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080062#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080063#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070065#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080066#include "optimize/ResourceDeduper.h"
67#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "process/IResourceTableConsumer.h"
69#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080070#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080071#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080073#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070075using ::aapt::io::FileInputStream;
MÃ¥rten Kongstad24c9aa62018-06-20 08:46:41 +020076using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070077using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070078using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070079using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070080using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070081
Adam Lesinski1ab598f2015-08-14 14:26:04 -070082namespace aapt {
83
Ryan Mitchell9634efb2021-03-19 14:53:17 -070084namespace {
85
86expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
87 // Resource tables built by aapt2 always contain one package. This is a post condition of
88 // VerifyNoExternalPackages.
89 if (table->packages.size() != 1u) {
90 return unexpected("static library contains more than one package");
91 }
92 return table->packages.back().get();
93}
94
95} // namespace
96
Ryan Mitchell22dc5312020-06-01 12:17:07 -070097constexpr uint8_t kAndroidPackageId = 0x01;
98
Adam Lesinski64587af2016-02-18 18:33:06 -080099class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700100 public:
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000101 explicit LinkContext(android::IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100102 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700103 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104
Adam Lesinskib522f042017-04-21 16:57:59 -0700105 PackageType GetPackageType() override {
106 return package_type_;
107 }
108
109 void SetPackageType(PackageType type) {
110 package_type_ = type;
111 }
112
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000113 android::IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100114 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 NameMangler* GetNameMangler() override {
118 return &name_mangler_;
119 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700121 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
122 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800124
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 const std::string& GetCompilationPackage() override {
126 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700128
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700129 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800130 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 uint8_t GetPackageId() override {
134 return package_id_;
135 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetPackageId(uint8_t id) {
138 package_id_ = id;
139 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800140
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700141 SymbolTable* GetExternalSymbols() override {
142 return &symbols_;
143 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800144
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 bool IsVerbose() override {
146 return verbose_;
147 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 void SetVerbose(bool val) {
150 verbose_ = val;
151 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800152
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700153 int GetMinSdkVersion() override {
154 return min_sdk_version_;
155 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700156
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700157 void SetMinSdkVersion(int minSdk) {
158 min_sdk_version_ = minSdk;
159 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700160
Udam Sainib228df32019-06-18 16:50:34 -0700161 const std::set<std::string>& GetSplitNameDependencies() override {
162 return split_name_dependencies_;
163 }
164
165 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
166 split_name_dependencies_ = split_name_dependencies;
167 }
168
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700170 DISALLOW_COPY_AND_ASSIGN(LinkContext);
171
Adam Lesinskib522f042017-04-21 16:57:59 -0700172 PackageType package_type_ = PackageType::kApp;
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000173 android::IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700174 NameMangler name_mangler_;
175 std::string compilation_package_;
176 uint8_t package_id_ = 0x0;
177 SymbolTable symbols_;
178 bool verbose_ = false;
179 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700180 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700181};
182
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700183// A custom delegate that generates compatible pre-O IDs for use with feature splits.
184// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
185// is interpreted as a negative number. Some verification was wrongly assuming negative values
186// were invalid.
187//
188// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
189// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
190// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800191//
192// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700193class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
194 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800195 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700196 }
197
198 virtual ~FeatureSplitSymbolTableDelegate() = default;
199
200 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
201 const ResourceName& name,
202 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
203 std::unique_ptr<SymbolTable::Symbol> symbol =
204 DefaultSymbolTableDelegate::FindByName(name, sources);
205 if (symbol == nullptr) {
206 return {};
207 }
208
209 // Check to see if this is an 'id' with the target package.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000210 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700211 ResourceId* id = &symbol->id.value();
212 if (id->package_id() > kAppPackageId) {
213 // Rewrite the resource ID to be compatible pre-O.
214 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
215
216 // Check that this doesn't overlap another resource.
217 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
218 // The ID overlaps, so log a message (since this is a weird failure) and fail.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000219 context_->GetDiagnostics()->Error(android::DiagMessage()
220 << "Failed to rewrite " << name
221 << " for pre-O feature split support");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700222 return {};
223 }
224
225 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000226 context_->GetDiagnostics()->Note(android::DiagMessage()
227 << "rewriting " << name << " (" << *id << ") -> ("
228 << rewritten_id << ")");
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700229 }
230
231 *id = rewritten_id;
232 }
233 }
234 return symbol;
235 }
236
237 private:
238 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
239
240 IAaptContext* context_;
241};
242
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700243static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
244 const StringPiece& path, bool keep_raw_values, bool utf16,
245 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800246 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700247 if (context->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000248 context->GetDiagnostics()->Note(android::DiagMessage(path)
249 << "writing to archive (keep_raw_values="
250 << (keep_raw_values ? "true" : "false") << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700251 }
252
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700253 switch (format) {
254 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000255 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700256 XmlFlattenerOptions options = {};
257 options.keep_raw_values = keep_raw_values;
258 options.use_utf16 = utf16;
259 XmlFlattener flattener(&buffer, options);
260 if (!flattener.Consume(context, &xml_res)) {
261 return false;
262 }
263
264 io::BigBufferInputStream input_stream(&buffer);
265 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
266 ArchiveEntry::kCompress, writer);
267 } break;
268
269 case OutputFormat::kProto: {
270 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800271 // Strip whitespace text nodes from tha AndroidManifest.xml
272 SerializeXmlOptions options;
273 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700274 SerializeXmlResourceToPb(xml_res, &pb_node);
275 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
276 writer);
277 } break;
278 }
279 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800280}
281
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700282// Inflates an XML file from the source path.
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000283static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path,
284 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800285 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700286 FileInputStream fin(path);
287 if (fin.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000288 diag->Error(android::DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700289 return {};
290 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000291 return xml::Inflate(&fin, diag, android::Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800292}
293
Adam Lesinski355f2852016-02-13 20:26:45 -0800294struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700295 bool no_auto_version = false;
296 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900297 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700298 bool no_xml_namespaces = false;
299 bool keep_raw_values = false;
300 bool do_not_compress_anything = false;
301 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100302 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700303 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700304 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700305 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800306};
307
Adam Lesinskic744ae82017-05-17 19:28:38 -0700308// A sampling of public framework resource IDs.
309struct R {
310 struct attr {
311 enum : uint32_t {
312 paddingLeft = 0x010100d6u,
313 paddingRight = 0x010100d8u,
314 paddingHorizontal = 0x0101053du,
315
316 paddingTop = 0x010100d7u,
317 paddingBottom = 0x010100d9u,
318 paddingVertical = 0x0101053eu,
319
320 layout_marginLeft = 0x010100f7u,
321 layout_marginRight = 0x010100f9u,
322 layout_marginHorizontal = 0x0101053bu,
323
324 layout_marginTop = 0x010100f8u,
325 layout_marginBottom = 0x010100fau,
326 layout_marginVertical = 0x0101053cu,
327 };
328 };
329};
330
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700331template <typename T>
332uint32_t GetCompressionFlags(const StringPiece& str, T options) {
333 if (options.do_not_compress_anything) {
334 return 0;
335 }
336
337 if (options.regex_to_not_compress
338 && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) {
339 return 0;
340 }
341
342 for (const std::string& extension : options.extensions_to_not_compress) {
343 if (util::EndsWith(str, extension)) {
344 return 0;
345 }
346 }
347 return ArchiveEntry::kCompress;
348}
349
Adam Lesinski355f2852016-02-13 20:26:45 -0800350class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700351 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700352 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700353 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800354
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700355 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800356
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 private:
358 struct FileOperation {
359 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700362 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700365 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700369
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700370 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700372 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800373
Adam Lesinskic744ae82017-05-17 19:28:38 -0700374 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
375 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800376
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700377 ResourceFileFlattenerOptions options_;
378 IAaptContext* context_;
379 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700380 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800381};
382
Adam Lesinskic744ae82017-05-17 19:28:38 -0700383ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
384 IAaptContext* context, proguard::KeepSet* keep_set)
385 : options_(options), context_(context), keep_set_(keep_set) {
386 SymbolTable* symm = context_->GetExternalSymbols();
387
388 // Build up the rules for degrading newer attributes to older ones.
389 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
390 // generated from the attribute definitions themselves (b/62028956).
391 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
392 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800393 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
394 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700395 };
396 rules_[R::attr::paddingHorizontal] =
397 util::make_unique<DegradeToManyRule>(std::move(replacements));
398 }
399
400 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
401 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800402 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
403 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700404 };
405 rules_[R::attr::paddingVertical] =
406 util::make_unique<DegradeToManyRule>(std::move(replacements));
407 }
408
409 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
410 std::vector<ReplacementAttr> replacements{
411 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800412 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700413 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800414 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700415 };
416 rules_[R::attr::layout_marginHorizontal] =
417 util::make_unique<DegradeToManyRule>(std::move(replacements));
418 }
419
420 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
421 std::vector<ReplacementAttr> replacements{
422 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800423 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700424 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800425 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700426 };
427 rules_[R::attr::layout_marginVertical] =
428 util::make_unique<DegradeToManyRule>(std::move(replacements));
429 }
430}
431
Adam Lesinskibb94f322017-07-12 07:41:55 -0700432static bool IsTransitionElement(const std::string& name) {
433 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
434 name == "changeImageTransform" || name == "changeTransform" ||
435 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
436 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
437 name == "transitionManager";
438}
439
440static bool IsVectorElement(const std::string& name) {
441 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800442 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
443 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700444}
445
Adam Lesinskic744ae82017-05-17 19:28:38 -0700446template <typename T>
447std::vector<T> make_singleton_vec(T&& val) {
448 std::vector<T> vec;
449 vec.emplace_back(std::forward<T>(val));
450 return vec;
451}
452
453std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
454 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800455 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000457 const android::Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700458
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700459 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000460 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700461 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700462 }
463
Adam Lesinski00451162017-10-03 07:44:08 -0700464 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
465 // that existing projects have out-of-date references which pass compilation.
466 xml::StripAndroidStudioAttributes(doc->root.get());
467
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700468 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100469 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700470 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700471 }
472
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700473 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700474 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700475 }
476
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700477 if (options_.no_xml_namespaces) {
478 XmlNamespaceRemover namespace_remover;
479 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800481 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700482 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800483
Adam Lesinskibb94f322017-07-12 07:41:55 -0700484 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700485 return make_singleton_vec(std::move(file_op->xml_to_flatten));
486 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700487
Adam Lesinskibb94f322017-07-12 07:41:55 -0700488 if (options_.no_version_vectors || options_.no_version_transitions) {
489 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700490 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700491 if (el && el->namespace_uri.empty()) {
492 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
493 (options_.no_version_transitions && IsTransitionElement(el->name))) {
494 return make_singleton_vec(std::move(file_op->xml_to_flatten));
495 }
496 }
497 }
498
Adam Lesinskic744ae82017-05-17 19:28:38 -0700499 const ConfigDescription& config = file_op->config;
500 ResourceEntry* entry = file_op->entry;
501
502 XmlCompatVersioner xml_compat_versioner(&rules_);
503 const util::Range<ApiVersion> api_range{config.sdkVersion,
504 FindNextApiVersionForConfig(entry, config)};
505 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800506}
507
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800508ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
509 switch (format) {
510 case OutputFormat::kApk:
511 return ResourceFile::Type::kBinaryXml;
512 case OutputFormat::kProto:
513 return ResourceFile::Type::kProtoXml;
514 }
515 LOG_ALWAYS_FATAL("unreachable");
516 return ResourceFile::Type::kUnknown;
517}
518
Ryan Mitchell70f79722018-08-13 07:37:24 -0700519static auto kDrawableVersions = std::map<std::string, ApiVersion>{
520 { "adaptive-icon" , SDK_O },
521};
522
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700523bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800524 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700525 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700526 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800527
Adam Koskidc21dea2017-07-21 10:55:27 -0700528 proguard::CollectResourceReferences(context_, table, keep_set_);
529
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700531 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
532
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700534 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700535 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700536 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800537
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 // Populate the queue with all files in the ResourceTable.
539 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700540 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700541 // WARNING! Do not insert or remove any resources while executing in this scope. It will
542 // corrupt the iteration order.
543
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700544 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700545 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700546 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700548
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700549 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700550 if (!file) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000551 context_->GetDiagnostics()->Error(android::DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700553 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554 }
555
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 FileOperation file_op;
557 file_op.entry = entry.get();
558 file_op.dst_path = *file_ref->path;
559 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700560 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000562 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700563 (file_ref->type == ResourceFile::Type::kBinaryXml ||
564 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700565 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 if (!data) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000567 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700568 << "failed to open file");
569 return false;
570 }
571
Adam Lesinski00451162017-10-03 07:44:08 -0700572 if (file_ref->type == ResourceFile::Type::kProtoXml) {
573 pb::XmlNode pb_xml_node;
574 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000575 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700576 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700577 return false;
578 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579
Adam Lesinski00451162017-10-03 07:44:08 -0700580 std::string error;
581 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
582 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000583 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700584 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700585 return false;
586 }
587 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700588 std::string error_str;
589 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700590 if (file_op.xml_to_flatten == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000591 context_->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700592 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700593 return false;
594 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700595 }
596
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800597 // Update the type that this file will be written as.
598 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
599
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700600 file_op.xml_to_flatten->file.config = config_value->config;
601 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000602 file_op.xml_to_flatten->file.name =
603 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700604 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700605
606 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
607 // else we end up copying the string in the std::make_pair() method,
608 // then creating a StringPiece from the copy, which would cause us
609 // to end up referencing garbage in the map.
610 const StringPiece entry_name(entry->name);
611 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
612 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700613 }
614 }
615
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 for (auto& map_entry : config_sorted_files) {
618 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700619 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700622 // Check minimum sdk versions supported for drawables
623 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
624 if (drawable_entry != kDrawableVersions.end()) {
625 if (drawable_entry->second > context_->GetMinSdkVersion()
626 && drawable_entry->second > config.sdkVersion) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000627 context_->GetDiagnostics()->Error(
628 android::DiagMessage(file_op.xml_to_flatten->file.source)
629 << "<" << drawable_entry->first << "> elements "
630 << "require a sdk version of at least " << (int16_t)drawable_entry->second);
Ryan Mitchell70f79722018-08-13 07:37:24 -0700631 error = true;
632 continue;
633 }
634 }
635
Adam Lesinskic744ae82017-05-17 19:28:38 -0700636 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
637 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700638 if (versioned_docs.empty()) {
639 error = true;
640 continue;
641 }
642
Adam Lesinskic744ae82017-05-17 19:28:38 -0700643 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
644 std::string dst_path = file_op.dst_path;
645 if (doc->file.config != file_op.config) {
646 // Only add the new versioned configurations.
647 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000648 context_->GetDiagnostics()->Note(android::DiagMessage(doc->file.source)
Adam Lesinskic744ae82017-05-17 19:28:38 -0700649 << "auto-versioning resource from config '"
650 << config << "' -> '" << doc->file.config << "'");
651 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700652
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800653 const ResourceFile& file = doc->file;
654 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
655
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700656 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800657 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
658 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700659
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800660 // Update the output format of this XML file.
661 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700662 bool result = table->AddResource(NewResourceBuilder(file.name)
663 .SetValue(std::move(file_ref), file.config)
664 .SetAllowMangled(true)
665 .Build(),
666 context_->GetDiagnostics());
667 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700668 return false;
669 }
670 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700671
672 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
673 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 }
675 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700676 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700677 GetCompressionFlags(file_op.dst_path, options_),
678 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700679 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700681 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 }
683 return !error;
684}
685
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000686static bool WriteStableIdMapToPath(android::IDiagnostics* diag,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700687 const std::unordered_map<ResourceName, ResourceId>& id_map,
688 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800689 io::FileOutputStream fout(id_map_path);
690 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000691 diag->Error(android::DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 return false;
693 }
694
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800695 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700696 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697 const ResourceName& name = entry.first;
698 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800699 printer.Print(name.to_string());
700 printer.Print(" = ");
701 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700702 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800703 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800705 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000706 diag->Error(android::DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 return false;
708 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 return true;
710}
711
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000712static bool LoadStableIdMap(android::IDiagnostics* diag, const std::string& path,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700713 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700714 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700715 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000716 diag->Error(android::DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 return false;
718 }
719
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 out_id_map->clear();
721 size_t line_no = 0;
722 for (StringPiece line : util::Tokenize(content, '\n')) {
723 line_no++;
724 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 if (line.empty()) {
726 continue;
727 }
728
729 auto iter = std::find(line.begin(), line.end(), '=');
730 if (iter == line.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000731 diag->Error(android::DiagMessage(android::Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700732 return false;
733 }
734
735 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700736 StringPiece res_name_str =
737 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
738 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000739 diag->Error(android::DiagMessage(android::Source(path, line_no))
740 << "invalid resource name '" << res_name_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700741 return false;
742 }
743
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700744 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
745 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700746 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700747
Ryan Mitchell4382e442021-07-14 12:53:01 -0700748 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700749 if (!maybe_id) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000750 diag->Error(android::DiagMessage(android::Source(path, line_no))
751 << "invalid resource ID '" << res_id_str << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700752 return false;
753 }
754
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700755 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700756 }
757 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700758}
759
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700760class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700761 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700762 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700763 : options_(options),
764 context_(context),
765 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700766 file_collection_(util::make_unique<io::FileCollection>()) {
767 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700768
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800769 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800770 using namespace android;
771
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000772 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
773 // we're looking for the first attribute resource in the system package.
774 android::ApkAssetsCookie cookie;
775 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
776 cookie = value->cookie;
777 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800778 // No Framework assets loaded. Not a failure.
779 return;
780 }
781
782 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800783 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800784 if (manifest == nullptr) {
785 // No errors.
786 return;
787 }
788
789 std::string error;
790 std::unique_ptr<xml::XmlResource> manifest_xml =
791 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
792 if (manifest_xml == nullptr) {
793 // No errors.
794 return;
795 }
796
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700797 if (!options_.manifest_fixer_options.compile_sdk_version) {
798 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
799 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700800 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700801 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
802 switch (prim->value.dataType) {
803 case Res_value::TYPE_INT_DEC:
804 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
805 break;
806 case Res_value::TYPE_INT_HEX:
807 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
808 break;
809 default:
810 break;
811 }
812 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
813 compile_sdk_version = *str->value;
814 } else {
815 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800816 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800817 }
818 }
819
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700820 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
821 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
822 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700823 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700824 options_.manifest_fixer_options.compile_sdk_version_codename;
825 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
826 compile_sdk_version_codename = *str->value;
827 } else {
828 compile_sdk_version_codename = attr->value;
829 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800830 }
831 }
832 }
833
Adam Lesinski8780eb62017-10-31 17:44:39 -0700834 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800835 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700836 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800837 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700838 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700839 for (const std::string& path : options_.include_paths) {
840 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000841 context_->GetDiagnostics()->Note(android::DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700842 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700843
Adam Lesinski8780eb62017-10-31 17:44:39 -0700844 std::string error;
845 auto zip_collection = io::ZipFileCollection::Create(path, &error);
846 if (zip_collection == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000847 context_->GetDiagnostics()->Error(android::DiagMessage()
848 << "failed to open APK: " << error);
Adam Lesinski8780eb62017-10-31 17:44:39 -0700849 return false;
850 }
851
852 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
853 // Load this as a static library include.
854 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000855 android::Source(path), std::move(zip_collection), context_->GetDiagnostics());
Adam Lesinski8780eb62017-10-31 17:44:39 -0700856 if (static_apk == nullptr) {
857 return false;
858 }
859
Adam Lesinskib522f042017-04-21 16:57:59 -0700860 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800861 // Can't include static libraries when not building a static library (they have no IDs
862 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700863 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000864 android::DiagMessage(path)
865 << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700866 return false;
867 }
868
Adam Lesinski8780eb62017-10-31 17:44:39 -0700869 ResourceTable* table = static_apk->GetResourceTable();
870
871 // 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 -0700872 // our compilation package so the symbol package name does not get mangled into the entry
873 // name.
874 if (options_.no_static_lib_packages && !table->packages.empty()) {
875 auto lib_package_result = GetStaticLibraryPackage(table);
876 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000877 context_->GetDiagnostics()->Error(android::DiagMessage(path)
878 << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800879 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700880 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700881 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 }
883
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700884 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700885 util::make_unique<ResourceTableSymbolSource>(table));
886 static_library_includes_.push_back(std::move(static_apk));
887 } else {
888 if (!asset_source->AddAssetPath(path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000889 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinski8780eb62017-10-31 17:44:39 -0700890 << "failed to load include path " << path);
891 return false;
892 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 }
894 }
895
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800896 // Capture the shared libraries so that the final resource table can be properly flattened
897 // with support for shared libraries.
898 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700899 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800900 // Capture the included base feature package.
901 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800902 } else if (entry.first == kFrameworkPackageId) {
903 // Try to embed which version of the framework we're compiling against.
904 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
905 // when linking our synthesized 'android:compileSdkVersion' attribute.
906 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
907 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
908 if (symbol != nullptr && symbol->is_public) {
909 // The symbol is present and public, extract the android:versionName and
910 // android:versionCode from the framework AndroidManifest.xml.
911 ExtractCompileSdkVersions(asset_source->GetAssetManager());
912 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700913 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700914 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800915 }
916 }
917
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700918 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700919 return true;
920 }
921
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000922 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res,
923 android::IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800924 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700925 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800926 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
927 if (manifest_el == nullptr) {
928 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700929 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800930
931 AppInfo app_info;
932
933 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000934 diag->Error(android::DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800935 return {};
936 }
937
938 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
939 if (!package_attr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000940 diag->Error(android::DiagMessage(xml_res->file.source)
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800941 << "<manifest> must have a 'package' attribute");
942 return {};
943 }
944 app_info.package = package_attr->value;
945
946 if (xml::Attribute* version_code_attr =
947 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700948 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800949 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000950 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800951 << "invalid android:versionCode '" << version_code_attr->value << "'");
952 return {};
953 }
954 app_info.version_code = maybe_code.value();
955 }
956
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700957 if (xml::Attribute* version_code_major_attr =
958 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700959 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700960 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000961 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
962 << "invalid android:versionCodeMajor '" << version_code_major_attr->value
963 << "'");
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700964 return {};
965 }
966 app_info.version_code_major = maybe_code.value();
967 }
968
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800969 if (xml::Attribute* revision_code_attr =
970 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700971 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800972 if (!maybe_code) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +0000973 diag->Error(android::DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800974 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
975 return {};
976 }
977 app_info.revision_code = maybe_code.value();
978 }
979
980 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
981 if (!split_name_attr->value.empty()) {
982 app_info.split_name = split_name_attr->value;
983 }
984 }
985
986 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
987 if (xml::Attribute* min_sdk =
988 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700989 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800990 }
991 }
Udam Sainib228df32019-06-18 16:50:34 -0700992
993 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
994 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
995 if (const xml::Attribute* split_name =
996 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
997 if (!split_name->value.empty()) {
998 app_info.split_name_dependencies.insert(split_name->value);
999 }
1000 }
1001 }
1002 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -08001003 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 }
1005
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001006 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1007 // Postcondition: ResourceTable has only one package left. All others are
1008 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001010 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001011 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 };
1013
1014 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001015 for (const auto& package : final_table_.packages) {
1016 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 // We have a package that is not related to the one we're building!
1018 for (const auto& type : package->types) {
1019 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001020 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001022 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001024 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001025 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001026 context_->GetDiagnostics()->Warn(
1027 android::DiagMessage(config_value->value->GetSource())
1028 << "generated id '" << res_name << "' for external package '" << package->name
1029 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001030 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001031 context_->GetDiagnostics()->Error(
1032 android::DiagMessage(config_value->value->GetSource())
1033 << "defined resource '" << res_name << "' for external package '"
1034 << package->name << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001035 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001036 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001037 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 }
1039 }
1040 }
1041 }
1042
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001043 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1044 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001045 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001046 return !error;
1047 }
1048
1049 /**
1050 * Returns true if no IDs have been set, false otherwise.
1051 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001052 bool VerifyNoIdsSet() {
1053 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001055 for (const auto& entry : type->entries) {
1056 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001057 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001058 context_->GetDiagnostics()->Error(android::DiagMessage()
1059 << "resource " << res_name << " has ID "
1060 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061 return false;
1062 }
1063 }
1064 }
1065 }
1066 return true;
1067 }
1068
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001069 bool VerifyLocaleFormat(xml::XmlResource* manifest, android::IDiagnostics* diag) {
Josh Houd3bd4522022-02-14 10:24:42 +08001070 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1071 // element.
1072 const xml::Element* application = manifest->root->FindChild("", "application");
1073 if (!application) {
1074 return true;
1075 }
1076 const xml::Attribute* localeConfig =
1077 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1078 if (!localeConfig) {
1079 return true;
1080 }
1081
1082 if (localeConfig->compiled_value) {
1083 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1084 const auto localeconfig_entry =
1085 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1086 if (!localeconfig_entry) {
1087 return true;
1088 }
1089
1090 for (const auto& value : localeconfig_entry->values) {
1091 // Load an XML file which is linked from the localeConfig attribute.
1092 const std::string& path = value->value->GetSource().path;
1093 std::unique_ptr<xml::XmlResource> localeConfig_xml = LoadXml(path, diag);
1094 if (!localeConfig_xml) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001095 diag->Error(android::DiagMessage(path) << "can't load the XML");
Josh Houd3bd4522022-02-14 10:24:42 +08001096 return false;
1097 }
1098
1099 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1100 if (!localeConfig_el) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001101 diag->Error(android::DiagMessage(path) << "no root tag defined");
Josh Houd3bd4522022-02-14 10:24:42 +08001102 return false;
1103 }
1104 if (localeConfig_el->name != "locale-config") {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001105 diag->Error(android::DiagMessage(path)
1106 << "invalid element name: " << localeConfig_el->name
1107 << ", expected: locale-config");
Josh Houd3bd4522022-02-14 10:24:42 +08001108 return false;
1109 }
1110
1111 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1112 if (child_el->name == "locale") {
1113 if (const xml::Attribute* locale_name_attr =
1114 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1115 const std::string& locale_name = locale_name_attr->value;
1116 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1117
1118 // Start to verify the locale format
1119 ConfigDescription config;
1120 if (!ConfigDescription::Parse(valid_name, &config)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001121 diag->Error(android::DiagMessage(path) << "invalid configuration: " << locale_name);
Josh Houd3bd4522022-02-14 10:24:42 +08001122 return false;
1123 }
1124 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001125 diag->Error(android::DiagMessage(path) << "the attribute android:name is not found");
Josh Houd3bd4522022-02-14 10:24:42 +08001126 return false;
1127 }
1128 } else {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001129 diag->Error(android::DiagMessage(path)
Josh Houd3bd4522022-02-14 10:24:42 +08001130 << "invalid element name: " << child_el->name << ", expected: locale");
1131 return false;
1132 }
1133 }
1134 }
1135 }
1136 return true;
1137 }
1138
1139 std::string ConvertToBCP47Tag(const std::string& locale) {
1140 std::string bcp47tag = "b+";
1141 bcp47tag += locale;
1142 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1143
1144 return bcp47tag;
1145 }
1146
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001147 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1148 if (options_.output_to_directory) {
1149 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001150 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001151 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001152 }
1153 }
1154
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001155 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001156 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001157 switch (format) {
1158 case OutputFormat::kApk: {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001159 android::BigBuffer buffer(1024);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001160 TableFlattener flattener(options_.table_flattener_options, &buffer);
1161 if (!flattener.Consume(context_, table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001162 context_->GetDiagnostics()->Error(android::DiagMessage()
1163 << "failed to flatten resource table");
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001164 return false;
1165 }
1166
1167 io::BigBufferInputStream input_stream(&buffer);
1168 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1169 ArchiveEntry::kAlign, writer);
1170 } break;
1171
1172 case OutputFormat::kProto: {
1173 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001174 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1175 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001176 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1177 ArchiveEntry::kCompress, writer);
1178 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001179 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001180 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001181 }
1182
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001183 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001184 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001185 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001186 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001187 return true;
1188 }
1189
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001190 std::string out_path;
1191 std::unique_ptr<io::FileOutputStream> fout;
1192 if (options_.generate_java_class_path) {
1193 out_path = options_.generate_java_class_path.value();
1194 file::AppendPath(&out_path, file::PackageToPath(out_package));
1195 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001196 context_->GetDiagnostics()->Error(android::DiagMessage()
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001197 << "failed to create directory '" << out_path << "'");
1198 return false;
1199 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001200
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001201 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001203 fout = util::make_unique<io::FileOutputStream>(out_path);
1204 if (fout->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001205 context_->GetDiagnostics()->Error(android::DiagMessage()
1206 << "failed writing to '" << out_path
1207 << "': " << fout->GetError());
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001208 return false;
1209 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001210 }
1211
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001212 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001213 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001214 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1215 if (fout_text->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001216 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001217 << "failed writing to '" << out_text_symbols_path.value()
1218 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001219 return false;
1220 }
1221 }
1222
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001223 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001224 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001225 context_->GetDiagnostics()->Error(android::DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001226 return false;
1227 }
1228
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 return true;
1230 }
1231
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001232 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001233 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001234 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1235 std::vector<std::string> packages_to_callback;
1236
1237 JavaClassGeneratorOptions template_options;
1238 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1239 template_options.javadoc_annotations = options_.javadoc_annotations;
1240
1241 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1242 template_options.use_final = false;
1243 }
1244
1245 if (context_->GetPackageType() == PackageType::kSharedLib) {
1246 template_options.use_final = false;
1247 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1248 }
1249
1250 const StringPiece actual_package = context_->GetCompilationPackage();
1251 StringPiece output_package = context_->GetCompilationPackage();
1252 if (options_.custom_java_package) {
1253 // Override the output java package to the custom one.
1254 output_package = options_.custom_java_package.value();
1255 }
1256
1257 // Generate the private symbols if required.
1258 if (options_.private_symbols) {
1259 packages_to_callback.push_back(options_.private_symbols.value());
1260
1261 // If we defined a private symbols package, we only emit Public symbols
1262 // to the original package, and private and public symbols to the private package.
1263 JavaClassGeneratorOptions options = template_options;
1264 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1265 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1266 options)) {
1267 return false;
1268 }
1269 }
1270
1271 // Generate copies of the original package R class but with different package names.
1272 // This is to support non-namespaced builds.
1273 for (const std::string& extra_package : options_.extra_java_packages) {
1274 packages_to_callback.push_back(extra_package);
1275
1276 JavaClassGeneratorOptions options = template_options;
1277 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1278 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1279 return false;
1280 }
1281 }
1282
1283 // Generate R classes for each package that was merged (static library).
1284 // Use the actual package's resources only.
1285 for (const std::string& package : table_merger_->merged_packages()) {
1286 packages_to_callback.push_back(package);
1287
1288 JavaClassGeneratorOptions options = template_options;
1289 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1290 if (!WriteJavaFile(&final_table_, package, package, options)) {
1291 return false;
1292 }
1293 }
1294
1295 // Generate the main public R class.
1296 JavaClassGeneratorOptions options = template_options;
1297
1298 // Only generate public symbols if we have a private package.
1299 if (options_.private_symbols) {
1300 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1301 }
1302
1303 if (options.rewrite_callback_options) {
1304 options.rewrite_callback_options.value().packages_to_callback =
1305 std::move(packages_to_callback);
1306 }
1307
1308 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1309 options_.generate_text_symbols_path)) {
1310 return false;
1311 }
1312
1313 return true;
1314 }
1315
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001316 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001317 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001318 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 return true;
1320 }
1321
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001322 std::unique_ptr<ClassDefinition> manifest_class =
1323 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001325 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001326 // Something bad happened, but we already logged it, so exit.
1327 return false;
1328 }
1329
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001330 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001331 // Empty Manifest class, no need to generate it.
1332 return true;
1333 }
1334
1335 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001336 for (const std::string& annotation : options_.javadoc_annotations) {
1337 std::string proper_annotation = "@";
1338 proper_annotation += annotation;
1339 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340 }
1341
Adam Lesinski0d81f702017-06-27 15:51:09 -07001342 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001343 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001345 std::string out_path = options_.generate_java_class_path.value();
1346 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001347
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001348 if (!file::mkdirs(out_path)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001349 context_->GetDiagnostics()->Error(android::DiagMessage()
1350 << "failed to create directory '" << out_path << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351 return false;
1352 }
1353
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001355
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001356 io::FileOutputStream fout(out_path);
1357 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001358 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1359 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001360 return false;
1361 }
1362
Makoto Onukide6e6f22020-06-22 10:17:02 -07001363 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1364 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001365 fout.Flush();
1366
1367 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001368 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1369 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370 return false;
1371 }
1372 return true;
1373 }
1374
Ryan Mitchell4382e442021-07-14 12:53:01 -07001375 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001376 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001377 if (!out) {
1378 return true;
1379 }
1380
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001381 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001382 io::FileOutputStream fout(out_path);
1383 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001384 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to open '" << out_path
1385 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001386 return false;
1387 }
1388
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001389 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1390 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001391 fout.Flush();
1392
1393 if (fout.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001394 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed writing to '" << out_path
1395 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001396 return false;
1397 }
1398 return true;
1399 }
1400
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001401 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001402 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001403 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001404 context_->GetDiagnostics()->Note(android::DiagMessage()
1405 << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001406 }
1407
Adam Lesinski8780eb62017-10-31 17:44:39 -07001408 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1409 if (apk == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001410 context_->GetDiagnostics()->Error(android::DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 return false;
1412 }
1413
Adam Lesinski8780eb62017-10-31 17:44:39 -07001414 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001415 if (table->packages.empty()) {
1416 return true;
1417 }
1418
1419 auto lib_package_result = GetStaticLibraryPackage(table);
1420 if (!lib_package_result.has_value()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001421 context_->GetDiagnostics()->Error(android::DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 return false;
1423 }
1424
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001425 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001426 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001427 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001428 // Merge all resources as if they were in the compilation package. This is the old behavior
1429 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001430
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001431 // Add the package to the set of --extra-packages so we emit an R.java for each library
1432 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001433 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001434 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001435 }
1436
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001437 // Clear the package name, so as to make the resources look like they are coming from the
1438 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001439 pkg->name = "";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001440 result = table_merger_->Merge(android::Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001441
1442 } else {
1443 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001444 // preserved and resource names are mangled.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001445 result = table_merger_->MergeAndMangle(android::Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001446 }
1447
1448 if (!result) {
1449 return false;
1450 }
1451
1452 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001453 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001454 return true;
1455 }
1456
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001457 bool MergeExportedSymbols(const android::Source& source,
Adam Lesinski2427dce2017-11-30 15:10:28 -08001458 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001459 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001460 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001461 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001462 ResourceName res_name = exported_symbol.name;
1463 if (res_name.package.empty()) {
1464 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465 }
1466
Ryan Mitchell4382e442021-07-14 12:53:01 -07001467 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001468 if (mangled_name) {
1469 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001470 }
1471
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001472 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001473 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001474 bool result = final_table_.AddResource(
1475 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1476 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001477 if (!result) {
1478 return false;
1479 }
1480 }
1481 return true;
1482 }
1483
Adam Lesinski2427dce2017-11-30 15:10:28 -08001484 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001485 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001486 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001487 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski2427dce2017-11-30 15:10:28 -08001488 << "merging '" << compiled_file.name
1489 << "' from compiled file " << compiled_file.source);
1490 }
1491
1492 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1493 return false;
1494 }
1495 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1496 }
1497
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001498 // 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 -07001499 // If override is true, conflicting resources are allowed to override each other, in order of last
1500 // seen.
1501 // An io::IFileCollection is created from the ZIP file and added to the set of
1502 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001503 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001504 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001505 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001506 context_->GetDiagnostics()->Note(android::DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001507 }
1508
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001509 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001510 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001511 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001512 if (!collection) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001513 context_->GetDiagnostics()->Error(android::DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001514 return false;
1515 }
1516
1517 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001518 for (auto iter = collection->Iterator(); iter->HasNext();) {
1519 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001520 error = true;
1521 }
1522 }
1523
1524 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001525 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001526 return !error;
1527 }
1528
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001529 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001530 // conflicting resources are allowed to override each other, in order of last seen.
1531 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1532 // as ZIP archive and the files within are merged individually.
1533 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001534 bool MergePath(const std::string& path, bool override) {
1535 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1536 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1537 return MergeArchive(path, override);
1538 } else if (util::EndsWith(path, ".apk")) {
1539 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540 }
1541
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 io::IFile* file = file_collection_->InsertFile(path);
1543 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001544 }
1545
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001546 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001547 // If override is true, conflicting resources are allowed to override each other, in order of last
1548 // seen.
1549 // All other file types are ignored. This is because these files could be coming from a zip,
1550 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001551 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001552 TRACE_CALL();
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001553 const android::Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001554
Adam Lesinski00451162017-10-03 07:44:08 -07001555 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001556 // Since AAPT compiles these file types and appends .flat to them, seeing
1557 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001558 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001559 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1560 << "uncompiled " << file_type
1561 << " file passed as argument. Must be "
1562 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001563 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001564 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1565 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001566 context_->GetDiagnostics()->Warn(android::DiagMessage(src) << "ignoring unrecognized file");
Adam Lesinski00451162017-10-03 07:44:08 -07001567 return true;
1568 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001569 }
1570
Adam Lesinski00451162017-10-03 07:44:08 -07001571 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1572 if (input_stream == nullptr) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001573 context_->GetDiagnostics()->Error(android::DiagMessage(src) << "failed to open file");
Adam Lesinski00451162017-10-03 07:44:08 -07001574 return false;
1575 }
1576
1577 if (input_stream->HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001578 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001579 << "failed to open file: " << input_stream->GetError());
1580 return false;
1581 }
1582
1583 ContainerReaderEntry* entry;
1584 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001585
1586 if (reader.HadError()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001587 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Mohamed Heikal10844322018-02-07 15:17:38 -05001588 << "failed to read file: " << reader.GetError());
1589 return false;
1590 }
1591
Adam Lesinski00451162017-10-03 07:44:08 -07001592 while ((entry = reader.Next()) != nullptr) {
1593 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001594 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001595 pb::ResourceTable pb_table;
1596 if (!entry->GetResTable(&pb_table)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001597 context_->GetDiagnostics()->Error(
1598 android::DiagMessage(src) << "failed to read resource table: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001599 return false;
1600 }
1601
1602 ResourceTable table;
1603 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001604 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001605 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001606 << "failed to deserialize resource table: " << error);
1607 return false;
1608 }
1609
1610 if (!table_merger_->Merge(src, &table, override)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001611 context_->GetDiagnostics()->Error(android::DiagMessage(src)
1612 << "failed to merge resource table");
Adam Lesinski00451162017-10-03 07:44:08 -07001613 return false;
1614 }
1615 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001616 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001617 pb::internal::CompiledFile pb_compiled_file;
1618 off64_t offset;
1619 size_t len;
1620 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001621 context_->GetDiagnostics()->Error(
1622 android::DiagMessage(src) << "failed to get resource file: " << entry->GetError());
Adam Lesinski00451162017-10-03 07:44:08 -07001623 return false;
1624 }
1625
1626 ResourceFile resource_file;
1627 std::string error;
1628 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001629 context_->GetDiagnostics()->Error(android::DiagMessage(src)
Adam Lesinski00451162017-10-03 07:44:08 -07001630 << "failed to read compiled header: " << error);
1631 return false;
1632 }
1633
1634 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1635 return false;
1636 }
1637 }
1638 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001639 return true;
1640 }
1641
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001642 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1643 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1644 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001645 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001646 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1647 if (!files) {
1648 return false;
1649 }
1650
1651 for (const std::string& file : files.value()) {
1652 std::string full_key = "assets/" + file;
1653 std::string full_path = assets_dir;
1654 file::AppendPath(&full_path, file);
1655
1656 auto iter = merged_assets.find(full_key);
1657 if (iter == merged_assets.end()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001658 merged_assets.emplace(std::move(full_key), util::make_unique<io::RegularFile>(
1659 android::Source(std::move(full_path))));
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001660 } else if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001661 context_->GetDiagnostics()->Warn(android::DiagMessage(iter->second->GetSource())
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001662 << "asset file overrides '" << full_path << "'");
1663 }
1664 }
1665 }
1666
1667 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001668 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001669 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1670 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001671 return false;
1672 }
1673 }
1674 return true;
1675 }
1676
Rhed Jao2c434422020-11-12 10:48:03 +08001677 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1678 Reference* reference) {
1679 if (!reference || !reference->name) {
1680 return nullptr;
1681 }
1682 auto name_ref = ResourceNameRef(reference->name.value());
1683 if (name_ref.package.empty()) {
1684 name_ref.package = context->GetCompilationPackage();
1685 }
1686 const auto search_result = table->FindResource(name_ref);
1687 if (!search_result) {
1688 return nullptr;
1689 }
1690 return search_result.value().entry;
1691 }
1692
Ryan Mitchelldba64562019-06-07 17:07:37 -07001693 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001694 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001695 if (!application) {
1696 return;
1697 }
1698
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001699 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1700 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001701 if (!icon || !round_icon) {
1702 return;
1703 }
1704
1705 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001706 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001707 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1708 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001709 return;
1710 }
1711
1712 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001713 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001714 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1715 ? config_value->config.sdkVersion : icon_max_sdk;
1716 }
1717 if (icon_max_sdk < SDK_O) {
1718 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1719 return;
1720 }
1721
1722 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001723 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001724 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1725 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001726 return;
1727 }
1728
1729 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001730 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001731 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1732 ? config_value->config.sdkVersion : round_icon_max_sdk;
1733 }
1734 if (round_icon_max_sdk >= SDK_O) {
1735 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1736 // not generate an alias to the icon drawable.
1737 return;
1738 }
1739
1740 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001741 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001742 if (config_value->config.sdkVersion < SDK_O) {
1743 continue;
1744 }
1745
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001746 context_->GetDiagnostics()->Note(android::DiagMessage()
1747 << "generating " << round_icon_reference->name.value()
1748 << " with config \"" << config_value->config
1749 << "\" for round icon compatibility");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001750
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001751 CloningValueTransformer cloner(&table->string_pool);
1752 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001753 auto round_config_value =
1754 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001755 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001756 }
1757 }
1758
Rhed Jao2c434422020-11-12 10:48:03 +08001759 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1760 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1761 if (manifest_el == nullptr) {
1762 return true;
1763 }
1764 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1765 return true;
1766 }
1767 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1768 if (!attr) {
1769 return true;
1770 }
1771 const auto validate = [&](const std::string& shared_user_id) -> bool {
1772 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1773 return true;
1774 }
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001775 android::DiagMessage error_msg(manifest_el->line_number);
Rhed Jao2c434422020-11-12 10:48:03 +08001776 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1777 << shared_user_id << "'";
1778 if (options_.manifest_fixer_options.warn_validation) {
1779 // Treat the error only as a warning.
1780 context_->GetDiagnostics()->Warn(error_msg);
1781 return true;
1782 }
1783 context_->GetDiagnostics()->Error(error_msg);
1784 return false;
1785 };
1786 // If attr->compiled_value is not null, check if it is a ref
1787 if (attr->compiled_value) {
1788 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1789 if (ref == nullptr) {
1790 return true;
1791 }
1792 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1793 if (!shared_user_id_entry) {
1794 return true;
1795 }
1796 for (const auto& value : shared_user_id_entry->values) {
1797 const auto str_value = ValueCast<String>(value->value.get());
1798 if (str_value != nullptr && !validate(*str_value->value)) {
1799 return false;
1800 }
1801 }
1802 return true;
1803 }
1804
1805 // Fallback to checking the raw value
1806 return validate(attr->value);
1807 }
1808
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001809 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1810 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001811 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1812 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001813 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001814 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1815 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001816 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001817 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001818 if (!result) {
1819 return false;
1820 }
1821
Ryan Mitchelldba64562019-06-07 17:07:37 -07001822 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1823 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1824 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1825 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1826 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1827 // See (b/34829129)
1828 AliasAdaptiveIcon(manifest, table);
1829
Rhed Jao2c434422020-11-12 10:48:03 +08001830 // Verify the shared user id here to handle the case of reference value.
1831 if (!VerifySharedUserId(manifest, table)) {
1832 return false;
1833 }
1834
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001835 ResourceFileFlattenerOptions file_flattener_options;
1836 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001837 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1838 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001839 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 file_flattener_options.no_auto_version = options_.no_auto_version;
1841 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001842 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001843 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1844 file_flattener_options.update_proguard_spec =
1845 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001846 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001847 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001849 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001850 if (!file_flattener.Flatten(table, writer)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001851 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852 return false;
1853 }
1854
Adam Lesinski490595a2017-11-07 17:08:07 -08001855 // Hack to fix b/68820737.
1856 // We need to modify the ResourceTable's package name, but that should NOT affect
1857 // anything else being generated, which includes the Java classes.
1858 // If required, the package name is modifed before flattening, and then modified back
1859 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001860 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001861 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1862 // or higher] as invalid. In order to work around this limitation, we allow the use
1863 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1864 // definition of what a valid "split" package ID is to account for this.
1865 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1866 context_->GetPackageId() != kAppPackageId &&
1867 context_->GetPackageId() != kFrameworkPackageId)
1868 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001869 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001870 // The base APK is included, and this is a feature split. If the base package is
1871 // the same as this package, then we are building an old style Android Instant Apps feature
1872 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001873 if (!table->packages.empty() &&
1874 table->packages.back()->name == context_->GetCompilationPackage()) {
1875 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001876 std::string new_package_name =
1877 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001878 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001879
1880 if (context_->IsVerbose()) {
1881 context_->GetDiagnostics()->Note(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001882 android::DiagMessage() << "rewriting resource package name for feature split to '"
1883 << new_package_name << "'");
Adam Lesinski490595a2017-11-07 17:08:07 -08001884 }
1885 package_to_rewrite->name = new_package_name;
1886 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001887 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001888
1889 bool success = FlattenTable(table, options_.output_format, writer);
1890
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001891 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001892 // Change the name back.
1893 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001894
1895 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1896 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1897 // library, do not include a mapping from the feature package name to the feature package id
1898 // in the feature's dynamic reference table.
1899 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001900 }
1901
1902 if (!success) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001903 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to write resource table");
Adam Lesinski490595a2017-11-07 17:08:07 -08001904 }
1905 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906 }
1907
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001909 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001910 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 std::unique_ptr<xml::XmlResource> manifest_xml =
1912 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1913 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 return 1;
1915 }
1916
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001917 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001918 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001919 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 const AppInfo& app_info = maybe_app_info.value();
1921 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922 }
1923
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001924 // Determine the package name under which to merge resources.
1925 if (options_.rename_resources_package) {
1926 if (!options_.custom_java_package) {
1927 // Generate the R.java under the original package name instead of the package name specified
1928 // through --rename-resources-package.
1929 options_.custom_java_package = context_->GetCompilationPackage();
1930 }
1931 context_->SetCompilationPackage(options_.rename_resources_package.value());
1932 }
1933
Adam Lesinskic6284372017-12-04 13:46:23 -08001934 // Now that the compilation package is set, load the dependencies. This will also extract
1935 // the Android framework's versionCode and versionName, if they exist.
1936 if (!LoadSymbolsFromIncludePaths()) {
1937 return 1;
1938 }
1939
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1941 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001942 return 1;
1943 }
1944
Ryan Mitchell4382e442021-07-14 12:53:01 -07001945 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001946 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001947 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 return 1;
1949 }
1950
Adam Lesinski490595a2017-11-07 17:08:07 -08001951 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001952 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001954 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001955 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001956
1957 // Override the package ID when it is "android".
1958 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001959 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001960
1961 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001962 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001963 context_->GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001964 android::DiagMessage() << "package 'android' can only be built as a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001965 return 1;
1966 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 }
1968
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001969 TableMergerOptions table_merger_options;
1970 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001971 table_merger_options.override_styles_instead_of_overlaying =
1972 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001973 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001974 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001976 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001977 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001978 << StringPrintf("linking package '%s' using package ID %02x",
1979 context_->GetCompilationPackage().data(),
1980 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001981 }
1982
Adam Lesinski2427dce2017-11-30 15:10:28 -08001983 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1984 // in res/**/*.
1985 {
1986 XmlIdCollector collector;
1987 if (!collector.Consume(context_, manifest_xml.get())) {
1988 return false;
1989 }
1990
1991 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1992 return false;
1993 }
1994 }
1995
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 for (const std::string& input : input_files) {
1997 if (!MergePath(input, false)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00001998 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001999 return 1;
2000 }
2001 }
2002
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002003 for (const std::string& input : options_.overlay_files) {
2004 if (!MergePath(input, true)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002005 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006 return 1;
2007 }
2008 }
2009
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 return 1;
2012 }
2013
Adam Lesinskib522f042017-04-21 16:57:59 -07002014 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002015 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002016 if (context_->GetPackageId() == kAndroidPackageId &&
2017 !mover.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002018 context_->GetDiagnostics()->Error(android::DiagMessage()
2019 << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002020 return 1;
2021 }
2022
2023 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 IdAssigner id_assigner(&options_.stable_id_map);
2025 if (!id_assigner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002026 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002027 return 1;
2028 }
2029
2030 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002031 if (options_.resource_id_map_path) {
2032 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002033 for (auto& type : package->types) {
2034 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002035 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002037 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002038 }
2039 }
2040 }
2041
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002042 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002043 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002044 return 1;
2045 }
2046 }
2047 } else {
2048 // Static libs are merged with other apps, and ID collisions are bad, so
2049 // verify that
2050 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002051 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002052 return 1;
2053 }
2054 }
2055
2056 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002057 context_->SetNameManglerPolicy(
2058 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059
2060 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002061 context_->GetExternalSymbols()->PrependSource(
2062 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002063
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002064 // Workaround for pre-O runtime that would treat negative resource IDs
2065 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2066 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2067 // are just identifiers.
2068 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2069 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002070 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002071 << "enabling pre-O feature split ID rewriting");
2072 }
2073 context_->GetExternalSymbols()->SetDelegate(
2074 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2075 }
2076
Adam Lesinski34a16872018-02-23 16:18:10 -08002077 // Before we process anything, remove the resources whose default values don't exist.
2078 // We want to force any references to these to fail the build.
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002079 if (!options_.no_resource_removal) {
2080 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002081 context_->GetDiagnostics()->Error(android::DiagMessage()
MÃ¥rten Kongstadd8d29012018-06-11 14:13:37 +02002082 << "failed removing resources with no defaults");
2083 return 1;
2084 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002085 }
2086
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002088 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002089 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002090 return 1;
2091 }
2092
Adam Lesinskib522f042017-04-21 16:57:59 -07002093 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 if (!options_.products.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002095 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002096 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002097 }
2098 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 ProductFilter product_filter(options_.products);
2100 if (!product_filter.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002101 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 return 1;
2103 }
2104 }
2105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002108 if (!versioner.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002109 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002110 return 1;
2111 }
2112 }
2113
Adam Lesinskib522f042017-04-21 16:57:59 -07002114 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002115 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002116 context_->GetDiagnostics()->Note(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002117 << "collapsing resource versions for minimum SDK "
2118 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 }
2120
2121 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002122 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 return 1;
2124 }
2125 }
2126
Winson3c918b82019-01-25 14:25:37 -08002127 if (!options_.exclude_configs_.empty()) {
2128 std::vector<ConfigDescription> excluded_configs;
2129
2130 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002131 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002132 ConfigDescription config_description;
2133
2134 if (!ConfigDescription::Parse(config_string, &config_description)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002135 context_->GetDiagnostics()->Error(
2136 android::DiagMessage() << "failed to parse --excluded-configs " << config_string);
Winson3c918b82019-01-25 14:25:37 -08002137 return 1;
2138 }
2139
2140 excluded_configs.push_back(config_description);
2141 }
2142
2143 ResourceExcluder excluder(excluded_configs);
2144 if (!excluder.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002145 context_->GetDiagnostics()->Error(android::DiagMessage()
2146 << "failed excluding configurations");
Winson3c918b82019-01-25 14:25:37 -08002147 return 1;
2148 }
2149 }
2150
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002151 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002152 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 if (!deduper.Consume(context_, &final_table_)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002154 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 return 1;
2156 }
2157 }
2158
Adam Koskidc21dea2017-07-21 10:55:27 -07002159 proguard::KeepSet proguard_keep_set =
2160 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002161 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002162
Adam Lesinskib522f042017-04-21 16:57:59 -07002163 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002165 !options_.table_splitter_options.preferred_densities.empty()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002166 context_->GetDiagnostics()->Warn(android::DiagMessage()
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002167 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 }
2169 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002170 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2171 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002172 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002173 options_.split_constraints =
2174 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002175
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002176 if (origConstraintSize != options_.split_constraints.size()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002177 context_->GetDiagnostics()->Warn(android::DiagMessage()
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002178 << "requested to split resources prior to min sdk of "
2179 << context_->GetMinSdkVersion());
2180 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002181 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002182 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002183 return 1;
2184 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002185 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186
2187 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002188 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002189 auto split_constraints_iter = options_.split_constraints.begin();
2190 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002191 if (context_->IsVerbose()) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002192 context_->GetDiagnostics()->Note(android::DiagMessage(*path_iter)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002193 << "generating split with configurations '"
2194 << util::Joiner(split_constraints_iter->configs, ", ")
2195 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002196 }
2197
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002198 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002199 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002200 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201 return 1;
2202 }
2203
2204 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002205 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002206 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002207
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002208 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002209 if (!linker.Consume(context_, split_manifest.get())) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002210 context_->GetDiagnostics()->Error(android::DiagMessage()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002211 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212 return 1;
2213 }
2214
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002215 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2216 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002217 return 1;
2218 }
2219
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002220 ++path_iter;
2221 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222 }
2223 }
2224
2225 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002226 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002227 if (!archive_writer) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002228 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002229 return 1;
2230 }
2231
2232 bool error = false;
2233 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002234 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002235 // (aka, which package the AndroidManifest.xml is coming from).
2236 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002237 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002238
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002239 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002240 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002241 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002242 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002243 error = true;
2244 }
2245
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002246 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002247 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002248 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002249 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002250 }
2251
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002252 if (options_.generate_java_class_path) {
2253 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002254 error = true;
2255 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002256 }
2257
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002258 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002259 // PackageParser will fail if URIs are removed from
2260 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002261 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2262 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002263 error = true;
2264 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002265 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 } else {
2267 error = true;
2268 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002269 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002270
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271 if (error) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002272 context_->GetDiagnostics()->Error(android::DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002273 return 1;
2274 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002275
Josh Houd3bd4522022-02-14 10:24:42 +08002276 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2277 return 1;
2278 };
2279
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002280 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2281 return 1;
2282 }
2283
2284 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002285 return 1;
2286 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002287
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002288 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002289 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002290 return 1;
2291 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002292 }
2293
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002294 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002295 return 1;
2296 }
2297
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002298 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2299 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002300 return 1;
2301 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002302 return 0;
2303 }
2304
2305 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002306 LinkOptions options_;
2307 LinkContext* context_;
2308 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002309
Adam Lesinski490595a2017-11-07 17:08:07 -08002310 AppInfo app_info_;
2311
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002312 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002313
2314 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002315 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002316
Adam Lesinski8780eb62017-10-31 17:44:39 -07002317 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002318 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002319 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002320
Adam Lesinski8780eb62017-10-31 17:44:39 -07002321 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2322 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2323
2324 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2325 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002326
2327 // The set of shared libraries being used, mapping their assigned package ID to package name.
2328 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002329
2330 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002331 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002332};
2333
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002334int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002335 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002336 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002337
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002338 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002339 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002340 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002341 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002342 const std::string path = arg.substr(1, arg.size() - 1);
2343 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002344 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002345 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002346 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002347 }
2348 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002349 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002350 }
2351 }
2352
2353 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002354 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002355 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002356 const std::string path = arg.substr(1, arg.size() - 1);
2357 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002358 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002359 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002360 return 1;
2361 }
2362 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002363 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002364 }
2365 }
2366
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002367 if (verbose_) {
2368 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002369 }
2370
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002371 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002372 context.GetDiagnostics()
2373 ->Error(android::DiagMessage()
2374 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002375 return 1;
2376 }
2377
Ryan Mitchell5855de72021-02-24 14:39:13 -08002378 if (shared_lib_ && options_.private_symbols) {
2379 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2380 // reference the private attribute within the styleable array will cause a link error because
2381 // the private attribute will not be emitted in the public R.java.
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002382 context.GetDiagnostics()->Error(android::DiagMessage()
Ryan Mitchell5855de72021-02-24 14:39:13 -08002383 << "--shared-lib cannot currently be used in combination with"
2384 << " --private-symbols");
2385 return 1;
2386 }
2387
Izabela Orlowska84febea2019-06-03 18:34:12 +01002388 if (options_.merge_only && !static_lib_) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002389 context.GetDiagnostics()
2390 ->Error(android::DiagMessage()
2391 << "the --merge-only flag can be only used when building a static library");
Izabela Orlowska84febea2019-06-03 18:34:12 +01002392 return 1;
2393 }
2394
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002395 // The default build type.
2396 context.SetPackageType(PackageType::kApp);
2397 context.SetPackageId(kAppPackageId);
2398
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002399 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002400 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002401 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002402 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002403 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002404 options_.output_format = OutputFormat::kProto;
2405 } else if (proto_format_) {
2406 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002407 }
2408
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002409 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002410 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002411 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002412 android::DiagMessage() << "can't specify --package-id when not building a regular app");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002413 return 1;
2414 }
2415
Ryan Mitchell4382e442021-07-14 12:53:01 -07002416 const std::optional<uint32_t> maybe_package_id_int =
2417 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002418 if (!maybe_package_id_int) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002419 context.GetDiagnostics()->Error(android::DiagMessage()
2420 << "package ID '" << package_id_.value()
2421 << "' is not a valid integer");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002422 return 1;
2423 }
2424
2425 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002426 if (package_id_int > std::numeric_limits<uint8_t>::max()
2427 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002428 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002429 context.GetDiagnostics()->Error(
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002430 android::DiagMessage() << StringPrintf(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002431 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2432 return 1;
2433 }
2434 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2435 }
2436
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002437 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002438 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002439 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002440 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002441 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002442 }
2443 }
2444
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002445 if (product_list_) {
2446 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002447 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002448 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002449 }
2450 }
2451 }
2452
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002453 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002454 if (!configs_.empty()) {
2455 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002456 if (filter == nullptr) {
2457 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002458 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002459 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002460 }
2461
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002462 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002463 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002464 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002465 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002466 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002467 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002468 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002469 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002470
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002471 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002472 for (const std::string& split_arg : split_args_) {
2473 options_.split_paths.push_back({});
2474 options_.split_constraints.push_back({});
2475 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2476 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002477 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002478 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002479 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002480
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002481 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2482 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2483 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002484 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002485 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002486 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002487
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002488 if (no_compress_regex) {
2489 std::string regex = no_compress_regex.value();
2490 if (util::StartsWith(regex, "@")) {
2491 const std::string path = regex.substr(1, regex.size() -1);
2492 std::string error;
2493 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
Jeremy Meyer56f36e82022-05-20 20:35:42 +00002494 context.GetDiagnostics()->Error(android::DiagMessage(path) << error);
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002495 return 1;
2496 }
2497 } else {
2498 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2499 }
2500 }
2501
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002502 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002503 options_.extensions_to_not_compress.insert({
2504 // Image extensions
2505 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2506 // Audio extensions
2507 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2508 ".xmf", ".amr", ".awb",
2509 // Audio/video extensions
2510 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2511 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002512
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002513 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002514 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002515 options_.no_auto_version = true;
2516 options_.no_version_vectors = true;
2517 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002518 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002519
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002520 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002521 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002522}
2523
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002524} // namespace aapt