blob: bf886c2f893faaef034f27261fbe947cc6e406db [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"
28#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080029#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020030#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080031#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070032
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "AppInfo.h"
34#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080037#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070038#include "ResourceValues.h"
39#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070041#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080042#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080043#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070045#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070046#include "format/binary/TableFlattener.h"
47#include "format/binary/XmlFlattener.h"
48#include "format/proto/ProtoDeserialize.h"
49#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070050#include "io/BigBufferStream.h"
51#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070053#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080054#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070055#include "java/JavaClassGenerator.h"
56#include "java/ManifestClassGenerator.h"
57#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080060#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080062#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070064#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080065#include "optimize/ResourceDeduper.h"
66#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "process/IResourceTableConsumer.h"
68#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080069#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080070#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080072#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020075using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070076using ::android::StringPiece;
77using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070078
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079namespace aapt {
80
Adam Lesinski64587af2016-02-18 18:33:06 -080081class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070082 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -080083 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +010084 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070085 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070086
Adam Lesinskib522f042017-04-21 16:57:59 -070087 PackageType GetPackageType() override {
88 return package_type_;
89 }
90
91 void SetPackageType(PackageType type) {
92 package_type_ = type;
93 }
94
Adam Lesinskid0f492d2017-04-03 18:12:45 -070095 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010096 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070098
Adam Lesinskid0f492d2017-04-03 18:12:45 -070099 NameMangler* GetNameMangler() override {
100 return &name_mangler_;
101 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
104 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700105 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800106
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 const std::string& GetCompilationPackage() override {
108 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700109 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700110
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800112 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700113 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800114
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700115 uint8_t GetPackageId() override {
116 return package_id_;
117 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700118
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700119 void SetPackageId(uint8_t id) {
120 package_id_ = id;
121 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800122
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700123 SymbolTable* GetExternalSymbols() override {
124 return &symbols_;
125 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800126
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700127 bool IsVerbose() override {
128 return verbose_;
129 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800130
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700131 void SetVerbose(bool val) {
132 verbose_ = val;
133 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800134
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700135 int GetMinSdkVersion() override {
136 return min_sdk_version_;
137 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700138
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700139 void SetMinSdkVersion(int minSdk) {
140 min_sdk_version_ = minSdk;
141 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700142
Udam Sainib228df32019-06-18 16:50:34 -0700143 const std::set<std::string>& GetSplitNameDependencies() override {
144 return split_name_dependencies_;
145 }
146
147 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
148 split_name_dependencies_ = split_name_dependencies;
149 }
150
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700151 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700152 DISALLOW_COPY_AND_ASSIGN(LinkContext);
153
Adam Lesinskib522f042017-04-21 16:57:59 -0700154 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100155 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700156 NameMangler name_mangler_;
157 std::string compilation_package_;
158 uint8_t package_id_ = 0x0;
159 SymbolTable symbols_;
160 bool verbose_ = false;
161 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700162 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700163};
164
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700165// A custom delegate that generates compatible pre-O IDs for use with feature splits.
166// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
167// is interpreted as a negative number. Some verification was wrongly assuming negative values
168// were invalid.
169//
170// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
171// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
172// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800173//
174// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700175class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
176 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800177 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700178 }
179
180 virtual ~FeatureSplitSymbolTableDelegate() = default;
181
182 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
183 const ResourceName& name,
184 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
185 std::unique_ptr<SymbolTable::Symbol> symbol =
186 DefaultSymbolTableDelegate::FindByName(name, sources);
187 if (symbol == nullptr) {
188 return {};
189 }
190
191 // Check to see if this is an 'id' with the target package.
192 if (name.type == ResourceType::kId && symbol->id) {
193 ResourceId* id = &symbol->id.value();
194 if (id->package_id() > kAppPackageId) {
195 // Rewrite the resource ID to be compatible pre-O.
196 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
197
198 // Check that this doesn't overlap another resource.
199 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
200 // The ID overlaps, so log a message (since this is a weird failure) and fail.
201 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
202 << " for pre-O feature split support");
203 return {};
204 }
205
206 if (context_->IsVerbose()) {
207 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
208 << ") -> (" << rewritten_id << ")");
209 }
210
211 *id = rewritten_id;
212 }
213 }
214 return symbol;
215 }
216
217 private:
218 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
219
220 IAaptContext* context_;
221};
222
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700223static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
224 const StringPiece& path, bool keep_raw_values, bool utf16,
225 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800226 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700227 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700228 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
229 << (keep_raw_values ? "true" : "false")
230 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700231 }
232
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700233 switch (format) {
234 case OutputFormat::kApk: {
235 BigBuffer buffer(1024);
236 XmlFlattenerOptions options = {};
237 options.keep_raw_values = keep_raw_values;
238 options.use_utf16 = utf16;
239 XmlFlattener flattener(&buffer, options);
240 if (!flattener.Consume(context, &xml_res)) {
241 return false;
242 }
243
244 io::BigBufferInputStream input_stream(&buffer);
245 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
246 ArchiveEntry::kCompress, writer);
247 } break;
248
249 case OutputFormat::kProto: {
250 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800251 // Strip whitespace text nodes from tha AndroidManifest.xml
252 SerializeXmlOptions options;
253 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700254 SerializeXmlResourceToPb(xml_res, &pb_node);
255 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
256 writer);
257 } break;
258 }
259 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800260}
261
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700262// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700263static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800264 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700265 FileInputStream fin(path);
266 if (fin.HadError()) {
267 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700268 return {};
269 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700270 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800271}
272
Adam Lesinski355f2852016-02-13 20:26:45 -0800273struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700274 bool no_auto_version = false;
275 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900276 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700277 bool no_xml_namespaces = false;
278 bool keep_raw_values = false;
279 bool do_not_compress_anything = false;
280 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100281 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700282 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700283 std::unordered_set<std::string> extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100284 Maybe<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800285};
286
Adam Lesinskic744ae82017-05-17 19:28:38 -0700287// A sampling of public framework resource IDs.
288struct R {
289 struct attr {
290 enum : uint32_t {
291 paddingLeft = 0x010100d6u,
292 paddingRight = 0x010100d8u,
293 paddingHorizontal = 0x0101053du,
294
295 paddingTop = 0x010100d7u,
296 paddingBottom = 0x010100d9u,
297 paddingVertical = 0x0101053eu,
298
299 layout_marginLeft = 0x010100f7u,
300 layout_marginRight = 0x010100f9u,
301 layout_marginHorizontal = 0x0101053bu,
302
303 layout_marginTop = 0x010100f8u,
304 layout_marginBottom = 0x010100fau,
305 layout_marginVertical = 0x0101053cu,
306 };
307 };
308};
309
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700310template <typename T>
311uint32_t GetCompressionFlags(const StringPiece& str, T options) {
312 if (options.do_not_compress_anything) {
313 return 0;
314 }
315
316 if (options.regex_to_not_compress
317 && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) {
318 return 0;
319 }
320
321 for (const std::string& extension : options.extensions_to_not_compress) {
322 if (util::EndsWith(str, extension)) {
323 return 0;
324 }
325 }
326 return ArchiveEntry::kCompress;
327}
328
Adam Lesinski355f2852016-02-13 20:26:45 -0800329class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700330 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700331 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700332 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800333
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700334 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800335
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700336 private:
337 struct FileOperation {
338 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700339
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700340 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700341 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700342
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700343 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700344 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700345
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700346 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700347 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700348
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700349 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700350 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700351 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800352
Adam Lesinskic744ae82017-05-17 19:28:38 -0700353 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
354 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800355
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700356 ResourceFileFlattenerOptions options_;
357 IAaptContext* context_;
358 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700359 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800360};
361
Adam Lesinskic744ae82017-05-17 19:28:38 -0700362ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
363 IAaptContext* context, proguard::KeepSet* keep_set)
364 : options_(options), context_(context), keep_set_(keep_set) {
365 SymbolTable* symm = context_->GetExternalSymbols();
366
367 // Build up the rules for degrading newer attributes to older ones.
368 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
369 // generated from the attribute definitions themselves (b/62028956).
370 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
371 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800372 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
373 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700374 };
375 rules_[R::attr::paddingHorizontal] =
376 util::make_unique<DegradeToManyRule>(std::move(replacements));
377 }
378
379 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
380 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800381 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
382 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700383 };
384 rules_[R::attr::paddingVertical] =
385 util::make_unique<DegradeToManyRule>(std::move(replacements));
386 }
387
388 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
389 std::vector<ReplacementAttr> replacements{
390 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800391 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700392 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800393 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 };
395 rules_[R::attr::layout_marginHorizontal] =
396 util::make_unique<DegradeToManyRule>(std::move(replacements));
397 }
398
399 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
400 std::vector<ReplacementAttr> replacements{
401 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800402 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700403 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800404 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700405 };
406 rules_[R::attr::layout_marginVertical] =
407 util::make_unique<DegradeToManyRule>(std::move(replacements));
408 }
409}
410
Adam Lesinskibb94f322017-07-12 07:41:55 -0700411static bool IsTransitionElement(const std::string& name) {
412 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
413 name == "changeImageTransform" || name == "changeTransform" ||
414 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
415 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
416 name == "transitionManager";
417}
418
419static bool IsVectorElement(const std::string& name) {
420 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800421 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
422 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700423}
424
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425template <typename T>
426std::vector<T> make_singleton_vec(T&& val) {
427 std::vector<T> vec;
428 vec.emplace_back(std::forward<T>(val));
429 return vec;
430}
431
432std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
433 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800434 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700436 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700437
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700438 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700439 context_->GetDiagnostics()->Note(DiagMessage()
440 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700441 }
442
Adam Lesinski00451162017-10-03 07:44:08 -0700443 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
444 // that existing projects have out-of-date references which pass compilation.
445 xml::StripAndroidStudioAttributes(doc->root.get());
446
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700447 XmlReferenceLinker xml_linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100448 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700449 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700450 }
451
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700452 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700453 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700454 }
455
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 if (options_.no_xml_namespaces) {
457 XmlNamespaceRemover namespace_remover;
458 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700459 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800460 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700461 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800462
Adam Lesinskibb94f322017-07-12 07:41:55 -0700463 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700464 return make_singleton_vec(std::move(file_op->xml_to_flatten));
465 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700466
Adam Lesinskibb94f322017-07-12 07:41:55 -0700467 if (options_.no_version_vectors || options_.no_version_transitions) {
468 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700469 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700470 if (el && el->namespace_uri.empty()) {
471 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
472 (options_.no_version_transitions && IsTransitionElement(el->name))) {
473 return make_singleton_vec(std::move(file_op->xml_to_flatten));
474 }
475 }
476 }
477
Adam Lesinskic744ae82017-05-17 19:28:38 -0700478 const ConfigDescription& config = file_op->config;
479 ResourceEntry* entry = file_op->entry;
480
481 XmlCompatVersioner xml_compat_versioner(&rules_);
482 const util::Range<ApiVersion> api_range{config.sdkVersion,
483 FindNextApiVersionForConfig(entry, config)};
484 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800485}
486
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800487ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
488 switch (format) {
489 case OutputFormat::kApk:
490 return ResourceFile::Type::kBinaryXml;
491 case OutputFormat::kProto:
492 return ResourceFile::Type::kProtoXml;
493 }
494 LOG_ALWAYS_FATAL("unreachable");
495 return ResourceFile::Type::kUnknown;
496}
497
Ryan Mitchell70f79722018-08-13 07:37:24 -0700498static auto kDrawableVersions = std::map<std::string, ApiVersion>{
499 { "adaptive-icon" , SDK_O },
500};
501
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700502bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800503 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700505 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800506
Adam Koskidc21dea2017-07-21 10:55:27 -0700507 proguard::CollectResourceReferences(context_, table, keep_set_);
508
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700509 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700510 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
511
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700512 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700513 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700514 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700515 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800516
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700517 // Populate the queue with all files in the ResourceTable.
518 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700519 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700520 // WARNING! Do not insert or remove any resources while executing in this scope. It will
521 // corrupt the iteration order.
522
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700523 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700524 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700525 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700526 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700527
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700528 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700530 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700531 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700532 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 }
534
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700535 FileOperation file_op;
536 file_op.entry = entry.get();
537 file_op.dst_path = *file_ref->path;
538 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700539 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700540
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700542 (file_ref->type == ResourceFile::Type::kBinaryXml ||
543 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700544 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700545 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 << "failed to open file");
548 return false;
549 }
550
Adam Lesinski00451162017-10-03 07:44:08 -0700551 if (file_ref->type == ResourceFile::Type::kProtoXml) {
552 pb::XmlNode pb_xml_node;
553 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
554 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700555 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700556 return false;
557 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558
Adam Lesinski00451162017-10-03 07:44:08 -0700559 std::string error;
560 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
561 if (file_op.xml_to_flatten == nullptr) {
562 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700563 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700564 return false;
565 }
566 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700567 std::string error_str;
568 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700569 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700570 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
571 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700572 return false;
573 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 }
575
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800576 // Update the type that this file will be written as.
577 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
578
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700579 file_op.xml_to_flatten->file.config = config_value->config;
580 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700581 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700582 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700583
584 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
585 // else we end up copying the string in the std::make_pair() method,
586 // then creating a StringPiece from the copy, which would cause us
587 // to end up referencing garbage in the map.
588 const StringPiece entry_name(entry->name);
589 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
590 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591 }
592 }
593
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700594 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700595 for (auto& map_entry : config_sorted_files) {
596 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700597 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700598
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700599 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700600 // Check minimum sdk versions supported for drawables
601 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
602 if (drawable_entry != kDrawableVersions.end()) {
603 if (drawable_entry->second > context_->GetMinSdkVersion()
604 && drawable_entry->second > config.sdkVersion) {
605 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
606 << "<" << drawable_entry->first << "> elements "
607 << "require a sdk version of at least "
608 << (int16_t) drawable_entry->second);
609 error = true;
610 continue;
611 }
612 }
613
Adam Lesinskic744ae82017-05-17 19:28:38 -0700614 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
615 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700616 if (versioned_docs.empty()) {
617 error = true;
618 continue;
619 }
620
Adam Lesinskic744ae82017-05-17 19:28:38 -0700621 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
622 std::string dst_path = file_op.dst_path;
623 if (doc->file.config != file_op.config) {
624 // Only add the new versioned configurations.
625 if (context_->IsVerbose()) {
626 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
627 << "auto-versioning resource from config '"
628 << config << "' -> '" << doc->file.config << "'");
629 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800631 const ResourceFile& file = doc->file;
632 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
633
634 std::unique_ptr<FileReference> file_ref =
635 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
636 file_ref->SetSource(doc->file.source);
637 // Update the output format of this XML file.
638 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
639 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
640 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700641 return false;
642 }
643 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700644
645 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
646 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700647 }
648 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700649 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700650 GetCompressionFlags(file_op.dst_path, options_),
651 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700652 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700654 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700655 }
656 return !error;
657}
658
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700659static bool WriteStableIdMapToPath(IDiagnostics* diag,
660 const std::unordered_map<ResourceName, ResourceId>& id_map,
661 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800662 io::FileOutputStream fout(id_map_path);
663 if (fout.HadError()) {
664 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700665 return false;
666 }
667
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800668 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700669 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 const ResourceName& name = entry.first;
671 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800672 printer.Print(name.to_string());
673 printer.Print(" = ");
674 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800676 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800678 if (fout.HadError()) {
679 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 return false;
681 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 return true;
683}
684
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700685static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
686 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700688 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700689 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 return false;
691 }
692
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700693 out_id_map->clear();
694 size_t line_no = 0;
695 for (StringPiece line : util::Tokenize(content, '\n')) {
696 line_no++;
697 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 if (line.empty()) {
699 continue;
700 }
701
702 auto iter = std::find(line.begin(), line.end(), '=');
703 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700704 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 return false;
706 }
707
708 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 StringPiece res_name_str =
710 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
711 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700712 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
713 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700714 return false;
715 }
716
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700717 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
718 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700719 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
722 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700723 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
724 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 return false;
726 }
727
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700728 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700729 }
730 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700731}
732
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800733static android::ApkAssetsCookie FindFrameworkAssetManagerCookie(
734 const android::AssetManager2& assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800735 using namespace android;
736
737 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
738 // we're looking for the first attribute resource in the system package.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800739 Res_value val{};
740 ResTable_config config{};
741 uint32_t type_spec_flags;
742 ApkAssetsCookie idx = assets.GetResource(0x01010000, true /** may_be_bag */,
743 0 /** density_override */, &val, &config,
744 &type_spec_flags);
Adam Lesinskic6284372017-12-04 13:46:23 -0800745
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800746 return idx;
Adam Lesinskic6284372017-12-04 13:46:23 -0800747}
748
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700749class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700750 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700751 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700752 : options_(options),
753 context_(context),
754 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700755 file_collection_(util::make_unique<io::FileCollection>()) {
756 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700757
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800758 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800759 using namespace android;
760
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800761 android::ApkAssetsCookie cookie = FindFrameworkAssetManagerCookie(*assets);
762 if (cookie == android::kInvalidCookie) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800763 // No Framework assets loaded. Not a failure.
764 return;
765 }
766
767 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800768 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800769 if (manifest == nullptr) {
770 // No errors.
771 return;
772 }
773
774 std::string error;
775 std::unique_ptr<xml::XmlResource> manifest_xml =
776 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
777 if (manifest_xml == nullptr) {
778 // No errors.
779 return;
780 }
781
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700782 if (!options_.manifest_fixer_options.compile_sdk_version) {
783 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
784 if (attr != nullptr) {
785 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
786 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
787 switch (prim->value.dataType) {
788 case Res_value::TYPE_INT_DEC:
789 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
790 break;
791 case Res_value::TYPE_INT_HEX:
792 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
793 break;
794 default:
795 break;
796 }
797 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
798 compile_sdk_version = *str->value;
799 } else {
800 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800801 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800802 }
803 }
804
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700805 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
806 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
807 if (attr != nullptr) {
808 Maybe<std::string>& compile_sdk_version_codename =
809 options_.manifest_fixer_options.compile_sdk_version_codename;
810 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
811 compile_sdk_version_codename = *str->value;
812 } else {
813 compile_sdk_version_codename = attr->value;
814 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800815 }
816 }
817 }
818
Adam Lesinski8780eb62017-10-31 17:44:39 -0700819 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800820 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700821 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800822 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700823 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700824 for (const std::string& path : options_.include_paths) {
825 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700826 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700827 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700828
Adam Lesinski8780eb62017-10-31 17:44:39 -0700829 std::string error;
830 auto zip_collection = io::ZipFileCollection::Create(path, &error);
831 if (zip_collection == nullptr) {
832 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
833 return false;
834 }
835
836 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
837 // Load this as a static library include.
838 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
839 Source(path), std::move(zip_collection), context_->GetDiagnostics());
840 if (static_apk == nullptr) {
841 return false;
842 }
843
Adam Lesinskib522f042017-04-21 16:57:59 -0700844 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800845 // Can't include static libraries when not building a static library (they have no IDs
846 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700847 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800848 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700849 return false;
850 }
851
Adam Lesinski8780eb62017-10-31 17:44:39 -0700852 ResourceTable* table = static_apk->GetResourceTable();
853
854 // If we are using --no-static-lib-packages, we need to rename the package of this table to
855 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700856 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800857 // Since package names can differ, and multiple packages can exist in a ResourceTable,
858 // we place the requirement that all static libraries are built with the package
859 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700860 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700861 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800862 } else {
863 context_->GetDiagnostics()->Error(DiagMessage(path)
864 << "no package with ID 0x7f found in static library");
865 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700866 }
867 }
868
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700869 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700870 util::make_unique<ResourceTableSymbolSource>(table));
871 static_library_includes_.push_back(std::move(static_apk));
872 } else {
873 if (!asset_source->AddAssetPath(path)) {
874 context_->GetDiagnostics()->Error(DiagMessage()
875 << "failed to load include path " << path);
876 return false;
877 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700878 }
879 }
880
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800881 // Capture the shared libraries so that the final resource table can be properly flattened
882 // with support for shared libraries.
883 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700884 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800885 // Capture the included base feature package.
886 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800887 } else if (entry.first == kFrameworkPackageId) {
888 // Try to embed which version of the framework we're compiling against.
889 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
890 // when linking our synthesized 'android:compileSdkVersion' attribute.
891 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
892 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
893 if (symbol != nullptr && symbol->is_public) {
894 // The symbol is present and public, extract the android:versionName and
895 // android:versionCode from the framework AndroidManifest.xml.
896 ExtractCompileSdkVersions(asset_source->GetAssetManager());
897 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700898 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700899 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800900 }
901 }
902
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700903 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 return true;
905 }
906
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800907 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800908 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700909 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800910 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
911 if (manifest_el == nullptr) {
912 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700913 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800914
915 AppInfo app_info;
916
917 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
918 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
919 return {};
920 }
921
922 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
923 if (!package_attr) {
924 diag->Error(DiagMessage(xml_res->file.source)
925 << "<manifest> must have a 'package' attribute");
926 return {};
927 }
928 app_info.package = package_attr->value;
929
930 if (xml::Attribute* version_code_attr =
931 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
932 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
933 if (!maybe_code) {
934 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
935 << "invalid android:versionCode '" << version_code_attr->value << "'");
936 return {};
937 }
938 app_info.version_code = maybe_code.value();
939 }
940
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700941 if (xml::Attribute* version_code_major_attr =
942 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
943 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
944 if (!maybe_code) {
945 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
946 << "invalid android:versionCodeMajor '"
947 << version_code_major_attr->value << "'");
948 return {};
949 }
950 app_info.version_code_major = maybe_code.value();
951 }
952
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800953 if (xml::Attribute* revision_code_attr =
954 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
955 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
956 if (!maybe_code) {
957 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
958 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
959 return {};
960 }
961 app_info.revision_code = maybe_code.value();
962 }
963
964 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
965 if (!split_name_attr->value.empty()) {
966 app_info.split_name = split_name_attr->value;
967 }
968 }
969
970 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
971 if (xml::Attribute* min_sdk =
972 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700973 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800974 }
975 }
Udam Sainib228df32019-06-18 16:50:34 -0700976
977 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
978 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
979 if (const xml::Attribute* split_name =
980 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
981 if (!split_name->value.empty()) {
982 app_info.split_name_dependencies.insert(split_name->value);
983 }
984 }
985 }
986 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800987 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700988 }
989
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700990 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
991 // Postcondition: ResourceTable has only one package left. All others are
992 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700993 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700994 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700995 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
996 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 };
998
999 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001000 for (const auto& package : final_table_.packages) {
1001 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002 // We have a package that is not related to the one we're building!
1003 for (const auto& type : package->types) {
1004 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001005 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001006
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001008 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001010 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1011 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1012 << "generated id '" << res_name
1013 << "' for external package '" << package->name
1014 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001015 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001016 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1017 << "defined resource '" << res_name
1018 << "' for external package '" << package->name
1019 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001020 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001022 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 }
1024 }
1025 }
1026 }
1027
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001028 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1029 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001030 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001031 return !error;
1032 }
1033
1034 /**
1035 * Returns true if no IDs have been set, false otherwise.
1036 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001037 bool VerifyNoIdsSet() {
1038 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 for (const auto& type : package->types) {
1040 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001041 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1042 << StringPrintf("%02x", type->id.value())
1043 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001044 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001045 }
1046
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);
1050 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001051 DiagMessage() << "entry " << res_name << " has ID "
1052 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001053 return false;
1054 }
1055 }
1056 }
1057 }
1058 return true;
1059 }
1060
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001061 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1062 if (options_.output_to_directory) {
1063 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001064 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001065 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001066 }
1067 }
1068
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001069 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001070 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001071 switch (format) {
1072 case OutputFormat::kApk: {
1073 BigBuffer buffer(1024);
1074 TableFlattener flattener(options_.table_flattener_options, &buffer);
1075 if (!flattener.Consume(context_, table)) {
1076 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1077 return false;
1078 }
1079
1080 io::BigBufferInputStream input_stream(&buffer);
1081 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1082 ArchiveEntry::kAlign, writer);
1083 } break;
1084
1085 case OutputFormat::kProto: {
1086 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001087 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1088 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001089 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1090 ArchiveEntry::kCompress, writer);
1091 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001092 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001093 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001094 }
1095
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001096 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001097 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001098 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001099 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001100 return true;
1101 }
1102
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001103 std::string out_path;
1104 std::unique_ptr<io::FileOutputStream> fout;
1105 if (options_.generate_java_class_path) {
1106 out_path = options_.generate_java_class_path.value();
1107 file::AppendPath(&out_path, file::PackageToPath(out_package));
1108 if (!file::mkdirs(out_path)) {
1109 context_->GetDiagnostics()->Error(DiagMessage()
1110 << "failed to create directory '" << out_path << "'");
1111 return false;
1112 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001113
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001114 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001116 fout = util::make_unique<io::FileOutputStream>(out_path);
1117 if (fout->HadError()) {
1118 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1119 << "': " << fout->GetError());
1120 return false;
1121 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001122 }
1123
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001124 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001125 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001126 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1127 if (fout_text->HadError()) {
1128 context_->GetDiagnostics()->Error(DiagMessage()
1129 << "failed writing to '" << out_text_symbols_path.value()
1130 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001131 return false;
1132 }
1133 }
1134
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001135 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001136 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001137 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138 return false;
1139 }
1140
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141 return true;
1142 }
1143
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001144 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001145 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001146 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1147 std::vector<std::string> packages_to_callback;
1148
1149 JavaClassGeneratorOptions template_options;
1150 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1151 template_options.javadoc_annotations = options_.javadoc_annotations;
1152
1153 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1154 template_options.use_final = false;
1155 }
1156
1157 if (context_->GetPackageType() == PackageType::kSharedLib) {
1158 template_options.use_final = false;
1159 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1160 }
1161
1162 const StringPiece actual_package = context_->GetCompilationPackage();
1163 StringPiece output_package = context_->GetCompilationPackage();
1164 if (options_.custom_java_package) {
1165 // Override the output java package to the custom one.
1166 output_package = options_.custom_java_package.value();
1167 }
1168
1169 // Generate the private symbols if required.
1170 if (options_.private_symbols) {
1171 packages_to_callback.push_back(options_.private_symbols.value());
1172
1173 // If we defined a private symbols package, we only emit Public symbols
1174 // to the original package, and private and public symbols to the private package.
1175 JavaClassGeneratorOptions options = template_options;
1176 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1177 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1178 options)) {
1179 return false;
1180 }
1181 }
1182
1183 // Generate copies of the original package R class but with different package names.
1184 // This is to support non-namespaced builds.
1185 for (const std::string& extra_package : options_.extra_java_packages) {
1186 packages_to_callback.push_back(extra_package);
1187
1188 JavaClassGeneratorOptions options = template_options;
1189 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1190 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1191 return false;
1192 }
1193 }
1194
1195 // Generate R classes for each package that was merged (static library).
1196 // Use the actual package's resources only.
1197 for (const std::string& package : table_merger_->merged_packages()) {
1198 packages_to_callback.push_back(package);
1199
1200 JavaClassGeneratorOptions options = template_options;
1201 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1202 if (!WriteJavaFile(&final_table_, package, package, options)) {
1203 return false;
1204 }
1205 }
1206
1207 // Generate the main public R class.
1208 JavaClassGeneratorOptions options = template_options;
1209
1210 // Only generate public symbols if we have a private package.
1211 if (options_.private_symbols) {
1212 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1213 }
1214
1215 if (options.rewrite_callback_options) {
1216 options.rewrite_callback_options.value().packages_to_callback =
1217 std::move(packages_to_callback);
1218 }
1219
1220 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1221 options_.generate_text_symbols_path)) {
1222 return false;
1223 }
1224
1225 return true;
1226 }
1227
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001228 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001229 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001230 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001231 return true;
1232 }
1233
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001234 std::unique_ptr<ClassDefinition> manifest_class =
1235 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001237 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001238 // Something bad happened, but we already logged it, so exit.
1239 return false;
1240 }
1241
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001242 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 // Empty Manifest class, no need to generate it.
1244 return true;
1245 }
1246
1247 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001248 for (const std::string& annotation : options_.javadoc_annotations) {
1249 std::string proper_annotation = "@";
1250 proper_annotation += annotation;
1251 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001252 }
1253
Adam Lesinski0d81f702017-06-27 15:51:09 -07001254 const std::string package_utf8 =
1255 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001256
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 std::string out_path = options_.generate_java_class_path.value();
1258 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001260 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001261 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1262 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001263 return false;
1264 }
1265
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001266 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001267
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001268 io::FileOutputStream fout(out_path);
1269 if (fout.HadError()) {
1270 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1271 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001272 return false;
1273 }
1274
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001275 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1276 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();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001325 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001326 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001327 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001328 return false;
1329 }
1330
1331 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001332 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001333 // Merge all resources as if they were in the compilation package. This is the old behavior
1334 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001336 // Add the package to the set of --extra-packages so we emit an R.java for each library
1337 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001338 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001339 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340 }
1341
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001342 // Clear the package name, so as to make the resources look like they are coming from the
1343 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001345 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346
1347 } else {
1348 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001349 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001350 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351 }
1352
1353 if (!result) {
1354 return false;
1355 }
1356
1357 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001358 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359 return true;
1360 }
1361
Adam Lesinski2427dce2017-11-30 15:10:28 -08001362 bool MergeExportedSymbols(const Source& source,
1363 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001364 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001365 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001366 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001367 ResourceName res_name = exported_symbol.name;
1368 if (res_name.package.empty()) {
1369 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370 }
1371
Adam Lesinski00451162017-10-03 07:44:08 -07001372 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001373 if (mangled_name) {
1374 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 }
1376
1377 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001378 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001379 bool result =
1380 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1381 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382 if (!result) {
1383 return false;
1384 }
1385 }
1386 return true;
1387 }
1388
Adam Lesinski2427dce2017-11-30 15:10:28 -08001389 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001390 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001391 if (context_->IsVerbose()) {
1392 context_->GetDiagnostics()->Note(DiagMessage()
1393 << "merging '" << compiled_file.name
1394 << "' from compiled file " << compiled_file.source);
1395 }
1396
1397 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1398 return false;
1399 }
1400 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1401 }
1402
Adam Lesinski00451162017-10-03 07:44:08 -07001403 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1404 // If override is true, conflicting resources are allowed to override each other, in order of last
1405 // seen.
1406 // An io::IFileCollection is created from the ZIP file and added to the set of
1407 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001408 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001409 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001411 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001412 }
1413
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001415 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001416 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001419 return false;
1420 }
1421
1422 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001423 for (auto iter = collection->Iterator(); iter->HasNext();) {
1424 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001425 error = true;
1426 }
1427 }
1428
1429 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001430 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001431 return !error;
1432 }
1433
Adam Lesinski00451162017-10-03 07:44:08 -07001434 // Takes a path to load and merge into the master ResourceTable. If override is true,
1435 // conflicting resources are allowed to override each other, in order of last seen.
1436 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1437 // as ZIP archive and the files within are merged individually.
1438 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001439 bool MergePath(const std::string& path, bool override) {
1440 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1441 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1442 return MergeArchive(path, override);
1443 } else if (util::EndsWith(path, ".apk")) {
1444 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001445 }
1446
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001447 io::IFile* file = file_collection_->InsertFile(path);
1448 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001449 }
1450
Adam Lesinski00451162017-10-03 07:44:08 -07001451 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1452 // If override is true, conflicting resources are allowed to override each other, in order of last
1453 // seen.
1454 // All other file types are ignored. This is because these files could be coming from a zip,
1455 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001456 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001457 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001458 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001459
Adam Lesinski00451162017-10-03 07:44:08 -07001460 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001461 // Since AAPT compiles these file types and appends .flat to them, seeing
1462 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001463 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1464 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1465 << " file passed as argument. Must be "
1466 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001467 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001468 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1469 if (context_->IsVerbose()) {
1470 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1471 return true;
1472 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 }
1474
Adam Lesinski00451162017-10-03 07:44:08 -07001475 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1476 if (input_stream == nullptr) {
1477 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1478 return false;
1479 }
1480
1481 if (input_stream->HadError()) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src)
1483 << "failed to open file: " << input_stream->GetError());
1484 return false;
1485 }
1486
1487 ContainerReaderEntry* entry;
1488 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001489
1490 if (reader.HadError()) {
1491 context_->GetDiagnostics()->Error(DiagMessage(src)
1492 << "failed to read file: " << reader.GetError());
1493 return false;
1494 }
1495
Adam Lesinski00451162017-10-03 07:44:08 -07001496 while ((entry = reader.Next()) != nullptr) {
1497 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001498 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001499 pb::ResourceTable pb_table;
1500 if (!entry->GetResTable(&pb_table)) {
1501 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1502 << entry->GetError());
1503 return false;
1504 }
1505
1506 ResourceTable table;
1507 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001508 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001509 context_->GetDiagnostics()->Error(DiagMessage(src)
1510 << "failed to deserialize resource table: " << error);
1511 return false;
1512 }
1513
1514 if (!table_merger_->Merge(src, &table, override)) {
1515 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1516 return false;
1517 }
1518 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001519 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001520 pb::internal::CompiledFile pb_compiled_file;
1521 off64_t offset;
1522 size_t len;
1523 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1524 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1525 << entry->GetError());
1526 return false;
1527 }
1528
1529 ResourceFile resource_file;
1530 std::string error;
1531 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1532 context_->GetDiagnostics()->Error(DiagMessage(src)
1533 << "failed to read compiled header: " << error);
1534 return false;
1535 }
1536
1537 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1538 return false;
1539 }
1540 }
1541 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001542 return true;
1543 }
1544
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001545 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1546 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1547 for (const std::string& assets_dir : options_.assets_dirs) {
1548 Maybe<std::vector<std::string>> files =
1549 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1550 if (!files) {
1551 return false;
1552 }
1553
1554 for (const std::string& file : files.value()) {
1555 std::string full_key = "assets/" + file;
1556 std::string full_path = assets_dir;
1557 file::AppendPath(&full_path, file);
1558
1559 auto iter = merged_assets.find(full_key);
1560 if (iter == merged_assets.end()) {
1561 merged_assets.emplace(std::move(full_key),
1562 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1563 } else if (context_->IsVerbose()) {
1564 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1565 << "asset file overrides '" << full_path << "'");
1566 }
1567 }
1568 }
1569
1570 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001571 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001572 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1573 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001574 return false;
1575 }
1576 }
1577 return true;
1578 }
1579
Ryan Mitchelldba64562019-06-07 17:07:37 -07001580 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
1581 xml::Element* application = manifest->root->FindChild("", "application");
1582 if (!application) {
1583 return;
1584 }
1585
1586 xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1587 xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
1588 if (!icon || !round_icon) {
1589 return;
1590 }
1591
1592 // Find the icon resource defined within the application.
1593 auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
1594 if (!icon_reference || !icon_reference->name) {
1595 return;
1596 }
1597 auto package = table->FindPackageById(icon_reference->id.value().package_id());
1598 if (!package) {
1599 return;
1600 }
1601 auto type = package->FindType(icon_reference->name.value().type);
1602 if (!type) {
1603 return;
1604 }
1605 auto icon_entry = type->FindEntry(icon_reference->name.value().entry);
1606 if (!icon_entry) {
1607 return;
1608 }
1609
1610 int icon_max_sdk = 0;
1611 for (auto& config_value : icon_entry->values) {
1612 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1613 ? config_value->config.sdkVersion : icon_max_sdk;
1614 }
1615 if (icon_max_sdk < SDK_O) {
1616 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1617 return;
1618 }
1619
1620 // Find the roundIcon resource defined within the application.
1621 auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
1622 if (!round_icon_reference || !round_icon_reference->name) {
1623 return;
1624 }
1625 package = table->FindPackageById(round_icon_reference->id.value().package_id());
1626 if (!package) {
1627 return;
1628 }
1629 type = package->FindType(round_icon_reference->name.value().type);
1630 if (!type) {
1631 return;
1632 }
1633 auto round_icon_entry = type->FindEntry(round_icon_reference->name.value().entry);
1634 if (!round_icon_entry) {
1635 return;
1636 }
1637
1638 int round_icon_max_sdk = 0;
1639 for (auto& config_value : round_icon_entry->values) {
1640 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1641 ? config_value->config.sdkVersion : round_icon_max_sdk;
1642 }
1643 if (round_icon_max_sdk >= SDK_O) {
1644 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1645 // not generate an alias to the icon drawable.
1646 return;
1647 }
1648
1649 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
1650 for (auto& config_value : icon_entry->values) {
1651 if (config_value->config.sdkVersion < SDK_O) {
1652 continue;
1653 }
1654
1655 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1656 << round_icon_reference->name.value()
1657 << " with config \"" << config_value->config
1658 << "\" for round icon compatibility");
1659
1660 auto value = icon_reference->Clone(&table->string_pool);
1661 auto round_config_value = round_icon_entry->FindOrCreateValue(
1662 config_value->config, config_value->product);
1663 round_config_value->value.reset(value);
1664 }
1665 }
1666
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001667 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1668 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001669 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1670 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001671 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001672 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1673 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001674 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001675 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001676 if (!result) {
1677 return false;
1678 }
1679
Ryan Mitchelldba64562019-06-07 17:07:37 -07001680 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1681 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1682 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1683 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1684 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1685 // See (b/34829129)
1686 AliasAdaptiveIcon(manifest, table);
1687
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001688 ResourceFileFlattenerOptions file_flattener_options;
1689 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001690 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1691 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001692 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 file_flattener_options.no_auto_version = options_.no_auto_version;
1694 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001695 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001696 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1697 file_flattener_options.update_proguard_spec =
1698 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001699 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001700 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001701
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001702 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001703 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001704 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001705 return false;
1706 }
1707
Adam Lesinski490595a2017-11-07 17:08:07 -08001708 // Hack to fix b/68820737.
1709 // We need to modify the ResourceTable's package name, but that should NOT affect
1710 // anything else being generated, which includes the Java classes.
1711 // If required, the package name is modifed before flattening, and then modified back
1712 // to its original name.
1713 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001714 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1715 // or higher] as invalid. In order to work around this limitation, we allow the use
1716 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1717 // definition of what a valid "split" package ID is to account for this.
1718 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1719 context_->GetPackageId() != kAppPackageId &&
1720 context_->GetPackageId() != kFrameworkPackageId)
1721 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1722 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001723 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1724 // The base APK is included, and this is a feature split. If the base package is
1725 // the same as this package, then we are building an old style Android Instant Apps feature
1726 // split and must apply this workaround to avoid requiring namespaces support.
1727 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1728 if (package_to_rewrite != nullptr) {
1729 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1730
1731 std::string new_package_name =
1732 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1733 app_info_.split_name.value_or_default("feature").c_str());
1734
1735 if (context_->IsVerbose()) {
1736 context_->GetDiagnostics()->Note(
1737 DiagMessage() << "rewriting resource package name for feature split to '"
1738 << new_package_name << "'");
1739 }
1740 package_to_rewrite->name = new_package_name;
1741 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001742 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001743
1744 bool success = FlattenTable(table, options_.output_format, writer);
1745
1746 if (package_to_rewrite != nullptr) {
1747 // Change the name back.
1748 package_to_rewrite->name = context_->GetCompilationPackage();
1749 if (package_to_rewrite->id) {
1750 table->included_packages_.erase(package_to_rewrite->id.value());
1751 }
1752 }
1753
1754 if (!success) {
1755 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1756 }
1757 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 }
1759
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001760 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001761 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001762 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001763 std::unique_ptr<xml::XmlResource> manifest_xml =
1764 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1765 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001766 return 1;
1767 }
1768
Ryan Mitchell60b74fb2020-02-26 12:45:39 -08001769 // Determine the package name under which to merge resources.
1770 if (options_.rename_resources_package) {
1771 context_->SetCompilationPackage(options_.rename_resources_package.value());
1772 } else if (Maybe<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001773 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Ryan Mitchell60b74fb2020-02-26 12:45:39 -08001774 // Extract the package name from the manifest ignoring the value of --rename-manifest-package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001775 const AppInfo& app_info = maybe_app_info.value();
1776 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001777 }
1778
Adam Lesinskic6284372017-12-04 13:46:23 -08001779 // Now that the compilation package is set, load the dependencies. This will also extract
1780 // the Android framework's versionCode and versionName, if they exist.
1781 if (!LoadSymbolsFromIncludePaths()) {
1782 return 1;
1783 }
1784
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001785 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1786 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001787 return 1;
1788 }
1789
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001790 Maybe<AppInfo> maybe_app_info =
1791 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001792 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001793 return 1;
1794 }
1795
Adam Lesinski490595a2017-11-07 17:08:07 -08001796 app_info_ = maybe_app_info.value();
1797 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001799 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001800 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001801
1802 // Override the package ID when it is "android".
1803 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001804 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001805
1806 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001807 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001808 context_->GetDiagnostics()->Error(
1809 DiagMessage() << "package 'android' can only be built as a regular app");
1810 return 1;
1811 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001812 }
1813
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001814 TableMergerOptions table_merger_options;
1815 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001816 table_merger_options.override_styles_instead_of_overlaying =
1817 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001818 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001819 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001821 if (context_->IsVerbose()) {
1822 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001823 << StringPrintf("linking package '%s' using package ID %02x",
1824 context_->GetCompilationPackage().data(),
1825 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 }
1827
Adam Lesinski2427dce2017-11-30 15:10:28 -08001828 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1829 // in res/**/*.
1830 {
1831 XmlIdCollector collector;
1832 if (!collector.Consume(context_, manifest_xml.get())) {
1833 return false;
1834 }
1835
1836 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1837 return false;
1838 }
1839 }
1840
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 for (const std::string& input : input_files) {
1842 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001843 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001844 return 1;
1845 }
1846 }
1847
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001848 for (const std::string& input : options_.overlay_files) {
1849 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001850 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001851 return 1;
1852 }
1853 }
1854
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001855 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856 return 1;
1857 }
1858
Adam Lesinskib522f042017-04-21 16:57:59 -07001859 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001862 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863 return 1;
1864 }
1865
1866 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001867 IdAssigner id_assigner(&options_.stable_id_map);
1868 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001869 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870 return 1;
1871 }
1872
1873 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001874 if (options_.resource_id_map_path) {
1875 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001876 for (auto& type : package->types) {
1877 for (auto& entry : type->entries) {
1878 ResourceName name(package->name, type->type, entry->name);
1879 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001880 options_.stable_id_map[std::move(name)] =
1881 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882 }
1883 }
1884 }
1885
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001886 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001888 return 1;
1889 }
1890 }
1891 } else {
1892 // Static libs are merged with other apps, and ID collisions are bad, so
1893 // verify that
1894 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 return 1;
1897 }
1898 }
1899
1900 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001901 context_->SetNameManglerPolicy(
1902 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903
1904 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001905 context_->GetExternalSymbols()->PrependSource(
1906 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001907
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001908 // Workaround for pre-O runtime that would treat negative resource IDs
1909 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1910 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1911 // are just identifiers.
1912 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1913 if (context_->IsVerbose()) {
1914 context_->GetDiagnostics()->Note(DiagMessage()
1915 << "enabling pre-O feature split ID rewriting");
1916 }
1917 context_->GetExternalSymbols()->SetDelegate(
1918 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1919 }
1920
Adam Lesinski34a16872018-02-23 16:18:10 -08001921 // Before we process anything, remove the resources whose default values don't exist.
1922 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001923 if (!options_.no_resource_removal) {
1924 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1925 context_->GetDiagnostics()->Error(DiagMessage()
1926 << "failed removing resources with no defaults");
1927 return 1;
1928 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001929 }
1930
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001931 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001932 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001933 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 return 1;
1935 }
1936
Adam Lesinskib522f042017-04-21 16:57:59 -07001937 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001939 context_->GetDiagnostics()->Warn(DiagMessage()
1940 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001941 }
1942 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 ProductFilter product_filter(options_.products);
1944 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001945 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001946 return 1;
1947 }
1948 }
1949
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001952 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001953 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001954 return 1;
1955 }
1956 }
1957
Adam Lesinskib522f042017-04-21 16:57:59 -07001958 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001959 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001960 context_->GetDiagnostics()->Note(DiagMessage()
1961 << "collapsing resource versions for minimum SDK "
1962 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001963 }
1964
1965 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001966 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 return 1;
1968 }
1969 }
1970
Winson3c918b82019-01-25 14:25:37 -08001971 if (!options_.exclude_configs_.empty()) {
1972 std::vector<ConfigDescription> excluded_configs;
1973
1974 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001975 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08001976 ConfigDescription config_description;
1977
1978 if (!ConfigDescription::Parse(config_string, &config_description)) {
1979 context_->GetDiagnostics()->Error(DiagMessage()
1980 << "failed to parse --excluded-configs "
1981 << config_string);
1982 return 1;
1983 }
1984
1985 excluded_configs.push_back(config_description);
1986 }
1987
1988 ResourceExcluder excluder(excluded_configs);
1989 if (!excluder.Consume(context_, &final_table_)) {
1990 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
1991 return 1;
1992 }
1993 }
1994
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001995 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001996 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001997 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001998 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001999 return 1;
2000 }
2001 }
2002
Adam Koskidc21dea2017-07-21 10:55:27 -07002003 proguard::KeepSet proguard_keep_set =
2004 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006
Adam Lesinskib522f042017-04-21 16:57:59 -07002007 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002009 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002010 context_->GetDiagnostics()->Warn(DiagMessage()
2011 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 }
2013 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002014 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2015 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002016 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002017 options_.split_constraints =
2018 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002019
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002020 if (origConstraintSize != options_.split_constraints.size()) {
2021 context_->GetDiagnostics()->Warn(DiagMessage()
2022 << "requested to split resources prior to min sdk of "
2023 << context_->GetMinSdkVersion());
2024 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002025 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002026 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002027 return 1;
2028 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030
2031 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002032 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002033 auto split_constraints_iter = options_.split_constraints.begin();
2034 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002036 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2037 << "generating split with configurations '"
2038 << util::Joiner(split_constraints_iter->configs, ", ")
2039 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002040 }
2041
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002042 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002043 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002044 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002045 return 1;
2046 }
2047
2048 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002050 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002051
2052 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002053 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002054 context_->GetDiagnostics()->Error(DiagMessage()
2055 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002056 return 1;
2057 }
2058
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002059 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2060 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002061 return 1;
2062 }
2063
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002064 ++path_iter;
2065 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002066 }
2067 }
2068
2069 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002070 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002071 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002072 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002073 return 1;
2074 }
2075
2076 bool error = false;
2077 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002078 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002079 // (aka, which package the AndroidManifest.xml is coming from).
2080 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002081 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002083 XmlReferenceLinker manifest_linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002084 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002086 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 error = true;
2088 }
2089
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002091 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002092 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002093 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002094 }
2095
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002096 if (options_.generate_java_class_path) {
2097 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002098 error = true;
2099 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002100 }
2101
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002102 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002103 // PackageParser will fail if URIs are removed from
2104 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2106 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 error = true;
2108 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002109 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002110 } else {
2111 error = true;
2112 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002113 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002114
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002115 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002116 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 return 1;
2118 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002119
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002120 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2121 return 1;
2122 }
2123
2124 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002125 return 1;
2126 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002127
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002128 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002129 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002130 return 1;
2131 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002132 }
2133
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002134 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 return 1;
2136 }
2137
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002138 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2139 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 return 1;
2141 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002142 return 0;
2143 }
2144
2145 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002146 LinkOptions options_;
2147 LinkContext* context_;
2148 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002149
Adam Lesinski490595a2017-11-07 17:08:07 -08002150 AppInfo app_info_;
2151
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002152 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002153
2154 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002155 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156
Adam Lesinski8780eb62017-10-31 17:44:39 -07002157 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002158 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002159 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002160
Adam Lesinski8780eb62017-10-31 17:44:39 -07002161 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2162 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2163
2164 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2165 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002166
2167 // The set of shared libraries being used, mapping their assigned package ID to package name.
2168 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002169
2170 // The package name of the base application, if it is included.
2171 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002172};
2173
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002174int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002175 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002176 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002177
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002178 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002179 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002180 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002181 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002182 const std::string path = arg.substr(1, arg.size() - 1);
2183 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2185 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002186 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002187 }
2188 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002189 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002190 }
2191 }
2192
2193 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002194 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002195 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002196 const std::string path = arg.substr(1, arg.size() - 1);
2197 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002198 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002199 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002200 return 1;
2201 }
2202 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002203 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002204 }
2205 }
2206
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002207 if (verbose_) {
2208 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002209 }
2210
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002211 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002212 context.GetDiagnostics()->Error(
2213 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002214 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002215 return 1;
2216 }
2217
Izabela Orlowska84febea2019-06-03 18:34:12 +01002218 if (options_.merge_only && !static_lib_) {
2219 context.GetDiagnostics()->Error(
2220 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2221 return 1;
2222 }
2223
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002224 // The default build type.
2225 context.SetPackageType(PackageType::kApp);
2226 context.SetPackageId(kAppPackageId);
2227
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002228 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002229 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002230 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002231 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002232 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002233 options_.output_format = OutputFormat::kProto;
2234 } else if (proto_format_) {
2235 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002236 }
2237
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002238 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002239 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002240 context.GetDiagnostics()->Error(
2241 DiagMessage() << "can't specify --package-id when not building a regular app");
2242 return 1;
2243 }
2244
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002245 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002246 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002247 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002248 << "' is not a valid integer");
2249 return 1;
2250 }
2251
2252 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002253 if (package_id_int > std::numeric_limits<uint8_t>::max()
2254 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002255 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002256 context.GetDiagnostics()->Error(
2257 DiagMessage() << StringPrintf(
2258 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2259 return 1;
2260 }
2261 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2262 }
2263
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002264 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002265 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002266 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002267 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002268 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002269 }
2270 }
2271
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002272 if (product_list_) {
2273 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002274 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002275 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002276 }
2277 }
2278 }
2279
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002280 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002281 if (!configs_.empty()) {
2282 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002283 if (filter == nullptr) {
2284 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002285 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002286 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002287 }
2288
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002289 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002290 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002291 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002292 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002293 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002294 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002295 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002296 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002297
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002298 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002299 for (const std::string& split_arg : split_args_) {
2300 options_.split_paths.push_back({});
2301 options_.split_constraints.push_back({});
2302 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2303 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002304 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002305 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002306 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002307
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002308 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2309 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2310 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002311 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002312 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002313 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002314
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002315 if (no_compress_regex) {
2316 std::string regex = no_compress_regex.value();
2317 if (util::StartsWith(regex, "@")) {
2318 const std::string path = regex.substr(1, regex.size() -1);
2319 std::string error;
2320 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2321 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2322 return 1;
2323 }
2324 } else {
2325 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2326 }
2327 }
2328
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002329 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002330 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002331 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002332 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2333 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2334 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002336 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002337 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002338 options_.no_auto_version = true;
2339 options_.no_version_vectors = true;
2340 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002341 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002342
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002343 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002344 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002345}
2346
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002347} // namespace aapt