blob: ee6a764966f0f9349602ffdb636ae778831de995 [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.
210 if (name.type == ResourceType::kId && symbol->id) {
211 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;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100302 Maybe<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
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700465 XmlReferenceLinker xml_linker;
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
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700744 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
745 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) {
796 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
797 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) {
819 Maybe<std::string>& compile_sdk_version_codename =
820 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
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800915 Maybe<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")) {
940 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
941 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")) {
951 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
952 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")) {
963 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
964 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
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001060 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1061 if (options_.output_to_directory) {
1062 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001064 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 }
1066 }
1067
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001068 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001069 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001070 switch (format) {
1071 case OutputFormat::kApk: {
1072 BigBuffer buffer(1024);
1073 TableFlattener flattener(options_.table_flattener_options, &buffer);
1074 if (!flattener.Consume(context_, table)) {
1075 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1076 return false;
1077 }
1078
1079 io::BigBufferInputStream input_stream(&buffer);
1080 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1081 ArchiveEntry::kAlign, writer);
1082 } break;
1083
1084 case OutputFormat::kProto: {
1085 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001086 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1087 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001088 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1089 ArchiveEntry::kCompress, writer);
1090 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001091 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001092 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 }
1094
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001095 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001096 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001097 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001098 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001099 return true;
1100 }
1101
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001102 std::string out_path;
1103 std::unique_ptr<io::FileOutputStream> fout;
1104 if (options_.generate_java_class_path) {
1105 out_path = options_.generate_java_class_path.value();
1106 file::AppendPath(&out_path, file::PackageToPath(out_package));
1107 if (!file::mkdirs(out_path)) {
1108 context_->GetDiagnostics()->Error(DiagMessage()
1109 << "failed to create directory '" << out_path << "'");
1110 return false;
1111 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001113 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001115 fout = util::make_unique<io::FileOutputStream>(out_path);
1116 if (fout->HadError()) {
1117 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1118 << "': " << fout->GetError());
1119 return false;
1120 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121 }
1122
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001123 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001124 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001125 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1126 if (fout_text->HadError()) {
1127 context_->GetDiagnostics()->Error(DiagMessage()
1128 << "failed writing to '" << out_text_symbols_path.value()
1129 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001130 return false;
1131 }
1132 }
1133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001135 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001136 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001137 return false;
1138 }
1139
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 return true;
1141 }
1142
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001143 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001144 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001145 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1146 std::vector<std::string> packages_to_callback;
1147
1148 JavaClassGeneratorOptions template_options;
1149 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1150 template_options.javadoc_annotations = options_.javadoc_annotations;
1151
1152 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1153 template_options.use_final = false;
1154 }
1155
1156 if (context_->GetPackageType() == PackageType::kSharedLib) {
1157 template_options.use_final = false;
1158 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1159 }
1160
1161 const StringPiece actual_package = context_->GetCompilationPackage();
1162 StringPiece output_package = context_->GetCompilationPackage();
1163 if (options_.custom_java_package) {
1164 // Override the output java package to the custom one.
1165 output_package = options_.custom_java_package.value();
1166 }
1167
1168 // Generate the private symbols if required.
1169 if (options_.private_symbols) {
1170 packages_to_callback.push_back(options_.private_symbols.value());
1171
1172 // If we defined a private symbols package, we only emit Public symbols
1173 // to the original package, and private and public symbols to the private package.
1174 JavaClassGeneratorOptions options = template_options;
1175 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1176 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1177 options)) {
1178 return false;
1179 }
1180 }
1181
1182 // Generate copies of the original package R class but with different package names.
1183 // This is to support non-namespaced builds.
1184 for (const std::string& extra_package : options_.extra_java_packages) {
1185 packages_to_callback.push_back(extra_package);
1186
1187 JavaClassGeneratorOptions options = template_options;
1188 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1189 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1190 return false;
1191 }
1192 }
1193
1194 // Generate R classes for each package that was merged (static library).
1195 // Use the actual package's resources only.
1196 for (const std::string& package : table_merger_->merged_packages()) {
1197 packages_to_callback.push_back(package);
1198
1199 JavaClassGeneratorOptions options = template_options;
1200 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1201 if (!WriteJavaFile(&final_table_, package, package, options)) {
1202 return false;
1203 }
1204 }
1205
1206 // Generate the main public R class.
1207 JavaClassGeneratorOptions options = template_options;
1208
1209 // Only generate public symbols if we have a private package.
1210 if (options_.private_symbols) {
1211 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1212 }
1213
1214 if (options.rewrite_callback_options) {
1215 options.rewrite_callback_options.value().packages_to_callback =
1216 std::move(packages_to_callback);
1217 }
1218
1219 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1220 options_.generate_text_symbols_path)) {
1221 return false;
1222 }
1223
1224 return true;
1225 }
1226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001228 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001229 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001230 return true;
1231 }
1232
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001233 std::unique_ptr<ClassDefinition> manifest_class =
1234 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001236 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 // Something bad happened, but we already logged it, so exit.
1238 return false;
1239 }
1240
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001241 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 // Empty Manifest class, no need to generate it.
1243 return true;
1244 }
1245
1246 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 for (const std::string& annotation : options_.javadoc_annotations) {
1248 std::string proper_annotation = "@";
1249 proper_annotation += annotation;
1250 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251 }
1252
Adam Lesinski0d81f702017-06-27 15:51:09 -07001253 const std::string package_utf8 =
1254 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 std::string out_path = options_.generate_java_class_path.value();
1257 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001259 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001260 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1261 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 return false;
1263 }
1264
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001265 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001267 io::FileOutputStream fout(out_path);
1268 if (fout.HadError()) {
1269 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1270 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001271 return false;
1272 }
1273
Makoto Onukide6e6f22020-06-22 10:17:02 -07001274 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1275 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001276 fout.Flush();
1277
1278 if (fout.HadError()) {
1279 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1280 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 return false;
1282 }
1283 return true;
1284 }
1285
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001286 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001287 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 if (!out) {
1289 return true;
1290 }
1291
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001292 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001293 io::FileOutputStream fout(out_path);
1294 if (fout.HadError()) {
1295 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1296 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 return false;
1298 }
1299
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001300 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1301 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001302 fout.Flush();
1303
1304 if (fout.HadError()) {
1305 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1306 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 return false;
1308 }
1309 return true;
1310 }
1311
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001312 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001313 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001315 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001316 }
1317
Adam Lesinski8780eb62017-10-31 17:44:39 -07001318 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1319 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001320 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 return false;
1322 }
1323
Adam Lesinski8780eb62017-10-31 17:44:39 -07001324 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001325 if (table->packages.empty()) {
1326 return true;
1327 }
1328
1329 auto lib_package_result = GetStaticLibraryPackage(table);
1330 if (!lib_package_result.has_value()) {
1331 context_->GetDiagnostics()->Error(DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332 return false;
1333 }
1334
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001335 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001336 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001337 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001338 // Merge all resources as if they were in the compilation package. This is the old behavior
1339 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001341 // Add the package to the set of --extra-packages so we emit an R.java for each library
1342 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001344 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001345 }
1346
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001347 // Clear the package name, so as to make the resources look like they are coming from the
1348 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001349 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001350 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351
1352 } else {
1353 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001355 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 }
1357
1358 if (!result) {
1359 return false;
1360 }
1361
1362 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001363 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001364 return true;
1365 }
1366
Adam Lesinski2427dce2017-11-30 15:10:28 -08001367 bool MergeExportedSymbols(const Source& source,
1368 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001369 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001371 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001372 ResourceName res_name = exported_symbol.name;
1373 if (res_name.package.empty()) {
1374 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 }
1376
Adam Lesinski00451162017-10-03 07:44:08 -07001377 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001378 if (mangled_name) {
1379 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001380 }
1381
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001382 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001383 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001384 bool result = final_table_.AddResource(
1385 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1386 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001387 if (!result) {
1388 return false;
1389 }
1390 }
1391 return true;
1392 }
1393
Adam Lesinski2427dce2017-11-30 15:10:28 -08001394 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001395 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001396 if (context_->IsVerbose()) {
1397 context_->GetDiagnostics()->Note(DiagMessage()
1398 << "merging '" << compiled_file.name
1399 << "' from compiled file " << compiled_file.source);
1400 }
1401
1402 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1403 return false;
1404 }
1405 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1406 }
1407
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001408 // 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 -07001409 // If override is true, conflicting resources are allowed to override each other, in order of last
1410 // seen.
1411 // An io::IFileCollection is created from the ZIP file and added to the set of
1412 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001413 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001414 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001416 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 }
1418
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001421 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001423 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001424 return false;
1425 }
1426
1427 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001428 for (auto iter = collection->Iterator(); iter->HasNext();) {
1429 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001430 error = true;
1431 }
1432 }
1433
1434 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001435 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001436 return !error;
1437 }
1438
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001439 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001440 // conflicting resources are allowed to override each other, in order of last seen.
1441 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1442 // as ZIP archive and the files within are merged individually.
1443 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001444 bool MergePath(const std::string& path, bool override) {
1445 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1446 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1447 return MergeArchive(path, override);
1448 } else if (util::EndsWith(path, ".apk")) {
1449 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450 }
1451
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001452 io::IFile* file = file_collection_->InsertFile(path);
1453 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001454 }
1455
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001456 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001457 // If override is true, conflicting resources are allowed to override each other, in order of last
1458 // seen.
1459 // All other file types are ignored. This is because these files could be coming from a zip,
1460 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001461 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001462 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001463 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464
Adam Lesinski00451162017-10-03 07:44:08 -07001465 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001466 // Since AAPT compiles these file types and appends .flat to them, seeing
1467 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001468 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1469 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1470 << " file passed as argument. Must be "
1471 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001472 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001473 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1474 if (context_->IsVerbose()) {
1475 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1476 return true;
1477 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001478 }
1479
Adam Lesinski00451162017-10-03 07:44:08 -07001480 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1481 if (input_stream == nullptr) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1483 return false;
1484 }
1485
1486 if (input_stream->HadError()) {
1487 context_->GetDiagnostics()->Error(DiagMessage(src)
1488 << "failed to open file: " << input_stream->GetError());
1489 return false;
1490 }
1491
1492 ContainerReaderEntry* entry;
1493 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001494
1495 if (reader.HadError()) {
1496 context_->GetDiagnostics()->Error(DiagMessage(src)
1497 << "failed to read file: " << reader.GetError());
1498 return false;
1499 }
1500
Adam Lesinski00451162017-10-03 07:44:08 -07001501 while ((entry = reader.Next()) != nullptr) {
1502 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001503 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001504 pb::ResourceTable pb_table;
1505 if (!entry->GetResTable(&pb_table)) {
1506 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1507 << entry->GetError());
1508 return false;
1509 }
1510
1511 ResourceTable table;
1512 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001513 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001514 context_->GetDiagnostics()->Error(DiagMessage(src)
1515 << "failed to deserialize resource table: " << error);
1516 return false;
1517 }
1518
1519 if (!table_merger_->Merge(src, &table, override)) {
1520 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1521 return false;
1522 }
1523 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001524 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001525 pb::internal::CompiledFile pb_compiled_file;
1526 off64_t offset;
1527 size_t len;
1528 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1529 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1530 << entry->GetError());
1531 return false;
1532 }
1533
1534 ResourceFile resource_file;
1535 std::string error;
1536 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1537 context_->GetDiagnostics()->Error(DiagMessage(src)
1538 << "failed to read compiled header: " << error);
1539 return false;
1540 }
1541
1542 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1543 return false;
1544 }
1545 }
1546 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001547 return true;
1548 }
1549
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001550 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1551 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1552 for (const std::string& assets_dir : options_.assets_dirs) {
1553 Maybe<std::vector<std::string>> files =
1554 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1555 if (!files) {
1556 return false;
1557 }
1558
1559 for (const std::string& file : files.value()) {
1560 std::string full_key = "assets/" + file;
1561 std::string full_path = assets_dir;
1562 file::AppendPath(&full_path, file);
1563
1564 auto iter = merged_assets.find(full_key);
1565 if (iter == merged_assets.end()) {
1566 merged_assets.emplace(std::move(full_key),
1567 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1568 } else if (context_->IsVerbose()) {
1569 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1570 << "asset file overrides '" << full_path << "'");
1571 }
1572 }
1573 }
1574
1575 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001576 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001577 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1578 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001579 return false;
1580 }
1581 }
1582 return true;
1583 }
1584
Rhed Jao2c434422020-11-12 10:48:03 +08001585 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1586 Reference* reference) {
1587 if (!reference || !reference->name) {
1588 return nullptr;
1589 }
1590 auto name_ref = ResourceNameRef(reference->name.value());
1591 if (name_ref.package.empty()) {
1592 name_ref.package = context->GetCompilationPackage();
1593 }
1594 const auto search_result = table->FindResource(name_ref);
1595 if (!search_result) {
1596 return nullptr;
1597 }
1598 return search_result.value().entry;
1599 }
1600
Ryan Mitchelldba64562019-06-07 17:07:37 -07001601 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001602 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001603 if (!application) {
1604 return;
1605 }
1606
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001607 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1608 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001609 if (!icon || !round_icon) {
1610 return;
1611 }
1612
1613 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001614 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001615 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1616 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001617 return;
1618 }
1619
1620 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001621 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001622 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1623 ? config_value->config.sdkVersion : icon_max_sdk;
1624 }
1625 if (icon_max_sdk < SDK_O) {
1626 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1627 return;
1628 }
1629
1630 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001631 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001632 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1633 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001634 return;
1635 }
1636
1637 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001638 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001639 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1640 ? config_value->config.sdkVersion : round_icon_max_sdk;
1641 }
1642 if (round_icon_max_sdk >= SDK_O) {
1643 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1644 // not generate an alias to the icon drawable.
1645 return;
1646 }
1647
1648 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001649 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001650 if (config_value->config.sdkVersion < SDK_O) {
1651 continue;
1652 }
1653
1654 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1655 << round_icon_reference->name.value()
1656 << " with config \"" << config_value->config
1657 << "\" for round icon compatibility");
1658
1659 auto value = icon_reference->Clone(&table->string_pool);
Rhed Jao2c434422020-11-12 10:48:03 +08001660 auto round_config_value =
1661 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001662 round_config_value->value.reset(value);
1663 }
1664 }
1665
Rhed Jao2c434422020-11-12 10:48:03 +08001666 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1667 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1668 if (manifest_el == nullptr) {
1669 return true;
1670 }
1671 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1672 return true;
1673 }
1674 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1675 if (!attr) {
1676 return true;
1677 }
1678 const auto validate = [&](const std::string& shared_user_id) -> bool {
1679 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1680 return true;
1681 }
1682 DiagMessage error_msg(manifest_el->line_number);
1683 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1684 << shared_user_id << "'";
1685 if (options_.manifest_fixer_options.warn_validation) {
1686 // Treat the error only as a warning.
1687 context_->GetDiagnostics()->Warn(error_msg);
1688 return true;
1689 }
1690 context_->GetDiagnostics()->Error(error_msg);
1691 return false;
1692 };
1693 // If attr->compiled_value is not null, check if it is a ref
1694 if (attr->compiled_value) {
1695 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1696 if (ref == nullptr) {
1697 return true;
1698 }
1699 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1700 if (!shared_user_id_entry) {
1701 return true;
1702 }
1703 for (const auto& value : shared_user_id_entry->values) {
1704 const auto str_value = ValueCast<String>(value->value.get());
1705 if (str_value != nullptr && !validate(*str_value->value)) {
1706 return false;
1707 }
1708 }
1709 return true;
1710 }
1711
1712 // Fallback to checking the raw value
1713 return validate(attr->value);
1714 }
1715
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001716 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1717 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001718 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1719 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001720 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001721 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1722 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001723 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001724 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001725 if (!result) {
1726 return false;
1727 }
1728
Ryan Mitchelldba64562019-06-07 17:07:37 -07001729 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1730 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1731 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1732 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1733 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1734 // See (b/34829129)
1735 AliasAdaptiveIcon(manifest, table);
1736
Rhed Jao2c434422020-11-12 10:48:03 +08001737 // Verify the shared user id here to handle the case of reference value.
1738 if (!VerifySharedUserId(manifest, table)) {
1739 return false;
1740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 ResourceFileFlattenerOptions file_flattener_options;
1743 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001744 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1745 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001746 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001747 file_flattener_options.no_auto_version = options_.no_auto_version;
1748 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001749 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001750 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1751 file_flattener_options.update_proguard_spec =
1752 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001753 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001754 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001755
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001756 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001757 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001758 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001759 return false;
1760 }
1761
Adam Lesinski490595a2017-11-07 17:08:07 -08001762 // Hack to fix b/68820737.
1763 // We need to modify the ResourceTable's package name, but that should NOT affect
1764 // anything else being generated, which includes the Java classes.
1765 // If required, the package name is modifed before flattening, and then modified back
1766 // to its original name.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001767 std::optional<ResourceTablePackageView> package_to_rewrite;
Todd Kennedy32512992018-04-25 16:45:59 -07001768 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1769 // or higher] as invalid. In order to work around this limitation, we allow the use
1770 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1771 // definition of what a valid "split" package ID is to account for this.
1772 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1773 context_->GetPackageId() != kAppPackageId &&
1774 context_->GetPackageId() != kFrameworkPackageId)
1775 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1776 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001777 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1778 // The base APK is included, and this is a feature split. If the base package is
1779 // the same as this package, then we are building an old style Android Instant Apps feature
1780 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001781 auto table_view = table->GetPartitionedView();
1782 if (!table_view.packages.empty() &&
1783 table_view.packages.back().name == context_->GetCompilationPackage()) {
1784 package_to_rewrite = std::move(table_view.packages.back());
Adam Lesinski490595a2017-11-07 17:08:07 -08001785 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
Adam Lesinski490595a2017-11-07 17:08:07 -08001786 std::string new_package_name =
1787 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1788 app_info_.split_name.value_or_default("feature").c_str());
1789
1790 if (context_->IsVerbose()) {
1791 context_->GetDiagnostics()->Note(
1792 DiagMessage() << "rewriting resource package name for feature split to '"
1793 << new_package_name << "'");
1794 }
1795 package_to_rewrite->name = new_package_name;
1796 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001797 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001798
1799 bool success = FlattenTable(table, options_.output_format, writer);
1800
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001801 if (package_to_rewrite.has_value()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001802 // Change the name back.
1803 package_to_rewrite->name = context_->GetCompilationPackage();
1804 if (package_to_rewrite->id) {
1805 table->included_packages_.erase(package_to_rewrite->id.value());
1806 }
1807 }
1808
1809 if (!success) {
1810 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1811 }
1812 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001813 }
1814
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001815 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001816 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 std::unique_ptr<xml::XmlResource> manifest_xml =
1819 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1820 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 return 1;
1822 }
1823
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001824 // First extract the Package name without modifying it (via --rename-manifest-package).
1825 if (Maybe<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001826 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 const AppInfo& app_info = maybe_app_info.value();
1828 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 }
1830
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001831 // Determine the package name under which to merge resources.
1832 if (options_.rename_resources_package) {
1833 if (!options_.custom_java_package) {
1834 // Generate the R.java under the original package name instead of the package name specified
1835 // through --rename-resources-package.
1836 options_.custom_java_package = context_->GetCompilationPackage();
1837 }
1838 context_->SetCompilationPackage(options_.rename_resources_package.value());
1839 }
1840
Adam Lesinskic6284372017-12-04 13:46:23 -08001841 // Now that the compilation package is set, load the dependencies. This will also extract
1842 // the Android framework's versionCode and versionName, if they exist.
1843 if (!LoadSymbolsFromIncludePaths()) {
1844 return 1;
1845 }
1846
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1848 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 return 1;
1850 }
1851
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001852 Maybe<AppInfo> maybe_app_info =
1853 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001855 return 1;
1856 }
1857
Adam Lesinski490595a2017-11-07 17:08:07 -08001858 app_info_ = maybe_app_info.value();
1859 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001861 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001862 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001863
1864 // Override the package ID when it is "android".
1865 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001866 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001867
1868 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001869 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001870 context_->GetDiagnostics()->Error(
1871 DiagMessage() << "package 'android' can only be built as a regular app");
1872 return 1;
1873 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001874 }
1875
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 TableMergerOptions table_merger_options;
1877 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001878 table_merger_options.override_styles_instead_of_overlaying =
1879 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001880 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001881 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001883 if (context_->IsVerbose()) {
1884 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001885 << StringPrintf("linking package '%s' using package ID %02x",
1886 context_->GetCompilationPackage().data(),
1887 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001888 }
1889
Adam Lesinski2427dce2017-11-30 15:10:28 -08001890 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1891 // in res/**/*.
1892 {
1893 XmlIdCollector collector;
1894 if (!collector.Consume(context_, manifest_xml.get())) {
1895 return false;
1896 }
1897
1898 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1899 return false;
1900 }
1901 }
1902
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001903 for (const std::string& input : input_files) {
1904 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906 return 1;
1907 }
1908 }
1909
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 for (const std::string& input : options_.overlay_files) {
1911 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001913 return 1;
1914 }
1915 }
1916
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001917 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001918 return 1;
1919 }
1920
Adam Lesinskib522f042017-04-21 16:57:59 -07001921 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001923 if (context_->GetPackageId() == kAndroidPackageId &&
1924 !mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001925 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001926 return 1;
1927 }
1928
1929 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001930 IdAssigner id_assigner(&options_.stable_id_map);
1931 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001932 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 return 1;
1934 }
1935
1936 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001937 if (options_.resource_id_map_path) {
1938 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001939 for (auto& type : package->types) {
1940 for (auto& entry : type->entries) {
1941 ResourceName name(package->name, type->type, entry->name);
1942 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001943 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 }
1945 }
1946 }
1947
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001948 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001949 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001950 return 1;
1951 }
1952 }
1953 } else {
1954 // Static libs are merged with other apps, and ID collisions are bad, so
1955 // verify that
1956 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001958 return 1;
1959 }
1960 }
1961
1962 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001963 context_->SetNameManglerPolicy(
1964 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965
1966 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001967 context_->GetExternalSymbols()->PrependSource(
1968 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001969
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001970 // Workaround for pre-O runtime that would treat negative resource IDs
1971 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1972 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1973 // are just identifiers.
1974 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1975 if (context_->IsVerbose()) {
1976 context_->GetDiagnostics()->Note(DiagMessage()
1977 << "enabling pre-O feature split ID rewriting");
1978 }
1979 context_->GetExternalSymbols()->SetDelegate(
1980 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1981 }
1982
Adam Lesinski34a16872018-02-23 16:18:10 -08001983 // Before we process anything, remove the resources whose default values don't exist.
1984 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001985 if (!options_.no_resource_removal) {
1986 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1987 context_->GetDiagnostics()->Error(DiagMessage()
1988 << "failed removing resources with no defaults");
1989 return 1;
1990 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001991 }
1992
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001994 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001995 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
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 Lesinskice5e56e2016-10-21 17:56:45 -07002000 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002001 context_->GetDiagnostics()->Warn(DiagMessage()
2002 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002003 }
2004 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 ProductFilter product_filter(options_.products);
2006 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002007 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002008 return 1;
2009 }
2010 }
2011
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002012 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002013 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002015 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 return 1;
2017 }
2018 }
2019
Adam Lesinskib522f042017-04-21 16:57:59 -07002020 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002021 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002022 context_->GetDiagnostics()->Note(DiagMessage()
2023 << "collapsing resource versions for minimum SDK "
2024 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025 }
2026
2027 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 return 1;
2030 }
2031 }
2032
Winson3c918b82019-01-25 14:25:37 -08002033 if (!options_.exclude_configs_.empty()) {
2034 std::vector<ConfigDescription> excluded_configs;
2035
2036 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002037 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002038 ConfigDescription config_description;
2039
2040 if (!ConfigDescription::Parse(config_string, &config_description)) {
2041 context_->GetDiagnostics()->Error(DiagMessage()
2042 << "failed to parse --excluded-configs "
2043 << config_string);
2044 return 1;
2045 }
2046
2047 excluded_configs.push_back(config_description);
2048 }
2049
2050 ResourceExcluder excluder(excluded_configs);
2051 if (!excluder.Consume(context_, &final_table_)) {
2052 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
2053 return 1;
2054 }
2055 }
2056
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002057 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002058 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002059 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002060 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002061 return 1;
2062 }
2063 }
2064
Adam Koskidc21dea2017-07-21 10:55:27 -07002065 proguard::KeepSet proguard_keep_set =
2066 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002067 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002068
Adam Lesinskib522f042017-04-21 16:57:59 -07002069 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002070 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002071 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002072 context_->GetDiagnostics()->Warn(DiagMessage()
2073 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002074 }
2075 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002076 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2077 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002078 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002079 options_.split_constraints =
2080 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002081
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002082 if (origConstraintSize != options_.split_constraints.size()) {
2083 context_->GetDiagnostics()->Warn(DiagMessage()
2084 << "requested to split resources prior to min sdk of "
2085 << context_->GetMinSdkVersion());
2086 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002087 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002088 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002089 return 1;
2090 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002091 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092
2093 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002095 auto split_constraints_iter = options_.split_constraints.begin();
2096 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002097 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002098 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2099 << "generating split with configurations '"
2100 << util::Joiner(split_constraints_iter->configs, ", ")
2101 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 }
2103
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002104 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002106 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 return 1;
2108 }
2109
2110 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002111 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002112 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002113
2114 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002115 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002116 context_->GetDiagnostics()->Error(DiagMessage()
2117 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002118 return 1;
2119 }
2120
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002121 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2122 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 return 1;
2124 }
2125
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002126 ++path_iter;
2127 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002128 }
2129 }
2130
2131 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002132 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002133 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002134 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 return 1;
2136 }
2137
2138 bool error = false;
2139 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002140 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 // (aka, which package the AndroidManifest.xml is coming from).
2142 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002143 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002144
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 XmlReferenceLinker manifest_linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002146 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002147 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002148 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002149 error = true;
2150 }
2151
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002152 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002153 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002154 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002156 }
2157
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002158 if (options_.generate_java_class_path) {
2159 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160 error = true;
2161 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002162 }
2163
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002165 // PackageParser will fail if URIs are removed from
2166 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002167 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2168 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002169 error = true;
2170 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002171 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002172 } else {
2173 error = true;
2174 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002175 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002176
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002177 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002178 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002179 return 1;
2180 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002181
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002182 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2183 return 1;
2184 }
2185
2186 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002187 return 1;
2188 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002189
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002190 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002191 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002192 return 1;
2193 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002194 }
2195
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002196 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002197 return 1;
2198 }
2199
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002200 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2201 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002202 return 1;
2203 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002204 return 0;
2205 }
2206
2207 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002208 LinkOptions options_;
2209 LinkContext* context_;
2210 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002211
Adam Lesinski490595a2017-11-07 17:08:07 -08002212 AppInfo app_info_;
2213
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002214 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002215
2216 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002217 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002218
Adam Lesinski8780eb62017-10-31 17:44:39 -07002219 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002220 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002221 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222
Adam Lesinski8780eb62017-10-31 17:44:39 -07002223 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2224 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2225
2226 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2227 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002228
2229 // The set of shared libraries being used, mapping their assigned package ID to package name.
2230 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002231
2232 // The package name of the base application, if it is included.
2233 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002234};
2235
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002236int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002237 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002238 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002239
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002240 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002241 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002242 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002243 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002244 const std::string path = arg.substr(1, arg.size() - 1);
2245 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002246 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2247 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002248 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002249 }
2250 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002251 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002252 }
2253 }
2254
2255 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002256 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002257 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002258 const std::string path = arg.substr(1, arg.size() - 1);
2259 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002260 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002261 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002262 return 1;
2263 }
2264 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002265 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 }
2267 }
2268
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002269 if (verbose_) {
2270 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002271 }
2272
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002273 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002274 context.GetDiagnostics()->Error(
2275 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002276 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002277 return 1;
2278 }
2279
Ryan Mitchell5855de72021-02-24 14:39:13 -08002280 if (shared_lib_ && options_.private_symbols) {
2281 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2282 // reference the private attribute within the styleable array will cause a link error because
2283 // the private attribute will not be emitted in the public R.java.
2284 context.GetDiagnostics()->Error(DiagMessage()
2285 << "--shared-lib cannot currently be used in combination with"
2286 << " --private-symbols");
2287 return 1;
2288 }
2289
Izabela Orlowska84febea2019-06-03 18:34:12 +01002290 if (options_.merge_only && !static_lib_) {
2291 context.GetDiagnostics()->Error(
2292 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2293 return 1;
2294 }
2295
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002296 // The default build type.
2297 context.SetPackageType(PackageType::kApp);
2298 context.SetPackageId(kAppPackageId);
2299
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002300 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002301 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002302 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002303 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002304 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002305 options_.output_format = OutputFormat::kProto;
2306 } else if (proto_format_) {
2307 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002308 }
2309
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002310 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002311 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002312 context.GetDiagnostics()->Error(
2313 DiagMessage() << "can't specify --package-id when not building a regular app");
2314 return 1;
2315 }
2316
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002317 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002318 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002319 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002320 << "' is not a valid integer");
2321 return 1;
2322 }
2323
2324 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002325 if (package_id_int > std::numeric_limits<uint8_t>::max()
2326 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002327 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002328 context.GetDiagnostics()->Error(
2329 DiagMessage() << StringPrintf(
2330 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2331 return 1;
2332 }
2333 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2334 }
2335
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002336 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002337 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002338 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002339 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002340 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002341 }
2342 }
2343
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002344 if (product_list_) {
2345 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002346 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002347 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002348 }
2349 }
2350 }
2351
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002352 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002353 if (!configs_.empty()) {
2354 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002355 if (filter == nullptr) {
2356 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002357 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002358 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002359 }
2360
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002361 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002362 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002363 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002364 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002365 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002366 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002367 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002368 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002369
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002370 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002371 for (const std::string& split_arg : split_args_) {
2372 options_.split_paths.push_back({});
2373 options_.split_constraints.push_back({});
2374 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2375 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002376 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002377 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002378 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002379
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002380 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2381 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2382 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002383 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002384 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002385 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002386
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002387 if (no_compress_regex) {
2388 std::string regex = no_compress_regex.value();
2389 if (util::StartsWith(regex, "@")) {
2390 const std::string path = regex.substr(1, regex.size() -1);
2391 std::string error;
2392 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2393 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2394 return 1;
2395 }
2396 } else {
2397 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2398 }
2399 }
2400
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002401 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002402 options_.extensions_to_not_compress.insert({
2403 // Image extensions
2404 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2405 // Audio extensions
2406 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2407 ".xmf", ".amr", ".awb",
2408 // Audio/video extensions
2409 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2410 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002411
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002412 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002413 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002414 options_.no_auto_version = true;
2415 options_.no_version_vectors = true;
2416 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002417 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002418
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002419 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002420 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002421}
2422
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002423} // namespace aapt