blob: bd74cc7be350919f6453c99966b737ba0f87a260 [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>
Adam Lesinskic6284372017-12-04 13:46:23 -080020#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050022#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
27#include "android-base/errors.h"
Ryan Mitchell9634efb2021-03-19 14:53:17 -070028#include "android-base/expected.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070029#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080030#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020031#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080032#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070033
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "AppInfo.h"
35#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070036#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080038#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070039#include "ResourceValues.h"
40#include "ValueVisitor.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:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800101 explicit LinkContext(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
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700113 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;
Chris Warrington820d72a2017-04-27 15:27:01 +0100173 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.
219 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
220 << " for pre-O feature split support");
221 return {};
222 }
223
224 if (context_->IsVerbose()) {
225 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
226 << ") -> (" << rewritten_id << ")");
227 }
228
229 *id = rewritten_id;
230 }
231 }
232 return symbol;
233 }
234
235 private:
236 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
237
238 IAaptContext* context_;
239};
240
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700241static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
242 const StringPiece& path, bool keep_raw_values, bool utf16,
243 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800244 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700245 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700246 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
247 << (keep_raw_values ? "true" : "false")
248 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700249 }
250
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700251 switch (format) {
252 case OutputFormat::kApk: {
253 BigBuffer buffer(1024);
254 XmlFlattenerOptions options = {};
255 options.keep_raw_values = keep_raw_values;
256 options.use_utf16 = utf16;
257 XmlFlattener flattener(&buffer, options);
258 if (!flattener.Consume(context, &xml_res)) {
259 return false;
260 }
261
262 io::BigBufferInputStream input_stream(&buffer);
263 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
264 ArchiveEntry::kCompress, writer);
265 } break;
266
267 case OutputFormat::kProto: {
268 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800269 // Strip whitespace text nodes from tha AndroidManifest.xml
270 SerializeXmlOptions options;
271 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700272 SerializeXmlResourceToPb(xml_res, &pb_node);
273 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
274 writer);
275 } break;
276 }
277 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800278}
279
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700280// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700281static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800282 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700283 FileInputStream fin(path);
284 if (fin.HadError()) {
285 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700286 return {};
287 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700288 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800289}
290
Adam Lesinski355f2852016-02-13 20:26:45 -0800291struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700292 bool no_auto_version = false;
293 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900294 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700295 bool no_xml_namespaces = false;
296 bool keep_raw_values = false;
297 bool do_not_compress_anything = false;
298 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100299 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700300 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700301 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700302 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800303};
304
Adam Lesinskic744ae82017-05-17 19:28:38 -0700305// A sampling of public framework resource IDs.
306struct R {
307 struct attr {
308 enum : uint32_t {
309 paddingLeft = 0x010100d6u,
310 paddingRight = 0x010100d8u,
311 paddingHorizontal = 0x0101053du,
312
313 paddingTop = 0x010100d7u,
314 paddingBottom = 0x010100d9u,
315 paddingVertical = 0x0101053eu,
316
317 layout_marginLeft = 0x010100f7u,
318 layout_marginRight = 0x010100f9u,
319 layout_marginHorizontal = 0x0101053bu,
320
321 layout_marginTop = 0x010100f8u,
322 layout_marginBottom = 0x010100fau,
323 layout_marginVertical = 0x0101053cu,
324 };
325 };
326};
327
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700328template <typename T>
329uint32_t GetCompressionFlags(const StringPiece& str, T options) {
330 if (options.do_not_compress_anything) {
331 return 0;
332 }
333
334 if (options.regex_to_not_compress
335 && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) {
336 return 0;
337 }
338
339 for (const std::string& extension : options.extensions_to_not_compress) {
340 if (util::EndsWith(str, extension)) {
341 return 0;
342 }
343 }
344 return ArchiveEntry::kCompress;
345}
346
Adam Lesinski355f2852016-02-13 20:26:45 -0800347class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700349 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700350 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800351
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800353
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 private:
355 struct FileOperation {
356 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700359 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700362 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskic744ae82017-05-17 19:28:38 -0700371 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
372 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800373
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700374 ResourceFileFlattenerOptions options_;
375 IAaptContext* context_;
376 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700377 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800378};
379
Adam Lesinskic744ae82017-05-17 19:28:38 -0700380ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
381 IAaptContext* context, proguard::KeepSet* keep_set)
382 : options_(options), context_(context), keep_set_(keep_set) {
383 SymbolTable* symm = context_->GetExternalSymbols();
384
385 // Build up the rules for degrading newer attributes to older ones.
386 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
387 // generated from the attribute definitions themselves (b/62028956).
388 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
389 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800390 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
391 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700392 };
393 rules_[R::attr::paddingHorizontal] =
394 util::make_unique<DegradeToManyRule>(std::move(replacements));
395 }
396
397 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
398 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800399 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
400 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700401 };
402 rules_[R::attr::paddingVertical] =
403 util::make_unique<DegradeToManyRule>(std::move(replacements));
404 }
405
406 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
407 std::vector<ReplacementAttr> replacements{
408 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800409 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700410 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800411 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 };
413 rules_[R::attr::layout_marginHorizontal] =
414 util::make_unique<DegradeToManyRule>(std::move(replacements));
415 }
416
417 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
418 std::vector<ReplacementAttr> replacements{
419 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800420 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700421 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800422 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 };
424 rules_[R::attr::layout_marginVertical] =
425 util::make_unique<DegradeToManyRule>(std::move(replacements));
426 }
427}
428
Adam Lesinskibb94f322017-07-12 07:41:55 -0700429static bool IsTransitionElement(const std::string& name) {
430 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
431 name == "changeImageTransform" || name == "changeTransform" ||
432 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
433 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
434 name == "transitionManager";
435}
436
437static bool IsVectorElement(const std::string& name) {
438 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800439 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
440 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700441}
442
Adam Lesinskic744ae82017-05-17 19:28:38 -0700443template <typename T>
444std::vector<T> make_singleton_vec(T&& val) {
445 std::vector<T> vec;
446 vec.emplace_back(std::forward<T>(val));
447 return vec;
448}
449
450std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
451 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800452 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700453 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700454 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700455
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700457 context_->GetDiagnostics()->Note(DiagMessage()
458 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700459 }
460
Adam Lesinski00451162017-10-03 07:44:08 -0700461 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
462 // that existing projects have out-of-date references which pass compilation.
463 xml::StripAndroidStudioAttributes(doc->root.get());
464
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700465 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100466 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700467 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700468 }
469
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700470 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700471 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700474 if (options_.no_xml_namespaces) {
475 XmlNamespaceRemover namespace_remover;
476 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700477 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800478 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700479 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800480
Adam Lesinskibb94f322017-07-12 07:41:55 -0700481 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700482 return make_singleton_vec(std::move(file_op->xml_to_flatten));
483 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700484
Adam Lesinskibb94f322017-07-12 07:41:55 -0700485 if (options_.no_version_vectors || options_.no_version_transitions) {
486 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700487 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700488 if (el && el->namespace_uri.empty()) {
489 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
490 (options_.no_version_transitions && IsTransitionElement(el->name))) {
491 return make_singleton_vec(std::move(file_op->xml_to_flatten));
492 }
493 }
494 }
495
Adam Lesinskic744ae82017-05-17 19:28:38 -0700496 const ConfigDescription& config = file_op->config;
497 ResourceEntry* entry = file_op->entry;
498
499 XmlCompatVersioner xml_compat_versioner(&rules_);
500 const util::Range<ApiVersion> api_range{config.sdkVersion,
501 FindNextApiVersionForConfig(entry, config)};
502 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800503}
504
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800505ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
506 switch (format) {
507 case OutputFormat::kApk:
508 return ResourceFile::Type::kBinaryXml;
509 case OutputFormat::kProto:
510 return ResourceFile::Type::kProtoXml;
511 }
512 LOG_ALWAYS_FATAL("unreachable");
513 return ResourceFile::Type::kUnknown;
514}
515
Ryan Mitchell70f79722018-08-13 07:37:24 -0700516static auto kDrawableVersions = std::map<std::string, ApiVersion>{
517 { "adaptive-icon" , SDK_O },
518};
519
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700520bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800521 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700523 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800524
Adam Koskidc21dea2017-07-21 10:55:27 -0700525 proguard::CollectResourceReferences(context_, table, keep_set_);
526
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700528 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
529
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700531 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700532 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700533 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800534
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 // Populate the queue with all files in the ResourceTable.
536 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700537 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700538 // WARNING! Do not insert or remove any resources while executing in this scope. It will
539 // corrupt the iteration order.
540
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700541 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700543 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700545
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700550 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 }
552
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700553 FileOperation file_op;
554 file_op.entry = entry.get();
555 file_op.dst_path = *file_ref->path;
556 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700557 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000559 if (type->named_type.type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700560 (file_ref->type == ResourceFile::Type::kBinaryXml ||
561 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700564 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 << "failed to open file");
566 return false;
567 }
568
Adam Lesinski00451162017-10-03 07:44:08 -0700569 if (file_ref->type == ResourceFile::Type::kProtoXml) {
570 pb::XmlNode pb_xml_node;
571 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
572 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700573 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700574 return false;
575 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576
Adam Lesinski00451162017-10-03 07:44:08 -0700577 std::string error;
578 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
579 if (file_op.xml_to_flatten == nullptr) {
580 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700581 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700582 return false;
583 }
584 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700585 std::string error_str;
586 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700587 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700588 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
589 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700590 return false;
591 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700592 }
593
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800594 // Update the type that this file will be written as.
595 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
596
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700597 file_op.xml_to_flatten->file.config = config_value->config;
598 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Iurii Makhnof0c5ff42022-02-22 13:31:02 +0000599 file_op.xml_to_flatten->file.name =
600 ResourceName(pkg->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700601 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700602
603 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
604 // else we end up copying the string in the std::make_pair() method,
605 // then creating a StringPiece from the copy, which would cause us
606 // to end up referencing garbage in the map.
607 const StringPiece entry_name(entry->name);
608 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
609 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700610 }
611 }
612
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700613 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700614 for (auto& map_entry : config_sorted_files) {
615 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700616 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700617
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700618 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700619 // Check minimum sdk versions supported for drawables
620 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
621 if (drawable_entry != kDrawableVersions.end()) {
622 if (drawable_entry->second > context_->GetMinSdkVersion()
623 && drawable_entry->second > config.sdkVersion) {
624 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
625 << "<" << drawable_entry->first << "> elements "
626 << "require a sdk version of at least "
627 << (int16_t) drawable_entry->second);
628 error = true;
629 continue;
630 }
631 }
632
Adam Lesinskic744ae82017-05-17 19:28:38 -0700633 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
634 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700635 if (versioned_docs.empty()) {
636 error = true;
637 continue;
638 }
639
Adam Lesinskic744ae82017-05-17 19:28:38 -0700640 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
641 std::string dst_path = file_op.dst_path;
642 if (doc->file.config != file_op.config) {
643 // Only add the new versioned configurations.
644 if (context_->IsVerbose()) {
645 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
646 << "auto-versioning resource from config '"
647 << config << "' -> '" << doc->file.config << "'");
648 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800650 const ResourceFile& file = doc->file;
651 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
652
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700653 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800654 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
655 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700656
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800657 // Update the output format of this XML file.
658 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700659 bool result = table->AddResource(NewResourceBuilder(file.name)
660 .SetValue(std::move(file_ref), file.config)
661 .SetAllowMangled(true)
662 .Build(),
663 context_->GetDiagnostics());
664 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700665 return false;
666 }
667 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700668
669 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
670 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700671 }
672 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700673 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700674 GetCompressionFlags(file_op.dst_path, options_),
675 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700676 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700678 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679 }
680 return !error;
681}
682
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700683static bool WriteStableIdMapToPath(IDiagnostics* diag,
684 const std::unordered_map<ResourceName, ResourceId>& id_map,
685 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800686 io::FileOutputStream fout(id_map_path);
687 if (fout.HadError()) {
688 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700689 return false;
690 }
691
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800692 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700693 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694 const ResourceName& name = entry.first;
695 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800696 printer.Print(name.to_string());
697 printer.Print(" = ");
698 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800700 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800702 if (fout.HadError()) {
703 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704 return false;
705 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 return true;
707}
708
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700709static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
710 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700712 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700713 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700714 return false;
715 }
716
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700717 out_id_map->clear();
718 size_t line_no = 0;
719 for (StringPiece line : util::Tokenize(content, '\n')) {
720 line_no++;
721 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722 if (line.empty()) {
723 continue;
724 }
725
726 auto iter = std::find(line.begin(), line.end(), '=');
727 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700728 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700729 return false;
730 }
731
732 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700733 StringPiece res_name_str =
734 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
735 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700736 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
737 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700738 return false;
739 }
740
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700741 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
742 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700743 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700744
Ryan Mitchell4382e442021-07-14 12:53:01 -0700745 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700746 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700747 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
748 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700749 return false;
750 }
751
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700752 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700753 }
754 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700755}
756
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700757class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700758 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700759 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700760 : options_(options),
761 context_(context),
762 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700763 file_collection_(util::make_unique<io::FileCollection>()) {
764 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700765
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800766 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800767 using namespace android;
768
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000769 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
770 // we're looking for the first attribute resource in the system package.
771 android::ApkAssetsCookie cookie;
772 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
773 cookie = value->cookie;
774 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800775 // No Framework assets loaded. Not a failure.
776 return;
777 }
778
779 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800780 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800781 if (manifest == nullptr) {
782 // No errors.
783 return;
784 }
785
786 std::string error;
787 std::unique_ptr<xml::XmlResource> manifest_xml =
788 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
789 if (manifest_xml == nullptr) {
790 // No errors.
791 return;
792 }
793
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700794 if (!options_.manifest_fixer_options.compile_sdk_version) {
795 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
796 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700797 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700798 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
799 switch (prim->value.dataType) {
800 case Res_value::TYPE_INT_DEC:
801 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
802 break;
803 case Res_value::TYPE_INT_HEX:
804 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
805 break;
806 default:
807 break;
808 }
809 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
810 compile_sdk_version = *str->value;
811 } else {
812 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800813 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800814 }
815 }
816
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700817 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
818 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
819 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700820 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700821 options_.manifest_fixer_options.compile_sdk_version_codename;
822 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
823 compile_sdk_version_codename = *str->value;
824 } else {
825 compile_sdk_version_codename = attr->value;
826 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800827 }
828 }
829 }
830
Adam Lesinski8780eb62017-10-31 17:44:39 -0700831 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800832 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700833 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800834 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700835 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700836 for (const std::string& path : options_.include_paths) {
837 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700838 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700839 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700840
Adam Lesinski8780eb62017-10-31 17:44:39 -0700841 std::string error;
842 auto zip_collection = io::ZipFileCollection::Create(path, &error);
843 if (zip_collection == nullptr) {
844 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
845 return false;
846 }
847
848 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
849 // Load this as a static library include.
850 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
851 Source(path), std::move(zip_collection), context_->GetDiagnostics());
852 if (static_apk == nullptr) {
853 return false;
854 }
855
Adam Lesinskib522f042017-04-21 16:57:59 -0700856 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800857 // Can't include static libraries when not building a static library (they have no IDs
858 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700859 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800860 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700861 return false;
862 }
863
Adam Lesinski8780eb62017-10-31 17:44:39 -0700864 ResourceTable* table = static_apk->GetResourceTable();
865
866 // 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 -0700867 // our compilation package so the symbol package name does not get mangled into the entry
868 // name.
869 if (options_.no_static_lib_packages && !table->packages.empty()) {
870 auto lib_package_result = GetStaticLibraryPackage(table);
871 if (!lib_package_result.has_value()) {
872 context_->GetDiagnostics()->Error(DiagMessage(path) << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800873 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700874 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700875 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700876 }
877
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700878 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700879 util::make_unique<ResourceTableSymbolSource>(table));
880 static_library_includes_.push_back(std::move(static_apk));
881 } else {
882 if (!asset_source->AddAssetPath(path)) {
883 context_->GetDiagnostics()->Error(DiagMessage()
884 << "failed to load include path " << path);
885 return false;
886 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887 }
888 }
889
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800890 // Capture the shared libraries so that the final resource table can be properly flattened
891 // with support for shared libraries.
892 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700893 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800894 // Capture the included base feature package.
895 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800896 } else if (entry.first == kFrameworkPackageId) {
897 // Try to embed which version of the framework we're compiling against.
898 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
899 // when linking our synthesized 'android:compileSdkVersion' attribute.
900 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
901 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
902 if (symbol != nullptr && symbol->is_public) {
903 // The symbol is present and public, extract the android:versionName and
904 // android:versionCode from the framework AndroidManifest.xml.
905 ExtractCompileSdkVersions(asset_source->GetAssetManager());
906 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700907 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700908 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800909 }
910 }
911
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700912 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700913 return true;
914 }
915
Ryan Mitchell4382e442021-07-14 12:53:01 -0700916 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800917 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800919 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
920 if (manifest_el == nullptr) {
921 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700922 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800923
924 AppInfo app_info;
925
926 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
927 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
928 return {};
929 }
930
931 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
932 if (!package_attr) {
933 diag->Error(DiagMessage(xml_res->file.source)
934 << "<manifest> must have a 'package' attribute");
935 return {};
936 }
937 app_info.package = package_attr->value;
938
939 if (xml::Attribute* version_code_attr =
940 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700941 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800942 if (!maybe_code) {
943 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
944 << "invalid android:versionCode '" << version_code_attr->value << "'");
945 return {};
946 }
947 app_info.version_code = maybe_code.value();
948 }
949
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700950 if (xml::Attribute* version_code_major_attr =
951 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700952 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700953 if (!maybe_code) {
954 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
955 << "invalid android:versionCodeMajor '"
956 << version_code_major_attr->value << "'");
957 return {};
958 }
959 app_info.version_code_major = maybe_code.value();
960 }
961
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800962 if (xml::Attribute* revision_code_attr =
963 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700964 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800965 if (!maybe_code) {
966 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
967 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
968 return {};
969 }
970 app_info.revision_code = maybe_code.value();
971 }
972
973 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
974 if (!split_name_attr->value.empty()) {
975 app_info.split_name = split_name_attr->value;
976 }
977 }
978
979 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
980 if (xml::Attribute* min_sdk =
981 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700982 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800983 }
984 }
Udam Sainib228df32019-06-18 16:50:34 -0700985
986 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
987 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
988 if (const xml::Attribute* split_name =
989 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
990 if (!split_name->value.empty()) {
991 app_info.split_name_dependencies.insert(split_name->value);
992 }
993 }
994 }
995 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800996 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 }
998
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700999 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
1000 // Postcondition: ResourceTable has only one package left. All others are
1001 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001002 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001003 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001004 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001005 };
1006
1007 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001008 for (const auto& package : final_table_.packages) {
1009 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001010 // We have a package that is not related to the one we're building!
1011 for (const auto& type : package->types) {
1012 for (const auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001013 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001014
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001015 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001017 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001018 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1019 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1020 << "generated id '" << res_name
1021 << "' for external package '" << package->name
1022 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001024 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1025 << "defined resource '" << res_name
1026 << "' for external package '" << package->name
1027 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001028 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001030 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001031 }
1032 }
1033 }
1034 }
1035
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001036 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1037 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001038 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 return !error;
1040 }
1041
1042 /**
1043 * Returns true if no IDs have been set, false otherwise.
1044 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001045 bool VerifyNoIdsSet() {
1046 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001048 for (const auto& entry : type->entries) {
1049 if (entry->id) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00001050 ResourceNameRef res_name(package->name, type->named_type, entry->name);
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001051 context_->GetDiagnostics()->Error(DiagMessage() << "resource " << res_name << " has ID "
1052 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 return false;
1054 }
1055 }
1056 }
1057 }
1058 return true;
1059 }
1060
Josh Houd3bd4522022-02-14 10:24:42 +08001061 bool VerifyLocaleFormat(xml::XmlResource* manifest, IDiagnostics* diag) {
1062 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1063 // element.
1064 const xml::Element* application = manifest->root->FindChild("", "application");
1065 if (!application) {
1066 return true;
1067 }
1068 const xml::Attribute* localeConfig =
1069 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1070 if (!localeConfig) {
1071 return true;
1072 }
1073
1074 if (localeConfig->compiled_value) {
1075 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1076 const auto localeconfig_entry =
1077 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1078 if (!localeconfig_entry) {
1079 return true;
1080 }
1081
1082 for (const auto& value : localeconfig_entry->values) {
1083 // Load an XML file which is linked from the localeConfig attribute.
1084 const std::string& path = value->value->GetSource().path;
1085 std::unique_ptr<xml::XmlResource> localeConfig_xml = LoadXml(path, diag);
1086 if (!localeConfig_xml) {
1087 diag->Error(DiagMessage(path) << "can't load the XML");
1088 return false;
1089 }
1090
1091 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1092 if (!localeConfig_el) {
1093 diag->Error(DiagMessage(path) << "no root tag defined");
1094 return false;
1095 }
1096 if (localeConfig_el->name != "locale-config") {
1097 diag->Error(DiagMessage(path) << "invalid element name: " << localeConfig_el->name
1098 << ", expected: locale-config");
1099 return false;
1100 }
1101
1102 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1103 if (child_el->name == "locale") {
1104 if (const xml::Attribute* locale_name_attr =
1105 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1106 const std::string& locale_name = locale_name_attr->value;
1107 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1108
1109 // Start to verify the locale format
1110 ConfigDescription config;
1111 if (!ConfigDescription::Parse(valid_name, &config)) {
1112 diag->Error(DiagMessage(path) << "invalid configuration: " << locale_name);
1113 return false;
1114 }
1115 } else {
1116 diag->Error(DiagMessage(path) << "the attribute android:name is not found");
1117 return false;
1118 }
1119 } else {
1120 diag->Error(DiagMessage(path)
1121 << "invalid element name: " << child_el->name << ", expected: locale");
1122 return false;
1123 }
1124 }
1125 }
1126 }
1127 return true;
1128 }
1129
1130 std::string ConvertToBCP47Tag(const std::string& locale) {
1131 std::string bcp47tag = "b+";
1132 bcp47tag += locale;
1133 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1134
1135 return bcp47tag;
1136 }
1137
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001138 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1139 if (options_.output_to_directory) {
1140 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001142 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001143 }
1144 }
1145
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001146 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001147 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001148 switch (format) {
1149 case OutputFormat::kApk: {
1150 BigBuffer buffer(1024);
1151 TableFlattener flattener(options_.table_flattener_options, &buffer);
1152 if (!flattener.Consume(context_, table)) {
1153 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1154 return false;
1155 }
1156
1157 io::BigBufferInputStream input_stream(&buffer);
1158 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1159 ArchiveEntry::kAlign, writer);
1160 } break;
1161
1162 case OutputFormat::kProto: {
1163 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001164 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1165 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001166 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1167 ArchiveEntry::kCompress, writer);
1168 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001169 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001170 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001171 }
1172
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001173 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001174 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001175 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001176 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001177 return true;
1178 }
1179
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001180 std::string out_path;
1181 std::unique_ptr<io::FileOutputStream> fout;
1182 if (options_.generate_java_class_path) {
1183 out_path = options_.generate_java_class_path.value();
1184 file::AppendPath(&out_path, file::PackageToPath(out_package));
1185 if (!file::mkdirs(out_path)) {
1186 context_->GetDiagnostics()->Error(DiagMessage()
1187 << "failed to create directory '" << out_path << "'");
1188 return false;
1189 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001190
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001191 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001192
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001193 fout = util::make_unique<io::FileOutputStream>(out_path);
1194 if (fout->HadError()) {
1195 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1196 << "': " << fout->GetError());
1197 return false;
1198 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001199 }
1200
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001201 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001202 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001203 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1204 if (fout_text->HadError()) {
1205 context_->GetDiagnostics()->Error(DiagMessage()
1206 << "failed writing to '" << out_text_symbols_path.value()
1207 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001208 return false;
1209 }
1210 }
1211
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001212 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001213 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001214 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001215 return false;
1216 }
1217
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 return true;
1219 }
1220
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001221 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001222 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001223 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1224 std::vector<std::string> packages_to_callback;
1225
1226 JavaClassGeneratorOptions template_options;
1227 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1228 template_options.javadoc_annotations = options_.javadoc_annotations;
1229
1230 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1231 template_options.use_final = false;
1232 }
1233
1234 if (context_->GetPackageType() == PackageType::kSharedLib) {
1235 template_options.use_final = false;
1236 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1237 }
1238
1239 const StringPiece actual_package = context_->GetCompilationPackage();
1240 StringPiece output_package = context_->GetCompilationPackage();
1241 if (options_.custom_java_package) {
1242 // Override the output java package to the custom one.
1243 output_package = options_.custom_java_package.value();
1244 }
1245
1246 // Generate the private symbols if required.
1247 if (options_.private_symbols) {
1248 packages_to_callback.push_back(options_.private_symbols.value());
1249
1250 // If we defined a private symbols package, we only emit Public symbols
1251 // to the original package, and private and public symbols to the private package.
1252 JavaClassGeneratorOptions options = template_options;
1253 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1254 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1255 options)) {
1256 return false;
1257 }
1258 }
1259
1260 // Generate copies of the original package R class but with different package names.
1261 // This is to support non-namespaced builds.
1262 for (const std::string& extra_package : options_.extra_java_packages) {
1263 packages_to_callback.push_back(extra_package);
1264
1265 JavaClassGeneratorOptions options = template_options;
1266 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1267 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1268 return false;
1269 }
1270 }
1271
1272 // Generate R classes for each package that was merged (static library).
1273 // Use the actual package's resources only.
1274 for (const std::string& package : table_merger_->merged_packages()) {
1275 packages_to_callback.push_back(package);
1276
1277 JavaClassGeneratorOptions options = template_options;
1278 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1279 if (!WriteJavaFile(&final_table_, package, package, options)) {
1280 return false;
1281 }
1282 }
1283
1284 // Generate the main public R class.
1285 JavaClassGeneratorOptions options = template_options;
1286
1287 // Only generate public symbols if we have a private package.
1288 if (options_.private_symbols) {
1289 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1290 }
1291
1292 if (options.rewrite_callback_options) {
1293 options.rewrite_callback_options.value().packages_to_callback =
1294 std::move(packages_to_callback);
1295 }
1296
1297 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1298 options_.generate_text_symbols_path)) {
1299 return false;
1300 }
1301
1302 return true;
1303 }
1304
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001305 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001306 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001307 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 return true;
1309 }
1310
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001311 std::unique_ptr<ClassDefinition> manifest_class =
1312 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001313
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 // Something bad happened, but we already logged it, so exit.
1316 return false;
1317 }
1318
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001319 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001320 // Empty Manifest class, no need to generate it.
1321 return true;
1322 }
1323
1324 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001325 for (const std::string& annotation : options_.javadoc_annotations) {
1326 std::string proper_annotation = "@";
1327 proper_annotation += annotation;
1328 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329 }
1330
Adam Lesinski0d81f702017-06-27 15:51:09 -07001331 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001332 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001334 std::string out_path = options_.generate_java_class_path.value();
1335 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001336
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001337 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001338 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1339 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340 return false;
1341 }
1342
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001343 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001345 io::FileOutputStream fout(out_path);
1346 if (fout.HadError()) {
1347 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1348 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001349 return false;
1350 }
1351
Makoto Onukide6e6f22020-06-22 10:17:02 -07001352 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1353 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001354 fout.Flush();
1355
1356 if (fout.HadError()) {
1357 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1358 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359 return false;
1360 }
1361 return true;
1362 }
1363
Ryan Mitchell4382e442021-07-14 12:53:01 -07001364 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001365 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001366 if (!out) {
1367 return true;
1368 }
1369
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001370 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001371 io::FileOutputStream fout(out_path);
1372 if (fout.HadError()) {
1373 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1374 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 return false;
1376 }
1377
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001378 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1379 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001380 fout.Flush();
1381
1382 if (fout.HadError()) {
1383 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1384 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001385 return false;
1386 }
1387 return true;
1388 }
1389
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001390 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001391 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001392 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001393 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 }
1395
Adam Lesinski8780eb62017-10-31 17:44:39 -07001396 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1397 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001398 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001399 return false;
1400 }
1401
Adam Lesinski8780eb62017-10-31 17:44:39 -07001402 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001403 if (table->packages.empty()) {
1404 return true;
1405 }
1406
1407 auto lib_package_result = GetStaticLibraryPackage(table);
1408 if (!lib_package_result.has_value()) {
1409 context_->GetDiagnostics()->Error(DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return false;
1411 }
1412
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001413 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001414 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001416 // Merge all resources as if they were in the compilation package. This is the old behavior
1417 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001418
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001419 // Add the package to the set of --extra-packages so we emit an R.java for each library
1420 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001421 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001422 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001423 }
1424
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001425 // Clear the package name, so as to make the resources look like they are coming from the
1426 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001427 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001428 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429
1430 } else {
1431 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001432 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001433 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001434 }
1435
1436 if (!result) {
1437 return false;
1438 }
1439
1440 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001441 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001442 return true;
1443 }
1444
Adam Lesinski2427dce2017-11-30 15:10:28 -08001445 bool MergeExportedSymbols(const Source& source,
1446 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001447 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001448 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001449 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001450 ResourceName res_name = exported_symbol.name;
1451 if (res_name.package.empty()) {
1452 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001453 }
1454
Ryan Mitchell4382e442021-07-14 12:53:01 -07001455 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001456 if (mangled_name) {
1457 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001458 }
1459
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001460 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001461 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001462 bool result = final_table_.AddResource(
1463 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1464 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001465 if (!result) {
1466 return false;
1467 }
1468 }
1469 return true;
1470 }
1471
Adam Lesinski2427dce2017-11-30 15:10:28 -08001472 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001473 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001474 if (context_->IsVerbose()) {
1475 context_->GetDiagnostics()->Note(DiagMessage()
1476 << "merging '" << compiled_file.name
1477 << "' from compiled file " << compiled_file.source);
1478 }
1479
1480 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1481 return false;
1482 }
1483 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1484 }
1485
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001486 // 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 -07001487 // If override is true, conflicting resources are allowed to override each other, in order of last
1488 // seen.
1489 // An io::IFileCollection is created from the ZIP file and added to the set of
1490 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001491 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001492 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001493 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001494 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495 }
1496
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001497 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001498 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001499 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001501 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001502 return false;
1503 }
1504
1505 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001506 for (auto iter = collection->Iterator(); iter->HasNext();) {
1507 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001508 error = true;
1509 }
1510 }
1511
1512 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001513 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001514 return !error;
1515 }
1516
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001517 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001518 // conflicting resources are allowed to override each other, in order of last seen.
1519 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1520 // as ZIP archive and the files within are merged individually.
1521 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001522 bool MergePath(const std::string& path, bool override) {
1523 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1524 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1525 return MergeArchive(path, override);
1526 } else if (util::EndsWith(path, ".apk")) {
1527 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001528 }
1529
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001530 io::IFile* file = file_collection_->InsertFile(path);
1531 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001532 }
1533
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001534 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001535 // If override is true, conflicting resources are allowed to override each other, in order of last
1536 // seen.
1537 // All other file types are ignored. This is because these files could be coming from a zip,
1538 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001539 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001540 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001541 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001542
Adam Lesinski00451162017-10-03 07:44:08 -07001543 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001544 // Since AAPT compiles these file types and appends .flat to them, seeing
1545 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001546 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1547 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1548 << " file passed as argument. Must be "
1549 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001550 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001551 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1552 if (context_->IsVerbose()) {
1553 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1554 return true;
1555 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001556 }
1557
Adam Lesinski00451162017-10-03 07:44:08 -07001558 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1559 if (input_stream == nullptr) {
1560 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1561 return false;
1562 }
1563
1564 if (input_stream->HadError()) {
1565 context_->GetDiagnostics()->Error(DiagMessage(src)
1566 << "failed to open file: " << input_stream->GetError());
1567 return false;
1568 }
1569
1570 ContainerReaderEntry* entry;
1571 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001572
1573 if (reader.HadError()) {
1574 context_->GetDiagnostics()->Error(DiagMessage(src)
1575 << "failed to read file: " << reader.GetError());
1576 return false;
1577 }
1578
Adam Lesinski00451162017-10-03 07:44:08 -07001579 while ((entry = reader.Next()) != nullptr) {
1580 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001581 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001582 pb::ResourceTable pb_table;
1583 if (!entry->GetResTable(&pb_table)) {
1584 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1585 << entry->GetError());
1586 return false;
1587 }
1588
1589 ResourceTable table;
1590 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001591 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001592 context_->GetDiagnostics()->Error(DiagMessage(src)
1593 << "failed to deserialize resource table: " << error);
1594 return false;
1595 }
1596
1597 if (!table_merger_->Merge(src, &table, override)) {
1598 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1599 return false;
1600 }
1601 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001602 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001603 pb::internal::CompiledFile pb_compiled_file;
1604 off64_t offset;
1605 size_t len;
1606 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1607 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1608 << entry->GetError());
1609 return false;
1610 }
1611
1612 ResourceFile resource_file;
1613 std::string error;
1614 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1615 context_->GetDiagnostics()->Error(DiagMessage(src)
1616 << "failed to read compiled header: " << error);
1617 return false;
1618 }
1619
1620 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1621 return false;
1622 }
1623 }
1624 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001625 return true;
1626 }
1627
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001628 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1629 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1630 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001631 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001632 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1633 if (!files) {
1634 return false;
1635 }
1636
1637 for (const std::string& file : files.value()) {
1638 std::string full_key = "assets/" + file;
1639 std::string full_path = assets_dir;
1640 file::AppendPath(&full_path, file);
1641
1642 auto iter = merged_assets.find(full_key);
1643 if (iter == merged_assets.end()) {
1644 merged_assets.emplace(std::move(full_key),
1645 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1646 } else if (context_->IsVerbose()) {
1647 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1648 << "asset file overrides '" << full_path << "'");
1649 }
1650 }
1651 }
1652
1653 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001654 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001655 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1656 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001657 return false;
1658 }
1659 }
1660 return true;
1661 }
1662
Rhed Jao2c434422020-11-12 10:48:03 +08001663 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1664 Reference* reference) {
1665 if (!reference || !reference->name) {
1666 return nullptr;
1667 }
1668 auto name_ref = ResourceNameRef(reference->name.value());
1669 if (name_ref.package.empty()) {
1670 name_ref.package = context->GetCompilationPackage();
1671 }
1672 const auto search_result = table->FindResource(name_ref);
1673 if (!search_result) {
1674 return nullptr;
1675 }
1676 return search_result.value().entry;
1677 }
1678
Ryan Mitchelldba64562019-06-07 17:07:37 -07001679 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001680 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001681 if (!application) {
1682 return;
1683 }
1684
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001685 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1686 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001687 if (!icon || !round_icon) {
1688 return;
1689 }
1690
1691 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001692 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001693 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1694 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001695 return;
1696 }
1697
1698 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001699 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001700 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1701 ? config_value->config.sdkVersion : icon_max_sdk;
1702 }
1703 if (icon_max_sdk < SDK_O) {
1704 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1705 return;
1706 }
1707
1708 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001709 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001710 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1711 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001712 return;
1713 }
1714
1715 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001716 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001717 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1718 ? config_value->config.sdkVersion : round_icon_max_sdk;
1719 }
1720 if (round_icon_max_sdk >= SDK_O) {
1721 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1722 // not generate an alias to the icon drawable.
1723 return;
1724 }
1725
1726 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001727 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001728 if (config_value->config.sdkVersion < SDK_O) {
1729 continue;
1730 }
1731
1732 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1733 << round_icon_reference->name.value()
1734 << " with config \"" << config_value->config
1735 << "\" for round icon compatibility");
1736
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001737 CloningValueTransformer cloner(&table->string_pool);
1738 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001739 auto round_config_value =
1740 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001741 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001742 }
1743 }
1744
Rhed Jao2c434422020-11-12 10:48:03 +08001745 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1746 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1747 if (manifest_el == nullptr) {
1748 return true;
1749 }
1750 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1751 return true;
1752 }
1753 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1754 if (!attr) {
1755 return true;
1756 }
1757 const auto validate = [&](const std::string& shared_user_id) -> bool {
1758 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1759 return true;
1760 }
1761 DiagMessage error_msg(manifest_el->line_number);
1762 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1763 << shared_user_id << "'";
1764 if (options_.manifest_fixer_options.warn_validation) {
1765 // Treat the error only as a warning.
1766 context_->GetDiagnostics()->Warn(error_msg);
1767 return true;
1768 }
1769 context_->GetDiagnostics()->Error(error_msg);
1770 return false;
1771 };
1772 // If attr->compiled_value is not null, check if it is a ref
1773 if (attr->compiled_value) {
1774 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1775 if (ref == nullptr) {
1776 return true;
1777 }
1778 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1779 if (!shared_user_id_entry) {
1780 return true;
1781 }
1782 for (const auto& value : shared_user_id_entry->values) {
1783 const auto str_value = ValueCast<String>(value->value.get());
1784 if (str_value != nullptr && !validate(*str_value->value)) {
1785 return false;
1786 }
1787 }
1788 return true;
1789 }
1790
1791 // Fallback to checking the raw value
1792 return validate(attr->value);
1793 }
1794
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001795 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1796 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001797 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1798 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001799 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001800 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1801 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001802 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001803 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804 if (!result) {
1805 return false;
1806 }
1807
Ryan Mitchelldba64562019-06-07 17:07:37 -07001808 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1809 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1810 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1811 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1812 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1813 // See (b/34829129)
1814 AliasAdaptiveIcon(manifest, table);
1815
Rhed Jao2c434422020-11-12 10:48:03 +08001816 // Verify the shared user id here to handle the case of reference value.
1817 if (!VerifySharedUserId(manifest, table)) {
1818 return false;
1819 }
1820
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001821 ResourceFileFlattenerOptions file_flattener_options;
1822 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001823 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1824 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001825 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001826 file_flattener_options.no_auto_version = options_.no_auto_version;
1827 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001828 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001829 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1830 file_flattener_options.update_proguard_spec =
1831 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001832 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001833 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001835 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001836 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001837 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 return false;
1839 }
1840
Adam Lesinski490595a2017-11-07 17:08:07 -08001841 // Hack to fix b/68820737.
1842 // We need to modify the ResourceTable's package name, but that should NOT affect
1843 // anything else being generated, which includes the Java classes.
1844 // If required, the package name is modifed before flattening, and then modified back
1845 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001846 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001847 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1848 // or higher] as invalid. In order to work around this limitation, we allow the use
1849 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1850 // definition of what a valid "split" package ID is to account for this.
1851 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1852 context_->GetPackageId() != kAppPackageId &&
1853 context_->GetPackageId() != kFrameworkPackageId)
1854 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001855 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001856 // The base APK is included, and this is a feature split. If the base package is
1857 // the same as this package, then we are building an old style Android Instant Apps feature
1858 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001859 if (!table->packages.empty() &&
1860 table->packages.back()->name == context_->GetCompilationPackage()) {
1861 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001862 std::string new_package_name =
1863 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001864 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001865
1866 if (context_->IsVerbose()) {
1867 context_->GetDiagnostics()->Note(
1868 DiagMessage() << "rewriting resource package name for feature split to '"
1869 << new_package_name << "'");
1870 }
1871 package_to_rewrite->name = new_package_name;
1872 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001873 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001874
1875 bool success = FlattenTable(table, options_.output_format, writer);
1876
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001877 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001878 // Change the name back.
1879 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001880
1881 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1882 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1883 // library, do not include a mapping from the feature package name to the feature package id
1884 // in the feature's dynamic reference table.
1885 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001886 }
1887
1888 if (!success) {
1889 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1890 }
1891 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001892 }
1893
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001894 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001895 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001897 std::unique_ptr<xml::XmlResource> manifest_xml =
1898 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1899 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001900 return 1;
1901 }
1902
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001903 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001904 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001906 const AppInfo& app_info = maybe_app_info.value();
1907 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001908 }
1909
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001910 // Determine the package name under which to merge resources.
1911 if (options_.rename_resources_package) {
1912 if (!options_.custom_java_package) {
1913 // Generate the R.java under the original package name instead of the package name specified
1914 // through --rename-resources-package.
1915 options_.custom_java_package = context_->GetCompilationPackage();
1916 }
1917 context_->SetCompilationPackage(options_.rename_resources_package.value());
1918 }
1919
Adam Lesinskic6284372017-12-04 13:46:23 -08001920 // Now that the compilation package is set, load the dependencies. This will also extract
1921 // the Android framework's versionCode and versionName, if they exist.
1922 if (!LoadSymbolsFromIncludePaths()) {
1923 return 1;
1924 }
1925
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001926 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1927 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001928 return 1;
1929 }
1930
Ryan Mitchell4382e442021-07-14 12:53:01 -07001931 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001932 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 return 1;
1935 }
1936
Adam Lesinski490595a2017-11-07 17:08:07 -08001937 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001938 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001939
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001940 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001941 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001942
1943 // Override the package ID when it is "android".
1944 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001945 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001946
1947 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001948 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001949 context_->GetDiagnostics()->Error(
1950 DiagMessage() << "package 'android' can only be built as a regular app");
1951 return 1;
1952 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 }
1954
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001955 TableMergerOptions table_merger_options;
1956 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001957 table_merger_options.override_styles_instead_of_overlaying =
1958 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001959 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001960 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001961
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001962 if (context_->IsVerbose()) {
1963 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001964 << StringPrintf("linking package '%s' using package ID %02x",
1965 context_->GetCompilationPackage().data(),
1966 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 }
1968
Adam Lesinski2427dce2017-11-30 15:10:28 -08001969 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1970 // in res/**/*.
1971 {
1972 XmlIdCollector collector;
1973 if (!collector.Consume(context_, manifest_xml.get())) {
1974 return false;
1975 }
1976
1977 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1978 return false;
1979 }
1980 }
1981
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 for (const std::string& input : input_files) {
1983 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001984 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985 return 1;
1986 }
1987 }
1988
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 for (const std::string& input : options_.overlay_files) {
1990 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001991 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001992 return 1;
1993 }
1994 }
1995
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 return 1;
1998 }
1999
Adam Lesinskib522f042017-04-21 16:57:59 -07002000 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002001 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002002 if (context_->GetPackageId() == kAndroidPackageId &&
2003 !mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002004 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002005 return 1;
2006 }
2007
2008 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 IdAssigner id_assigner(&options_.stable_id_map);
2010 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002011 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 return 1;
2013 }
2014
2015 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002016 if (options_.resource_id_map_path) {
2017 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018 for (auto& type : package->types) {
2019 for (auto& entry : type->entries) {
Iurii Makhnof0c5ff42022-02-22 13:31:02 +00002020 ResourceName name(package->name, type->named_type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002022 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002023 }
2024 }
2025 }
2026
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002027 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 return 1;
2030 }
2031 }
2032 } else {
2033 // Static libs are merged with other apps, and ID collisions are bad, so
2034 // verify that
2035 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002036 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002037 return 1;
2038 }
2039 }
2040
2041 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002042 context_->SetNameManglerPolicy(
2043 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002044
2045 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002046 context_->GetExternalSymbols()->PrependSource(
2047 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002048
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002049 // Workaround for pre-O runtime that would treat negative resource IDs
2050 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2051 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2052 // are just identifiers.
2053 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2054 if (context_->IsVerbose()) {
2055 context_->GetDiagnostics()->Note(DiagMessage()
2056 << "enabling pre-O feature split ID rewriting");
2057 }
2058 context_->GetExternalSymbols()->SetDelegate(
2059 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2060 }
2061
Adam Lesinski34a16872018-02-23 16:18:10 -08002062 // Before we process anything, remove the resources whose default values don't exist.
2063 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02002064 if (!options_.no_resource_removal) {
2065 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
2066 context_->GetDiagnostics()->Error(DiagMessage()
2067 << "failed removing resources with no defaults");
2068 return 1;
2069 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002070 }
2071
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002072 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002073 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002074 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002075 return 1;
2076 }
2077
Adam Lesinskib522f042017-04-21 16:57:59 -07002078 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002079 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002080 context_->GetDiagnostics()->Warn(DiagMessage()
2081 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082 }
2083 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002084 ProductFilter product_filter(options_.products);
2085 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002086 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 return 1;
2088 }
2089 }
2090
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002091 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002093 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002094 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002095 return 1;
2096 }
2097 }
2098
Adam Lesinskib522f042017-04-21 16:57:59 -07002099 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002100 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002101 context_->GetDiagnostics()->Note(DiagMessage()
2102 << "collapsing resource versions for minimum SDK "
2103 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 }
2105
2106 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002107 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002108 return 1;
2109 }
2110 }
2111
Winson3c918b82019-01-25 14:25:37 -08002112 if (!options_.exclude_configs_.empty()) {
2113 std::vector<ConfigDescription> excluded_configs;
2114
2115 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002116 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002117 ConfigDescription config_description;
2118
2119 if (!ConfigDescription::Parse(config_string, &config_description)) {
2120 context_->GetDiagnostics()->Error(DiagMessage()
2121 << "failed to parse --excluded-configs "
2122 << config_string);
2123 return 1;
2124 }
2125
2126 excluded_configs.push_back(config_description);
2127 }
2128
2129 ResourceExcluder excluder(excluded_configs);
2130 if (!excluder.Consume(context_, &final_table_)) {
2131 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
2132 return 1;
2133 }
2134 }
2135
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002136 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002137 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002138 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002139 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 return 1;
2141 }
2142 }
2143
Adam Koskidc21dea2017-07-21 10:55:27 -07002144 proguard::KeepSet proguard_keep_set =
2145 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002146 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002147
Adam Lesinskib522f042017-04-21 16:57:59 -07002148 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002149 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002150 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002151 context_->GetDiagnostics()->Warn(DiagMessage()
2152 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002153 }
2154 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002155 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2156 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002157 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002158 options_.split_constraints =
2159 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002161 if (origConstraintSize != options_.split_constraints.size()) {
2162 context_->GetDiagnostics()->Warn(DiagMessage()
2163 << "requested to split resources prior to min sdk of "
2164 << context_->GetMinSdkVersion());
2165 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002166 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002167 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 return 1;
2169 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002170 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002171
2172 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002173 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002174 auto split_constraints_iter = options_.split_constraints.begin();
2175 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002176 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002177 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2178 << "generating split with configurations '"
2179 << util::Joiner(split_constraints_iter->configs, ", ")
2180 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002181 }
2182
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002183 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002185 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186 return 1;
2187 }
2188
2189 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002190 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002191 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002192
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002193 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002194 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002195 context_->GetDiagnostics()->Error(DiagMessage()
2196 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002197 return 1;
2198 }
2199
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002200 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2201 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002202 return 1;
2203 }
2204
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002205 ++path_iter;
2206 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002207 }
2208 }
2209
2210 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002211 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002212 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002213 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002214 return 1;
2215 }
2216
2217 bool error = false;
2218 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002219 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002220 // (aka, which package the AndroidManifest.xml is coming from).
2221 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002222 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002223
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002224 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002225 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002226 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002227 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002228 error = true;
2229 }
2230
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002231 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002232 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002233 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002234 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002235 }
2236
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002237 if (options_.generate_java_class_path) {
2238 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002239 error = true;
2240 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002241 }
2242
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002243 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002244 // PackageParser will fail if URIs are removed from
2245 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002246 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2247 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002248 error = true;
2249 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002250 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002251 } else {
2252 error = true;
2253 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002254 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002255
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002256 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002257 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002258 return 1;
2259 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002260
Josh Houd3bd4522022-02-14 10:24:42 +08002261 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2262 return 1;
2263 };
2264
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002265 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2266 return 1;
2267 }
2268
2269 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002270 return 1;
2271 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002272
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002273 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002274 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002275 return 1;
2276 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002277 }
2278
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002279 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002280 return 1;
2281 }
2282
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002283 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2284 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002285 return 1;
2286 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002287 return 0;
2288 }
2289
2290 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002291 LinkOptions options_;
2292 LinkContext* context_;
2293 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002294
Adam Lesinski490595a2017-11-07 17:08:07 -08002295 AppInfo app_info_;
2296
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002297 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002298
2299 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002300 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002301
Adam Lesinski8780eb62017-10-31 17:44:39 -07002302 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002303 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002304 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002305
Adam Lesinski8780eb62017-10-31 17:44:39 -07002306 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2307 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2308
2309 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2310 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002311
2312 // The set of shared libraries being used, mapping their assigned package ID to package name.
2313 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002314
2315 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002316 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002317};
2318
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002319int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002320 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002321 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002322
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002323 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002324 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002325 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002326 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002327 const std::string path = arg.substr(1, arg.size() - 1);
2328 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002329 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2330 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002331 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002332 }
2333 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002334 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335 }
2336 }
2337
2338 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002339 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002340 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002341 const std::string path = arg.substr(1, arg.size() - 1);
2342 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002343 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002344 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002345 return 1;
2346 }
2347 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002348 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002349 }
2350 }
2351
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002352 if (verbose_) {
2353 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002354 }
2355
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002356 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002357 context.GetDiagnostics()->Error(
2358 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002359 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002360 return 1;
2361 }
2362
Ryan Mitchell5855de72021-02-24 14:39:13 -08002363 if (shared_lib_ && options_.private_symbols) {
2364 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2365 // reference the private attribute within the styleable array will cause a link error because
2366 // the private attribute will not be emitted in the public R.java.
2367 context.GetDiagnostics()->Error(DiagMessage()
2368 << "--shared-lib cannot currently be used in combination with"
2369 << " --private-symbols");
2370 return 1;
2371 }
2372
Izabela Orlowska84febea2019-06-03 18:34:12 +01002373 if (options_.merge_only && !static_lib_) {
2374 context.GetDiagnostics()->Error(
2375 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2376 return 1;
2377 }
2378
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002379 // The default build type.
2380 context.SetPackageType(PackageType::kApp);
2381 context.SetPackageId(kAppPackageId);
2382
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002383 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002384 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002385 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002386 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002387 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002388 options_.output_format = OutputFormat::kProto;
2389 } else if (proto_format_) {
2390 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002391 }
2392
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002393 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002394 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002395 context.GetDiagnostics()->Error(
2396 DiagMessage() << "can't specify --package-id when not building a regular app");
2397 return 1;
2398 }
2399
Ryan Mitchell4382e442021-07-14 12:53:01 -07002400 const std::optional<uint32_t> maybe_package_id_int =
2401 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002402 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002403 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002404 << "' is not a valid integer");
2405 return 1;
2406 }
2407
2408 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002409 if (package_id_int > std::numeric_limits<uint8_t>::max()
2410 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002411 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002412 context.GetDiagnostics()->Error(
2413 DiagMessage() << StringPrintf(
2414 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2415 return 1;
2416 }
2417 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2418 }
2419
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002420 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002421 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002422 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002423 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002424 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002425 }
2426 }
2427
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002428 if (product_list_) {
2429 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002430 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002431 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002432 }
2433 }
2434 }
2435
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002436 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002437 if (!configs_.empty()) {
2438 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002439 if (filter == nullptr) {
2440 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002441 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002442 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002443 }
2444
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002445 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002446 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002447 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002448 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002449 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002450 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002451 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002452 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002453
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002454 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002455 for (const std::string& split_arg : split_args_) {
2456 options_.split_paths.push_back({});
2457 options_.split_constraints.push_back({});
2458 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2459 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002460 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002461 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002462 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002463
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002464 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2465 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2466 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002467 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002468 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002469 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002470
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002471 if (no_compress_regex) {
2472 std::string regex = no_compress_regex.value();
2473 if (util::StartsWith(regex, "@")) {
2474 const std::string path = regex.substr(1, regex.size() -1);
2475 std::string error;
2476 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2477 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2478 return 1;
2479 }
2480 } else {
2481 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2482 }
2483 }
2484
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002485 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002486 options_.extensions_to_not_compress.insert({
2487 // Image extensions
2488 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2489 // Audio extensions
2490 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2491 ".xmf", ".amr", ".awb",
2492 // Audio/video extensions
2493 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2494 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002495
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002496 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002497 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002498 options_.no_auto_version = true;
2499 options_.no_version_vectors = true;
2500 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002501 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002502
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002503 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002504 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002505}
2506
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002507} // namespace aapt