blob: 1efe6c25d21764d273e259adbbabc41530a3399d [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
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 if (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();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700599 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700601
602 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
603 // else we end up copying the string in the std::make_pair() method,
604 // then creating a StringPiece from the copy, which would cause us
605 // to end up referencing garbage in the map.
606 const StringPiece entry_name(entry->name);
607 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
608 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700609 }
610 }
611
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700613 for (auto& map_entry : config_sorted_files) {
614 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700615 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700618 // Check minimum sdk versions supported for drawables
619 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
620 if (drawable_entry != kDrawableVersions.end()) {
621 if (drawable_entry->second > context_->GetMinSdkVersion()
622 && drawable_entry->second > config.sdkVersion) {
623 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
624 << "<" << drawable_entry->first << "> elements "
625 << "require a sdk version of at least "
626 << (int16_t) drawable_entry->second);
627 error = true;
628 continue;
629 }
630 }
631
Adam Lesinskic744ae82017-05-17 19:28:38 -0700632 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
633 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700634 if (versioned_docs.empty()) {
635 error = true;
636 continue;
637 }
638
Adam Lesinskic744ae82017-05-17 19:28:38 -0700639 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
640 std::string dst_path = file_op.dst_path;
641 if (doc->file.config != file_op.config) {
642 // Only add the new versioned configurations.
643 if (context_->IsVerbose()) {
644 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
645 << "auto-versioning resource from config '"
646 << config << "' -> '" << doc->file.config << "'");
647 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800649 const ResourceFile& file = doc->file;
650 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
651
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700652 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800653 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
654 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700655
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800656 // Update the output format of this XML file.
657 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700658 bool result = table->AddResource(NewResourceBuilder(file.name)
659 .SetValue(std::move(file_ref), file.config)
660 .SetAllowMangled(true)
661 .Build(),
662 context_->GetDiagnostics());
663 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700664 return false;
665 }
666 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700667
668 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
669 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 }
671 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700672 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700673 GetCompressionFlags(file_op.dst_path, options_),
674 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700675 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700677 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 }
679 return !error;
680}
681
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700682static bool WriteStableIdMapToPath(IDiagnostics* diag,
683 const std::unordered_map<ResourceName, ResourceId>& id_map,
684 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800685 io::FileOutputStream fout(id_map_path);
686 if (fout.HadError()) {
687 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688 return false;
689 }
690
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800691 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700692 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 const ResourceName& name = entry.first;
694 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800695 printer.Print(name.to_string());
696 printer.Print(" = ");
697 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800699 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800701 if (fout.HadError()) {
702 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 return false;
704 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 return true;
706}
707
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700708static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
709 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700711 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 return false;
714 }
715
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 out_id_map->clear();
717 size_t line_no = 0;
718 for (StringPiece line : util::Tokenize(content, '\n')) {
719 line_no++;
720 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700721 if (line.empty()) {
722 continue;
723 }
724
725 auto iter = std::find(line.begin(), line.end(), '=');
726 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700728 return false;
729 }
730
731 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 StringPiece res_name_str =
733 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
734 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700735 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
736 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700737 return false;
738 }
739
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
741 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700742 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743
Ryan Mitchell4382e442021-07-14 12:53:01 -0700744 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700746 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
747 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748 return false;
749 }
750
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700751 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700752 }
753 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700754}
755
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700756class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700758 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700759 : options_(options),
760 context_(context),
761 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700762 file_collection_(util::make_unique<io::FileCollection>()) {
763 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700764
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800765 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800766 using namespace android;
767
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000768 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
769 // we're looking for the first attribute resource in the system package.
770 android::ApkAssetsCookie cookie;
771 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
772 cookie = value->cookie;
773 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800774 // No Framework assets loaded. Not a failure.
775 return;
776 }
777
778 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800779 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800780 if (manifest == nullptr) {
781 // No errors.
782 return;
783 }
784
785 std::string error;
786 std::unique_ptr<xml::XmlResource> manifest_xml =
787 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
788 if (manifest_xml == nullptr) {
789 // No errors.
790 return;
791 }
792
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700793 if (!options_.manifest_fixer_options.compile_sdk_version) {
794 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
795 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700796 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700797 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
798 switch (prim->value.dataType) {
799 case Res_value::TYPE_INT_DEC:
800 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
801 break;
802 case Res_value::TYPE_INT_HEX:
803 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
804 break;
805 default:
806 break;
807 }
808 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
809 compile_sdk_version = *str->value;
810 } else {
811 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800812 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800813 }
814 }
815
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700816 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
817 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
818 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700819 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700820 options_.manifest_fixer_options.compile_sdk_version_codename;
821 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
822 compile_sdk_version_codename = *str->value;
823 } else {
824 compile_sdk_version_codename = attr->value;
825 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800826 }
827 }
828 }
829
Adam Lesinski8780eb62017-10-31 17:44:39 -0700830 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800831 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700832 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800833 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700834 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700835 for (const std::string& path : options_.include_paths) {
836 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700837 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700838 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700839
Adam Lesinski8780eb62017-10-31 17:44:39 -0700840 std::string error;
841 auto zip_collection = io::ZipFileCollection::Create(path, &error);
842 if (zip_collection == nullptr) {
843 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
844 return false;
845 }
846
847 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
848 // Load this as a static library include.
849 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
850 Source(path), std::move(zip_collection), context_->GetDiagnostics());
851 if (static_apk == nullptr) {
852 return false;
853 }
854
Adam Lesinskib522f042017-04-21 16:57:59 -0700855 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800856 // Can't include static libraries when not building a static library (they have no IDs
857 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700858 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800859 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700860 return false;
861 }
862
Adam Lesinski8780eb62017-10-31 17:44:39 -0700863 ResourceTable* table = static_apk->GetResourceTable();
864
865 // 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 -0700866 // our compilation package so the symbol package name does not get mangled into the entry
867 // name.
868 if (options_.no_static_lib_packages && !table->packages.empty()) {
869 auto lib_package_result = GetStaticLibraryPackage(table);
870 if (!lib_package_result.has_value()) {
871 context_->GetDiagnostics()->Error(DiagMessage(path) << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800872 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700874 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700875 }
876
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700877 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700878 util::make_unique<ResourceTableSymbolSource>(table));
879 static_library_includes_.push_back(std::move(static_apk));
880 } else {
881 if (!asset_source->AddAssetPath(path)) {
882 context_->GetDiagnostics()->Error(DiagMessage()
883 << "failed to load include path " << path);
884 return false;
885 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700886 }
887 }
888
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800889 // Capture the shared libraries so that the final resource table can be properly flattened
890 // with support for shared libraries.
891 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700892 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800893 // Capture the included base feature package.
894 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800895 } else if (entry.first == kFrameworkPackageId) {
896 // Try to embed which version of the framework we're compiling against.
897 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
898 // when linking our synthesized 'android:compileSdkVersion' attribute.
899 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
900 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
901 if (symbol != nullptr && symbol->is_public) {
902 // The symbol is present and public, extract the android:versionName and
903 // android:versionCode from the framework AndroidManifest.xml.
904 ExtractCompileSdkVersions(asset_source->GetAssetManager());
905 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700906 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700907 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800908 }
909 }
910
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700912 return true;
913 }
914
Ryan Mitchell4382e442021-07-14 12:53:01 -0700915 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800916 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700917 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800918 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
919 if (manifest_el == nullptr) {
920 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800922
923 AppInfo app_info;
924
925 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
926 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
927 return {};
928 }
929
930 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
931 if (!package_attr) {
932 diag->Error(DiagMessage(xml_res->file.source)
933 << "<manifest> must have a 'package' attribute");
934 return {};
935 }
936 app_info.package = package_attr->value;
937
938 if (xml::Attribute* version_code_attr =
939 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700940 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800941 if (!maybe_code) {
942 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
943 << "invalid android:versionCode '" << version_code_attr->value << "'");
944 return {};
945 }
946 app_info.version_code = maybe_code.value();
947 }
948
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700949 if (xml::Attribute* version_code_major_attr =
950 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700951 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700952 if (!maybe_code) {
953 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
954 << "invalid android:versionCodeMajor '"
955 << version_code_major_attr->value << "'");
956 return {};
957 }
958 app_info.version_code_major = maybe_code.value();
959 }
960
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800961 if (xml::Attribute* revision_code_attr =
962 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700963 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800964 if (!maybe_code) {
965 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
966 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
967 return {};
968 }
969 app_info.revision_code = maybe_code.value();
970 }
971
972 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
973 if (!split_name_attr->value.empty()) {
974 app_info.split_name = split_name_attr->value;
975 }
976 }
977
978 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
979 if (xml::Attribute* min_sdk =
980 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700981 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800982 }
983 }
Udam Sainib228df32019-06-18 16:50:34 -0700984
985 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
986 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
987 if (const xml::Attribute* split_name =
988 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
989 if (!split_name->value.empty()) {
990 app_info.split_name_dependencies.insert(split_name->value);
991 }
992 }
993 }
994 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800995 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 }
997
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700998 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
999 // Postcondition: ResourceTable has only one package left. All others are
1000 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001001 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001002 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001003 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 };
1005
1006 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 for (const auto& package : final_table_.packages) {
1008 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001009 // We have a package that is not related to the one we're building!
1010 for (const auto& type : package->types) {
1011 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001012 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001014 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001015 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001017 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1018 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1019 << "generated id '" << res_name
1020 << "' for external package '" << package->name
1021 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001023 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1024 << "defined resource '" << res_name
1025 << "' for external package '" << package->name
1026 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001027 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001028 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001029 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001030 }
1031 }
1032 }
1033 }
1034
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001035 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1036 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001037 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 return !error;
1039 }
1040
1041 /**
1042 * Returns true if no IDs have been set, false otherwise.
1043 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001044 bool VerifyNoIdsSet() {
1045 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001046 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 for (const auto& entry : type->entries) {
1048 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001049 ResourceNameRef res_name(package->name, type->type, entry->name);
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001050 context_->GetDiagnostics()->Error(DiagMessage() << "resource " << res_name << " has ID "
1051 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001052 return false;
1053 }
1054 }
1055 }
1056 }
1057 return true;
1058 }
1059
Josh Houd3bd4522022-02-14 10:24:42 +08001060 bool VerifyLocaleFormat(xml::XmlResource* manifest, IDiagnostics* diag) {
1061 // Skip it if the Manifest doesn't declare the localeConfig attribute within the <application>
1062 // element.
1063 const xml::Element* application = manifest->root->FindChild("", "application");
1064 if (!application) {
1065 return true;
1066 }
1067 const xml::Attribute* localeConfig =
1068 application->FindAttribute(xml::kSchemaAndroid, "localeConfig");
1069 if (!localeConfig) {
1070 return true;
1071 }
1072
1073 if (localeConfig->compiled_value) {
1074 const auto localeconfig_reference = ValueCast<Reference>(localeConfig->compiled_value.get());
1075 const auto localeconfig_entry =
1076 ResolveTableEntry(context_, &final_table_, localeconfig_reference);
1077 if (!localeconfig_entry) {
1078 return true;
1079 }
1080
1081 for (const auto& value : localeconfig_entry->values) {
1082 // Load an XML file which is linked from the localeConfig attribute.
1083 const std::string& path = value->value->GetSource().path;
1084 std::unique_ptr<xml::XmlResource> localeConfig_xml = LoadXml(path, diag);
1085 if (!localeConfig_xml) {
1086 diag->Error(DiagMessage(path) << "can't load the XML");
1087 return false;
1088 }
1089
1090 xml::Element* localeConfig_el = xml::FindRootElement(localeConfig_xml->root.get());
1091 if (!localeConfig_el) {
1092 diag->Error(DiagMessage(path) << "no root tag defined");
1093 return false;
1094 }
1095 if (localeConfig_el->name != "locale-config") {
1096 diag->Error(DiagMessage(path) << "invalid element name: " << localeConfig_el->name
1097 << ", expected: locale-config");
1098 return false;
1099 }
1100
1101 for (const xml::Element* child_el : localeConfig_el->GetChildElements()) {
1102 if (child_el->name == "locale") {
1103 if (const xml::Attribute* locale_name_attr =
1104 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
1105 const std::string& locale_name = locale_name_attr->value;
1106 const std::string valid_name = ConvertToBCP47Tag(locale_name);
1107
1108 // Start to verify the locale format
1109 ConfigDescription config;
1110 if (!ConfigDescription::Parse(valid_name, &config)) {
1111 diag->Error(DiagMessage(path) << "invalid configuration: " << locale_name);
1112 return false;
1113 }
1114 } else {
1115 diag->Error(DiagMessage(path) << "the attribute android:name is not found");
1116 return false;
1117 }
1118 } else {
1119 diag->Error(DiagMessage(path)
1120 << "invalid element name: " << child_el->name << ", expected: locale");
1121 return false;
1122 }
1123 }
1124 }
1125 }
1126 return true;
1127 }
1128
1129 std::string ConvertToBCP47Tag(const std::string& locale) {
1130 std::string bcp47tag = "b+";
1131 bcp47tag += locale;
1132 std::replace(bcp47tag.begin(), bcp47tag.end(), '-', '+');
1133
1134 return bcp47tag;
1135 }
1136
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001137 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1138 if (options_.output_to_directory) {
1139 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001141 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001142 }
1143 }
1144
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001145 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001146 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001147 switch (format) {
1148 case OutputFormat::kApk: {
1149 BigBuffer buffer(1024);
1150 TableFlattener flattener(options_.table_flattener_options, &buffer);
1151 if (!flattener.Consume(context_, table)) {
1152 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1153 return false;
1154 }
1155
1156 io::BigBufferInputStream input_stream(&buffer);
1157 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1158 ArchiveEntry::kAlign, writer);
1159 } break;
1160
1161 case OutputFormat::kProto: {
1162 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001163 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1164 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001165 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1166 ArchiveEntry::kCompress, writer);
1167 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001168 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001169 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001170 }
1171
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001172 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001173 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001174 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001175 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001176 return true;
1177 }
1178
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001179 std::string out_path;
1180 std::unique_ptr<io::FileOutputStream> fout;
1181 if (options_.generate_java_class_path) {
1182 out_path = options_.generate_java_class_path.value();
1183 file::AppendPath(&out_path, file::PackageToPath(out_package));
1184 if (!file::mkdirs(out_path)) {
1185 context_->GetDiagnostics()->Error(DiagMessage()
1186 << "failed to create directory '" << out_path << "'");
1187 return false;
1188 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001190 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001191
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001192 fout = util::make_unique<io::FileOutputStream>(out_path);
1193 if (fout->HadError()) {
1194 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1195 << "': " << fout->GetError());
1196 return false;
1197 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 }
1199
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001200 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001201 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001202 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1203 if (fout_text->HadError()) {
1204 context_->GetDiagnostics()->Error(DiagMessage()
1205 << "failed writing to '" << out_text_symbols_path.value()
1206 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001207 return false;
1208 }
1209 }
1210
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001211 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001212 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001213 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 return false;
1215 }
1216
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001217 return true;
1218 }
1219
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001220 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001221 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001222 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1223 std::vector<std::string> packages_to_callback;
1224
1225 JavaClassGeneratorOptions template_options;
1226 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1227 template_options.javadoc_annotations = options_.javadoc_annotations;
1228
1229 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1230 template_options.use_final = false;
1231 }
1232
1233 if (context_->GetPackageType() == PackageType::kSharedLib) {
1234 template_options.use_final = false;
1235 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1236 }
1237
1238 const StringPiece actual_package = context_->GetCompilationPackage();
1239 StringPiece output_package = context_->GetCompilationPackage();
1240 if (options_.custom_java_package) {
1241 // Override the output java package to the custom one.
1242 output_package = options_.custom_java_package.value();
1243 }
1244
1245 // Generate the private symbols if required.
1246 if (options_.private_symbols) {
1247 packages_to_callback.push_back(options_.private_symbols.value());
1248
1249 // If we defined a private symbols package, we only emit Public symbols
1250 // to the original package, and private and public symbols to the private package.
1251 JavaClassGeneratorOptions options = template_options;
1252 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1253 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1254 options)) {
1255 return false;
1256 }
1257 }
1258
1259 // Generate copies of the original package R class but with different package names.
1260 // This is to support non-namespaced builds.
1261 for (const std::string& extra_package : options_.extra_java_packages) {
1262 packages_to_callback.push_back(extra_package);
1263
1264 JavaClassGeneratorOptions options = template_options;
1265 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1266 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1267 return false;
1268 }
1269 }
1270
1271 // Generate R classes for each package that was merged (static library).
1272 // Use the actual package's resources only.
1273 for (const std::string& package : table_merger_->merged_packages()) {
1274 packages_to_callback.push_back(package);
1275
1276 JavaClassGeneratorOptions options = template_options;
1277 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1278 if (!WriteJavaFile(&final_table_, package, package, options)) {
1279 return false;
1280 }
1281 }
1282
1283 // Generate the main public R class.
1284 JavaClassGeneratorOptions options = template_options;
1285
1286 // Only generate public symbols if we have a private package.
1287 if (options_.private_symbols) {
1288 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1289 }
1290
1291 if (options.rewrite_callback_options) {
1292 options.rewrite_callback_options.value().packages_to_callback =
1293 std::move(packages_to_callback);
1294 }
1295
1296 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1297 options_.generate_text_symbols_path)) {
1298 return false;
1299 }
1300
1301 return true;
1302 }
1303
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001304 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001305 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001306 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 return true;
1308 }
1309
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001310 std::unique_ptr<ClassDefinition> manifest_class =
1311 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001313 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001314 // Something bad happened, but we already logged it, so exit.
1315 return false;
1316 }
1317
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001318 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 // Empty Manifest class, no need to generate it.
1320 return true;
1321 }
1322
1323 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001324 for (const std::string& annotation : options_.javadoc_annotations) {
1325 std::string proper_annotation = "@";
1326 proper_annotation += annotation;
1327 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001328 }
1329
Adam Lesinski0d81f702017-06-27 15:51:09 -07001330 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001331 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001333 std::string out_path = options_.generate_java_class_path.value();
1334 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001336 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001337 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1338 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339 return false;
1340 }
1341
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001342 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001344 io::FileOutputStream fout(out_path);
1345 if (fout.HadError()) {
1346 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1347 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001348 return false;
1349 }
1350
Makoto Onukide6e6f22020-06-22 10:17:02 -07001351 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1352 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001353 fout.Flush();
1354
1355 if (fout.HadError()) {
1356 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1357 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358 return false;
1359 }
1360 return true;
1361 }
1362
Ryan Mitchell4382e442021-07-14 12:53:01 -07001363 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001364 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001365 if (!out) {
1366 return true;
1367 }
1368
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001369 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001370 io::FileOutputStream fout(out_path);
1371 if (fout.HadError()) {
1372 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1373 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374 return false;
1375 }
1376
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001377 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1378 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001379 fout.Flush();
1380
1381 if (fout.HadError()) {
1382 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1383 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001384 return false;
1385 }
1386 return true;
1387 }
1388
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001390 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001391 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001392 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001393 }
1394
Adam Lesinski8780eb62017-10-31 17:44:39 -07001395 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1396 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001397 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 return false;
1399 }
1400
Adam Lesinski8780eb62017-10-31 17:44:39 -07001401 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001402 if (table->packages.empty()) {
1403 return true;
1404 }
1405
1406 auto lib_package_result = GetStaticLibraryPackage(table);
1407 if (!lib_package_result.has_value()) {
1408 context_->GetDiagnostics()->Error(DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001409 return false;
1410 }
1411
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001412 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001413 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001415 // Merge all resources as if they were in the compilation package. This is the old behavior
1416 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001418 // Add the package to the set of --extra-packages so we emit an R.java for each library
1419 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001421 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 }
1423
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001424 // Clear the package name, so as to make the resources look like they are coming from the
1425 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001426 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001427 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001428
1429 } else {
1430 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001431 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001432 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001433 }
1434
1435 if (!result) {
1436 return false;
1437 }
1438
1439 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001440 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001441 return true;
1442 }
1443
Adam Lesinski2427dce2017-11-30 15:10:28 -08001444 bool MergeExportedSymbols(const Source& source,
1445 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001446 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001447 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001448 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001449 ResourceName res_name = exported_symbol.name;
1450 if (res_name.package.empty()) {
1451 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001452 }
1453
Ryan Mitchell4382e442021-07-14 12:53:01 -07001454 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001455 if (mangled_name) {
1456 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001457 }
1458
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001459 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001460 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001461 bool result = final_table_.AddResource(
1462 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1463 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464 if (!result) {
1465 return false;
1466 }
1467 }
1468 return true;
1469 }
1470
Adam Lesinski2427dce2017-11-30 15:10:28 -08001471 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001472 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001473 if (context_->IsVerbose()) {
1474 context_->GetDiagnostics()->Note(DiagMessage()
1475 << "merging '" << compiled_file.name
1476 << "' from compiled file " << compiled_file.source);
1477 }
1478
1479 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1480 return false;
1481 }
1482 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1483 }
1484
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001485 // 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 -07001486 // If override is true, conflicting resources are allowed to override each other, in order of last
1487 // seen.
1488 // An io::IFileCollection is created from the ZIP file and added to the set of
1489 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001490 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001491 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001492 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001493 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001494 }
1495
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001496 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001497 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001498 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001499 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001500 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001501 return false;
1502 }
1503
1504 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001505 for (auto iter = collection->Iterator(); iter->HasNext();) {
1506 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001507 error = true;
1508 }
1509 }
1510
1511 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001512 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001513 return !error;
1514 }
1515
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001516 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001517 // conflicting resources are allowed to override each other, in order of last seen.
1518 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1519 // as ZIP archive and the files within are merged individually.
1520 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001521 bool MergePath(const std::string& path, bool override) {
1522 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1523 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1524 return MergeArchive(path, override);
1525 } else if (util::EndsWith(path, ".apk")) {
1526 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001527 }
1528
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001529 io::IFile* file = file_collection_->InsertFile(path);
1530 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001531 }
1532
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001533 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001534 // If override is true, conflicting resources are allowed to override each other, in order of last
1535 // seen.
1536 // All other file types are ignored. This is because these files could be coming from a zip,
1537 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001539 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001541
Adam Lesinski00451162017-10-03 07:44:08 -07001542 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001543 // Since AAPT compiles these file types and appends .flat to them, seeing
1544 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001545 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1546 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1547 << " file passed as argument. Must be "
1548 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001549 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001550 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1551 if (context_->IsVerbose()) {
1552 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1553 return true;
1554 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001555 }
1556
Adam Lesinski00451162017-10-03 07:44:08 -07001557 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1558 if (input_stream == nullptr) {
1559 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1560 return false;
1561 }
1562
1563 if (input_stream->HadError()) {
1564 context_->GetDiagnostics()->Error(DiagMessage(src)
1565 << "failed to open file: " << input_stream->GetError());
1566 return false;
1567 }
1568
1569 ContainerReaderEntry* entry;
1570 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001571
1572 if (reader.HadError()) {
1573 context_->GetDiagnostics()->Error(DiagMessage(src)
1574 << "failed to read file: " << reader.GetError());
1575 return false;
1576 }
1577
Adam Lesinski00451162017-10-03 07:44:08 -07001578 while ((entry = reader.Next()) != nullptr) {
1579 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001580 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001581 pb::ResourceTable pb_table;
1582 if (!entry->GetResTable(&pb_table)) {
1583 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1584 << entry->GetError());
1585 return false;
1586 }
1587
1588 ResourceTable table;
1589 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001590 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001591 context_->GetDiagnostics()->Error(DiagMessage(src)
1592 << "failed to deserialize resource table: " << error);
1593 return false;
1594 }
1595
1596 if (!table_merger_->Merge(src, &table, override)) {
1597 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1598 return false;
1599 }
1600 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001601 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001602 pb::internal::CompiledFile pb_compiled_file;
1603 off64_t offset;
1604 size_t len;
1605 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1606 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1607 << entry->GetError());
1608 return false;
1609 }
1610
1611 ResourceFile resource_file;
1612 std::string error;
1613 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1614 context_->GetDiagnostics()->Error(DiagMessage(src)
1615 << "failed to read compiled header: " << error);
1616 return false;
1617 }
1618
1619 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1620 return false;
1621 }
1622 }
1623 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001624 return true;
1625 }
1626
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001627 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1628 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1629 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001630 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001631 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1632 if (!files) {
1633 return false;
1634 }
1635
1636 for (const std::string& file : files.value()) {
1637 std::string full_key = "assets/" + file;
1638 std::string full_path = assets_dir;
1639 file::AppendPath(&full_path, file);
1640
1641 auto iter = merged_assets.find(full_key);
1642 if (iter == merged_assets.end()) {
1643 merged_assets.emplace(std::move(full_key),
1644 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1645 } else if (context_->IsVerbose()) {
1646 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1647 << "asset file overrides '" << full_path << "'");
1648 }
1649 }
1650 }
1651
1652 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001653 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001654 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1655 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001656 return false;
1657 }
1658 }
1659 return true;
1660 }
1661
Rhed Jao2c434422020-11-12 10:48:03 +08001662 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1663 Reference* reference) {
1664 if (!reference || !reference->name) {
1665 return nullptr;
1666 }
1667 auto name_ref = ResourceNameRef(reference->name.value());
1668 if (name_ref.package.empty()) {
1669 name_ref.package = context->GetCompilationPackage();
1670 }
1671 const auto search_result = table->FindResource(name_ref);
1672 if (!search_result) {
1673 return nullptr;
1674 }
1675 return search_result.value().entry;
1676 }
1677
Ryan Mitchelldba64562019-06-07 17:07:37 -07001678 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001679 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001680 if (!application) {
1681 return;
1682 }
1683
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001684 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1685 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001686 if (!icon || !round_icon) {
1687 return;
1688 }
1689
1690 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001691 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001692 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1693 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001694 return;
1695 }
1696
1697 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001698 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001699 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1700 ? config_value->config.sdkVersion : icon_max_sdk;
1701 }
1702 if (icon_max_sdk < SDK_O) {
1703 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1704 return;
1705 }
1706
1707 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001708 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001709 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1710 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001711 return;
1712 }
1713
1714 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001715 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001716 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1717 ? config_value->config.sdkVersion : round_icon_max_sdk;
1718 }
1719 if (round_icon_max_sdk >= SDK_O) {
1720 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1721 // not generate an alias to the icon drawable.
1722 return;
1723 }
1724
1725 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001726 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001727 if (config_value->config.sdkVersion < SDK_O) {
1728 continue;
1729 }
1730
1731 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1732 << round_icon_reference->name.value()
1733 << " with config \"" << config_value->config
1734 << "\" for round icon compatibility");
1735
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001736 CloningValueTransformer cloner(&table->string_pool);
1737 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001738 auto round_config_value =
1739 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001740 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001741 }
1742 }
1743
Rhed Jao2c434422020-11-12 10:48:03 +08001744 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1745 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1746 if (manifest_el == nullptr) {
1747 return true;
1748 }
1749 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1750 return true;
1751 }
1752 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1753 if (!attr) {
1754 return true;
1755 }
1756 const auto validate = [&](const std::string& shared_user_id) -> bool {
1757 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1758 return true;
1759 }
1760 DiagMessage error_msg(manifest_el->line_number);
1761 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1762 << shared_user_id << "'";
1763 if (options_.manifest_fixer_options.warn_validation) {
1764 // Treat the error only as a warning.
1765 context_->GetDiagnostics()->Warn(error_msg);
1766 return true;
1767 }
1768 context_->GetDiagnostics()->Error(error_msg);
1769 return false;
1770 };
1771 // If attr->compiled_value is not null, check if it is a ref
1772 if (attr->compiled_value) {
1773 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1774 if (ref == nullptr) {
1775 return true;
1776 }
1777 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1778 if (!shared_user_id_entry) {
1779 return true;
1780 }
1781 for (const auto& value : shared_user_id_entry->values) {
1782 const auto str_value = ValueCast<String>(value->value.get());
1783 if (str_value != nullptr && !validate(*str_value->value)) {
1784 return false;
1785 }
1786 }
1787 return true;
1788 }
1789
1790 // Fallback to checking the raw value
1791 return validate(attr->value);
1792 }
1793
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001794 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1795 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001796 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1797 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001798 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001799 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1800 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001801 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001802 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001803 if (!result) {
1804 return false;
1805 }
1806
Ryan Mitchelldba64562019-06-07 17:07:37 -07001807 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1808 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1809 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1810 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1811 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1812 // See (b/34829129)
1813 AliasAdaptiveIcon(manifest, table);
1814
Rhed Jao2c434422020-11-12 10:48:03 +08001815 // Verify the shared user id here to handle the case of reference value.
1816 if (!VerifySharedUserId(manifest, table)) {
1817 return false;
1818 }
1819
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 ResourceFileFlattenerOptions file_flattener_options;
1821 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001822 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1823 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001824 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001825 file_flattener_options.no_auto_version = options_.no_auto_version;
1826 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001827 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1829 file_flattener_options.update_proguard_spec =
1830 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001831 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001832 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001834 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001835 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001836 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001837 return false;
1838 }
1839
Adam Lesinski490595a2017-11-07 17:08:07 -08001840 // Hack to fix b/68820737.
1841 // We need to modify the ResourceTable's package name, but that should NOT affect
1842 // anything else being generated, which includes the Java classes.
1843 // If required, the package name is modifed before flattening, and then modified back
1844 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001845 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001846 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1847 // or higher] as invalid. In order to work around this limitation, we allow the use
1848 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1849 // definition of what a valid "split" package ID is to account for this.
1850 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1851 context_->GetPackageId() != kAppPackageId &&
1852 context_->GetPackageId() != kFrameworkPackageId)
1853 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001854 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001855 // The base APK is included, and this is a feature split. If the base package is
1856 // the same as this package, then we are building an old style Android Instant Apps feature
1857 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001858 if (!table->packages.empty() &&
1859 table->packages.back()->name == context_->GetCompilationPackage()) {
1860 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001861 std::string new_package_name =
1862 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001863 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001864
1865 if (context_->IsVerbose()) {
1866 context_->GetDiagnostics()->Note(
1867 DiagMessage() << "rewriting resource package name for feature split to '"
1868 << new_package_name << "'");
1869 }
1870 package_to_rewrite->name = new_package_name;
1871 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001873
1874 bool success = FlattenTable(table, options_.output_format, writer);
1875
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001876 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001877 // Change the name back.
1878 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001879
1880 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1881 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1882 // library, do not include a mapping from the feature package name to the feature package id
1883 // in the feature's dynamic reference table.
1884 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001885 }
1886
1887 if (!success) {
1888 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1889 }
1890 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001891 }
1892
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001893 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001894 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001895 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001896 std::unique_ptr<xml::XmlResource> manifest_xml =
1897 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1898 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001899 return 1;
1900 }
1901
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001902 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001903 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001904 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001905 const AppInfo& app_info = maybe_app_info.value();
1906 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001907 }
1908
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001909 // Determine the package name under which to merge resources.
1910 if (options_.rename_resources_package) {
1911 if (!options_.custom_java_package) {
1912 // Generate the R.java under the original package name instead of the package name specified
1913 // through --rename-resources-package.
1914 options_.custom_java_package = context_->GetCompilationPackage();
1915 }
1916 context_->SetCompilationPackage(options_.rename_resources_package.value());
1917 }
1918
Adam Lesinskic6284372017-12-04 13:46:23 -08001919 // Now that the compilation package is set, load the dependencies. This will also extract
1920 // the Android framework's versionCode and versionName, if they exist.
1921 if (!LoadSymbolsFromIncludePaths()) {
1922 return 1;
1923 }
1924
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001925 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1926 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001927 return 1;
1928 }
1929
Ryan Mitchell4382e442021-07-14 12:53:01 -07001930 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 return 1;
1934 }
1935
Adam Lesinski490595a2017-11-07 17:08:07 -08001936 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001937 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001938
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001939 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001940 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001941
1942 // Override the package ID when it is "android".
1943 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001944 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001945
1946 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001947 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001948 context_->GetDiagnostics()->Error(
1949 DiagMessage() << "package 'android' can only be built as a regular app");
1950 return 1;
1951 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 }
1953
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001954 TableMergerOptions table_merger_options;
1955 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001956 table_merger_options.override_styles_instead_of_overlaying =
1957 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001958 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001959 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001960
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001961 if (context_->IsVerbose()) {
1962 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001963 << StringPrintf("linking package '%s' using package ID %02x",
1964 context_->GetCompilationPackage().data(),
1965 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001966 }
1967
Adam Lesinski2427dce2017-11-30 15:10:28 -08001968 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1969 // in res/**/*.
1970 {
1971 XmlIdCollector collector;
1972 if (!collector.Consume(context_, manifest_xml.get())) {
1973 return false;
1974 }
1975
1976 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1977 return false;
1978 }
1979 }
1980
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 for (const std::string& input : input_files) {
1982 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001983 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001984 return 1;
1985 }
1986 }
1987
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 for (const std::string& input : options_.overlay_files) {
1989 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001990 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001991 return 1;
1992 }
1993 }
1994
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001995 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001996 return 1;
1997 }
1998
Adam Lesinskib522f042017-04-21 16:57:59 -07001999 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07002001 if (context_->GetPackageId() == kAndroidPackageId &&
2002 !mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002003 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004 return 1;
2005 }
2006
2007 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 IdAssigner id_assigner(&options_.stable_id_map);
2009 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002010 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 return 1;
2012 }
2013
2014 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 if (options_.resource_id_map_path) {
2016 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002017 for (auto& type : package->types) {
2018 for (auto& entry : type->entries) {
2019 ResourceName name(package->name, type->type, entry->name);
2020 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07002021 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002022 }
2023 }
2024 }
2025
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002026 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002027 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002028 return 1;
2029 }
2030 }
2031 } else {
2032 // Static libs are merged with other apps, and ID collisions are bad, so
2033 // verify that
2034 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036 return 1;
2037 }
2038 }
2039
2040 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002041 context_->SetNameManglerPolicy(
2042 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043
2044 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 context_->GetExternalSymbols()->PrependSource(
2046 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002047
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07002048 // Workaround for pre-O runtime that would treat negative resource IDs
2049 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
2050 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
2051 // are just identifiers.
2052 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
2053 if (context_->IsVerbose()) {
2054 context_->GetDiagnostics()->Note(DiagMessage()
2055 << "enabling pre-O feature split ID rewriting");
2056 }
2057 context_->GetExternalSymbols()->SetDelegate(
2058 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
2059 }
2060
Adam Lesinski34a16872018-02-23 16:18:10 -08002061 // Before we process anything, remove the resources whose default values don't exist.
2062 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02002063 if (!options_.no_resource_removal) {
2064 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
2065 context_->GetDiagnostics()->Error(DiagMessage()
2066 << "failed removing resources with no defaults");
2067 return 1;
2068 }
Adam Lesinski34a16872018-02-23 16:18:10 -08002069 }
2070
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002071 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002072 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002074 return 1;
2075 }
2076
Adam Lesinskib522f042017-04-21 16:57:59 -07002077 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002078 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002079 context_->GetDiagnostics()->Warn(DiagMessage()
2080 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002081 }
2082 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002083 ProductFilter product_filter(options_.products);
2084 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002085 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002086 return 1;
2087 }
2088 }
2089
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002091 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002093 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 return 1;
2095 }
2096 }
2097
Adam Lesinskib522f042017-04-21 16:57:59 -07002098 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002100 context_->GetDiagnostics()->Note(DiagMessage()
2101 << "collapsing resource versions for minimum SDK "
2102 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002103 }
2104
2105 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 return 1;
2108 }
2109 }
2110
Winson3c918b82019-01-25 14:25:37 -08002111 if (!options_.exclude_configs_.empty()) {
2112 std::vector<ConfigDescription> excluded_configs;
2113
2114 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002115 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002116 ConfigDescription config_description;
2117
2118 if (!ConfigDescription::Parse(config_string, &config_description)) {
2119 context_->GetDiagnostics()->Error(DiagMessage()
2120 << "failed to parse --excluded-configs "
2121 << config_string);
2122 return 1;
2123 }
2124
2125 excluded_configs.push_back(config_description);
2126 }
2127
2128 ResourceExcluder excluder(excluded_configs);
2129 if (!excluder.Consume(context_, &final_table_)) {
2130 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
2131 return 1;
2132 }
2133 }
2134
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002135 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002136 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002137 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002138 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002139 return 1;
2140 }
2141 }
2142
Adam Koskidc21dea2017-07-21 10:55:27 -07002143 proguard::KeepSet proguard_keep_set =
2144 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146
Adam Lesinskib522f042017-04-21 16:57:59 -07002147 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002149 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002150 context_->GetDiagnostics()->Warn(DiagMessage()
2151 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002152 }
2153 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002154 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2155 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002156 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002157 options_.split_constraints =
2158 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002159
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002160 if (origConstraintSize != options_.split_constraints.size()) {
2161 context_->GetDiagnostics()->Warn(DiagMessage()
2162 << "requested to split resources prior to min sdk of "
2163 << context_->GetMinSdkVersion());
2164 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002165 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002166 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002167 return 1;
2168 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002170
2171 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002172 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002173 auto split_constraints_iter = options_.split_constraints.begin();
2174 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002175 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002176 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2177 << "generating split with configurations '"
2178 << util::Joiner(split_constraints_iter->configs, ", ")
2179 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 }
2181
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002182 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002183 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002184 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185 return 1;
2186 }
2187
2188 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002190 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002191
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002192 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002193 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002194 context_->GetDiagnostics()->Error(DiagMessage()
2195 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002196 return 1;
2197 }
2198
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002199 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2200 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201 return 1;
2202 }
2203
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002204 ++path_iter;
2205 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002206 }
2207 }
2208
2209 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002210 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002211 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002212 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002213 return 1;
2214 }
2215
2216 bool error = false;
2217 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002218 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002219 // (aka, which package the AndroidManifest.xml is coming from).
2220 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002221 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002223 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002224 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002225 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002226 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002227 error = true;
2228 }
2229
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002230 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002231 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002232 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002233 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002234 }
2235
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002236 if (options_.generate_java_class_path) {
2237 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002238 error = true;
2239 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002240 }
2241
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002242 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002243 // PackageParser will fail if URIs are removed from
2244 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002245 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2246 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002247 error = true;
2248 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002249 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002250 } else {
2251 error = true;
2252 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002253 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002254
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002255 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002256 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002257 return 1;
2258 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002259
Josh Houd3bd4522022-02-14 10:24:42 +08002260 if (!VerifyLocaleFormat(manifest_xml.get(), context_->GetDiagnostics())) {
2261 return 1;
2262 };
2263
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002264 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2265 return 1;
2266 }
2267
2268 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002269 return 1;
2270 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002271
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002272 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002273 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002274 return 1;
2275 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002276 }
2277
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002278 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002279 return 1;
2280 }
2281
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002282 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2283 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002284 return 1;
2285 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002286 return 0;
2287 }
2288
2289 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002290 LinkOptions options_;
2291 LinkContext* context_;
2292 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002293
Adam Lesinski490595a2017-11-07 17:08:07 -08002294 AppInfo app_info_;
2295
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002296 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002297
2298 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002299 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002300
Adam Lesinski8780eb62017-10-31 17:44:39 -07002301 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002302 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002303 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002304
Adam Lesinski8780eb62017-10-31 17:44:39 -07002305 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2306 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2307
2308 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2309 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002310
2311 // The set of shared libraries being used, mapping their assigned package ID to package name.
2312 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002313
2314 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002315 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002316};
2317
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002318int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002319 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002320 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002321
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002322 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002323 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002324 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002325 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002326 const std::string path = arg.substr(1, arg.size() - 1);
2327 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002328 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2329 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002330 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002331 }
2332 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002333 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002334 }
2335 }
2336
2337 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002338 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002339 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002340 const std::string path = arg.substr(1, arg.size() - 1);
2341 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002342 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002343 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002344 return 1;
2345 }
2346 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002347 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002348 }
2349 }
2350
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002351 if (verbose_) {
2352 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002353 }
2354
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002355 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002356 context.GetDiagnostics()->Error(
2357 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002358 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002359 return 1;
2360 }
2361
Ryan Mitchell5855de72021-02-24 14:39:13 -08002362 if (shared_lib_ && options_.private_symbols) {
2363 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2364 // reference the private attribute within the styleable array will cause a link error because
2365 // the private attribute will not be emitted in the public R.java.
2366 context.GetDiagnostics()->Error(DiagMessage()
2367 << "--shared-lib cannot currently be used in combination with"
2368 << " --private-symbols");
2369 return 1;
2370 }
2371
Izabela Orlowska84febea2019-06-03 18:34:12 +01002372 if (options_.merge_only && !static_lib_) {
2373 context.GetDiagnostics()->Error(
2374 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2375 return 1;
2376 }
2377
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002378 // The default build type.
2379 context.SetPackageType(PackageType::kApp);
2380 context.SetPackageId(kAppPackageId);
2381
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002382 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002383 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002384 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002385 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002386 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002387 options_.output_format = OutputFormat::kProto;
2388 } else if (proto_format_) {
2389 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002390 }
2391
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002392 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002393 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002394 context.GetDiagnostics()->Error(
2395 DiagMessage() << "can't specify --package-id when not building a regular app");
2396 return 1;
2397 }
2398
Ryan Mitchell4382e442021-07-14 12:53:01 -07002399 const std::optional<uint32_t> maybe_package_id_int =
2400 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002401 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002402 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002403 << "' is not a valid integer");
2404 return 1;
2405 }
2406
2407 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002408 if (package_id_int > std::numeric_limits<uint8_t>::max()
2409 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002410 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002411 context.GetDiagnostics()->Error(
2412 DiagMessage() << StringPrintf(
2413 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2414 return 1;
2415 }
2416 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2417 }
2418
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002419 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002420 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002421 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002422 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002423 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002424 }
2425 }
2426
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002427 if (product_list_) {
2428 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002429 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002430 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002431 }
2432 }
2433 }
2434
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002435 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002436 if (!configs_.empty()) {
2437 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002438 if (filter == nullptr) {
2439 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002440 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002441 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002442 }
2443
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002444 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002445 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002446 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002447 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002448 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002449 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002450 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002451 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002452
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002453 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002454 for (const std::string& split_arg : split_args_) {
2455 options_.split_paths.push_back({});
2456 options_.split_constraints.push_back({});
2457 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2458 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002459 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002460 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002461 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002462
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002463 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2464 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2465 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002466 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002467 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002468 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002469
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002470 if (no_compress_regex) {
2471 std::string regex = no_compress_regex.value();
2472 if (util::StartsWith(regex, "@")) {
2473 const std::string path = regex.substr(1, regex.size() -1);
2474 std::string error;
2475 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2476 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2477 return 1;
2478 }
2479 } else {
2480 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2481 }
2482 }
2483
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002484 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002485 options_.extensions_to_not_compress.insert({
2486 // Image extensions
2487 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2488 // Audio extensions
2489 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2490 ".xmf", ".amr", ".awb",
2491 // Audio/video extensions
2492 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2493 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002494
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002495 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002496 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002497 options_.no_auto_version = true;
2498 options_.no_version_vectors = true;
2499 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002500 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002501
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002502 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002503 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002504}
2505
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002506} // namespace aapt