blob: 186f8a159fe72ac13151706d7c5803250e4c7394 [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"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070063#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080064#include "optimize/ResourceDeduper.h"
65#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066#include "process/IResourceTableConsumer.h"
67#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080068#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080070#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070072using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020073using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::android::StringPiece;
75using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070076
Adam Lesinski1ab598f2015-08-14 14:26:04 -070077namespace aapt {
78
Adam Lesinski64587af2016-02-18 18:33:06 -080079class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070080 public:
Chris Warrington820d72a2017-04-27 15:27:01 +010081 LinkContext(IDiagnostics* diagnostics)
82 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070083 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070084
Adam Lesinskib522f042017-04-21 16:57:59 -070085 PackageType GetPackageType() override {
86 return package_type_;
87 }
88
89 void SetPackageType(PackageType type) {
90 package_type_ = type;
91 }
92
Adam Lesinskid0f492d2017-04-03 18:12:45 -070093 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010094 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070095 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070096
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 NameMangler* GetNameMangler() override {
98 return &name_mangler_;
99 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
102 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800104
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 const std::string& GetCompilationPackage() override {
106 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700108
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700109 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800110 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700111 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800112
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700113 uint8_t GetPackageId() override {
114 return package_id_;
115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 void SetPackageId(uint8_t id) {
118 package_id_ = id;
119 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800120
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700121 SymbolTable* GetExternalSymbols() override {
122 return &symbols_;
123 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800124
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700125 bool IsVerbose() override {
126 return verbose_;
127 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800128
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700129 void SetVerbose(bool val) {
130 verbose_ = val;
131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 int GetMinSdkVersion() override {
134 return min_sdk_version_;
135 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetMinSdkVersion(int minSdk) {
138 min_sdk_version_ = minSdk;
139 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700140
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700142 DISALLOW_COPY_AND_ASSIGN(LinkContext);
143
Adam Lesinskib522f042017-04-21 16:57:59 -0700144 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100145 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700146 NameMangler name_mangler_;
147 std::string compilation_package_;
148 uint8_t package_id_ = 0x0;
149 SymbolTable symbols_;
150 bool verbose_ = false;
151 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152};
153
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700154// A custom delegate that generates compatible pre-O IDs for use with feature splits.
155// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
156// is interpreted as a negative number. Some verification was wrongly assuming negative values
157// were invalid.
158//
159// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
160// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
161// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800162//
163// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700164class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
165 public:
166 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
167 }
168
169 virtual ~FeatureSplitSymbolTableDelegate() = default;
170
171 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
172 const ResourceName& name,
173 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
174 std::unique_ptr<SymbolTable::Symbol> symbol =
175 DefaultSymbolTableDelegate::FindByName(name, sources);
176 if (symbol == nullptr) {
177 return {};
178 }
179
180 // Check to see if this is an 'id' with the target package.
181 if (name.type == ResourceType::kId && symbol->id) {
182 ResourceId* id = &symbol->id.value();
183 if (id->package_id() > kAppPackageId) {
184 // Rewrite the resource ID to be compatible pre-O.
185 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
186
187 // Check that this doesn't overlap another resource.
188 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
189 // The ID overlaps, so log a message (since this is a weird failure) and fail.
190 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
191 << " for pre-O feature split support");
192 return {};
193 }
194
195 if (context_->IsVerbose()) {
196 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
197 << ") -> (" << rewritten_id << ")");
198 }
199
200 *id = rewritten_id;
201 }
202 }
203 return symbol;
204 }
205
206 private:
207 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
208
209 IAaptContext* context_;
210};
211
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700212static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
213 const StringPiece& path, bool keep_raw_values, bool utf16,
214 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700215 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700216 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
217 << (keep_raw_values ? "true" : "false")
218 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700219 }
220
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700221 switch (format) {
222 case OutputFormat::kApk: {
223 BigBuffer buffer(1024);
224 XmlFlattenerOptions options = {};
225 options.keep_raw_values = keep_raw_values;
226 options.use_utf16 = utf16;
227 XmlFlattener flattener(&buffer, options);
228 if (!flattener.Consume(context, &xml_res)) {
229 return false;
230 }
231
232 io::BigBufferInputStream input_stream(&buffer);
233 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
234 ArchiveEntry::kCompress, writer);
235 } break;
236
237 case OutputFormat::kProto: {
238 pb::XmlNode pb_node;
239 SerializeXmlResourceToPb(xml_res, &pb_node);
240 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
241 writer);
242 } break;
243 }
244 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800245}
246
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700247// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700248static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700249 FileInputStream fin(path);
250 if (fin.HadError()) {
251 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700252 return {};
253 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700254 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800255}
256
Adam Lesinski355f2852016-02-13 20:26:45 -0800257struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700258 bool no_auto_version = false;
259 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900260 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 bool no_xml_namespaces = false;
262 bool keep_raw_values = false;
263 bool do_not_compress_anything = false;
264 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700265 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700266 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800267};
268
Adam Lesinskic744ae82017-05-17 19:28:38 -0700269// A sampling of public framework resource IDs.
270struct R {
271 struct attr {
272 enum : uint32_t {
273 paddingLeft = 0x010100d6u,
274 paddingRight = 0x010100d8u,
275 paddingHorizontal = 0x0101053du,
276
277 paddingTop = 0x010100d7u,
278 paddingBottom = 0x010100d9u,
279 paddingVertical = 0x0101053eu,
280
281 layout_marginLeft = 0x010100f7u,
282 layout_marginRight = 0x010100f9u,
283 layout_marginHorizontal = 0x0101053bu,
284
285 layout_marginTop = 0x010100f8u,
286 layout_marginBottom = 0x010100fau,
287 layout_marginVertical = 0x0101053cu,
288 };
289 };
290};
291
Adam Lesinski355f2852016-02-13 20:26:45 -0800292class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700293 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700294 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700295 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800296
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700297 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800298
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700299 private:
300 struct FileOperation {
301 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700302
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700303 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700304 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700305
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700306 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700307 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700308
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700309 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700310 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700311
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700312 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700313 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700314 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800315
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800317
Adam Lesinskic744ae82017-05-17 19:28:38 -0700318 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
319 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800320
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 ResourceFileFlattenerOptions options_;
322 IAaptContext* context_;
323 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700324 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800325};
326
Adam Lesinskic744ae82017-05-17 19:28:38 -0700327ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
328 IAaptContext* context, proguard::KeepSet* keep_set)
329 : options_(options), context_(context), keep_set_(keep_set) {
330 SymbolTable* symm = context_->GetExternalSymbols();
331
332 // Build up the rules for degrading newer attributes to older ones.
333 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
334 // generated from the attribute definitions themselves (b/62028956).
335 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
336 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800337 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
338 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700339 };
340 rules_[R::attr::paddingHorizontal] =
341 util::make_unique<DegradeToManyRule>(std::move(replacements));
342 }
343
344 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
345 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800346 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
347 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700348 };
349 rules_[R::attr::paddingVertical] =
350 util::make_unique<DegradeToManyRule>(std::move(replacements));
351 }
352
353 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
354 std::vector<ReplacementAttr> replacements{
355 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800356 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700357 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800358 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700359 };
360 rules_[R::attr::layout_marginHorizontal] =
361 util::make_unique<DegradeToManyRule>(std::move(replacements));
362 }
363
364 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
365 std::vector<ReplacementAttr> replacements{
366 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800367 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700368 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800369 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700370 };
371 rules_[R::attr::layout_marginVertical] =
372 util::make_unique<DegradeToManyRule>(std::move(replacements));
373 }
374}
375
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
377 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700378 return 0;
379 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800380
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700381 for (const std::string& extension : options_.extensions_to_not_compress) {
382 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700383 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800384 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700385 }
386 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800387}
388
Adam Lesinskibb94f322017-07-12 07:41:55 -0700389static bool IsTransitionElement(const std::string& name) {
390 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
391 name == "changeImageTransform" || name == "changeTransform" ||
392 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
393 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
394 name == "transitionManager";
395}
396
397static bool IsVectorElement(const std::string& name) {
398 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000399 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700400}
401
Adam Lesinskic744ae82017-05-17 19:28:38 -0700402template <typename T>
403std::vector<T> make_singleton_vec(T&& val) {
404 std::vector<T> vec;
405 vec.emplace_back(std::forward<T>(val));
406 return vec;
407}
408
409std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
410 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700411 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700412 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700413
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700414 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700415 context_->GetDiagnostics()->Note(DiagMessage()
416 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700417 }
418
Adam Lesinski00451162017-10-03 07:44:08 -0700419 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
420 // that existing projects have out-of-date references which pass compilation.
421 xml::StripAndroidStudioAttributes(doc->root.get());
422
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700423 XmlReferenceLinker xml_linker;
424 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700426 }
427
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700428 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700429 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700430 }
431
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700432 if (options_.no_xml_namespaces) {
433 XmlNamespaceRemover namespace_remover;
434 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700435 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800436 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700437 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800438
Adam Lesinskibb94f322017-07-12 07:41:55 -0700439 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700440 return make_singleton_vec(std::move(file_op->xml_to_flatten));
441 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700442
Adam Lesinskibb94f322017-07-12 07:41:55 -0700443 if (options_.no_version_vectors || options_.no_version_transitions) {
444 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700445 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700446 if (el && el->namespace_uri.empty()) {
447 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
448 (options_.no_version_transitions && IsTransitionElement(el->name))) {
449 return make_singleton_vec(std::move(file_op->xml_to_flatten));
450 }
451 }
452 }
453
Adam Lesinskic744ae82017-05-17 19:28:38 -0700454 const ConfigDescription& config = file_op->config;
455 ResourceEntry* entry = file_op->entry;
456
457 XmlCompatVersioner xml_compat_versioner(&rules_);
458 const util::Range<ApiVersion> api_range{config.sdkVersion,
459 FindNextApiVersionForConfig(entry, config)};
460 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800461}
462
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800463ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
464 switch (format) {
465 case OutputFormat::kApk:
466 return ResourceFile::Type::kBinaryXml;
467 case OutputFormat::kProto:
468 return ResourceFile::Type::kProtoXml;
469 }
470 LOG_ALWAYS_FATAL("unreachable");
471 return ResourceFile::Type::kUnknown;
472}
473
Ryan Mitchell70f79722018-08-13 07:37:24 -0700474static auto kDrawableVersions = std::map<std::string, ApiVersion>{
475 { "adaptive-icon" , SDK_O },
476};
477
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700478bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700479 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700480 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800481
Adam Koskidc21dea2017-07-21 10:55:27 -0700482 proguard::CollectResourceReferences(context_, table, keep_set_);
483
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700484 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700485 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
486
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700488 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700489 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700490 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800491
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 // Populate the queue with all files in the ResourceTable.
493 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700495 // WARNING! Do not insert or remove any resources while executing in this scope. It will
496 // corrupt the iteration order.
497
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700498 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700499 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700500 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700501 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700502
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700503 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700505 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700506 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700507 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700508 }
509
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700510 FileOperation file_op;
511 file_op.entry = entry.get();
512 file_op.dst_path = *file_ref->path;
513 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700514 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700515
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700516 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700517 (file_ref->type == ResourceFile::Type::kBinaryXml ||
518 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700519 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700520 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700521 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 << "failed to open file");
523 return false;
524 }
525
Adam Lesinski00451162017-10-03 07:44:08 -0700526 if (file_ref->type == ResourceFile::Type::kProtoXml) {
527 pb::XmlNode pb_xml_node;
528 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
529 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700530 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700531 return false;
532 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533
Adam Lesinski00451162017-10-03 07:44:08 -0700534 std::string error;
535 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
536 if (file_op.xml_to_flatten == nullptr) {
537 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700538 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700539 return false;
540 }
541 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700542 std::string error_str;
543 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700544 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700545 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
546 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700547 return false;
548 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 }
550
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800551 // Update the type that this file will be written as.
552 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
553
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700554 file_op.xml_to_flatten->file.config = config_value->config;
555 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700556 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700558
559 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
560 // else we end up copying the string in the std::make_pair() method,
561 // then creating a StringPiece from the copy, which would cause us
562 // to end up referencing garbage in the map.
563 const StringPiece entry_name(entry->name);
564 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
565 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 }
567 }
568
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 for (auto& map_entry : config_sorted_files) {
571 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700572 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700574 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700575 // Check minimum sdk versions supported for drawables
576 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
577 if (drawable_entry != kDrawableVersions.end()) {
578 if (drawable_entry->second > context_->GetMinSdkVersion()
579 && drawable_entry->second > config.sdkVersion) {
580 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
581 << "<" << drawable_entry->first << "> elements "
582 << "require a sdk version of at least "
583 << (int16_t) drawable_entry->second);
584 error = true;
585 continue;
586 }
587 }
588
Adam Lesinskic744ae82017-05-17 19:28:38 -0700589 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
590 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700591 if (versioned_docs.empty()) {
592 error = true;
593 continue;
594 }
595
Adam Lesinskic744ae82017-05-17 19:28:38 -0700596 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
597 std::string dst_path = file_op.dst_path;
598 if (doc->file.config != file_op.config) {
599 // Only add the new versioned configurations.
600 if (context_->IsVerbose()) {
601 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
602 << "auto-versioning resource from config '"
603 << config << "' -> '" << doc->file.config << "'");
604 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700605
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800606 const ResourceFile& file = doc->file;
607 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
608
609 std::unique_ptr<FileReference> file_ref =
610 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
611 file_ref->SetSource(doc->file.source);
612 // Update the output format of this XML file.
613 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
614 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
615 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700616 return false;
617 }
618 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700619
620 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
621 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700622 }
623 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700624 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
625 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700626 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700627 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700628 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629 }
630 return !error;
631}
632
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700633static bool WriteStableIdMapToPath(IDiagnostics* diag,
634 const std::unordered_map<ResourceName, ResourceId>& id_map,
635 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800636 io::FileOutputStream fout(id_map_path);
637 if (fout.HadError()) {
638 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700639 return false;
640 }
641
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800642 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700643 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700644 const ResourceName& name = entry.first;
645 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800646 printer.Print(name.to_string());
647 printer.Print(" = ");
648 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800650 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700651
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800652 if (fout.HadError()) {
653 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700654 return false;
655 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700656 return true;
657}
658
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700659static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
660 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700661 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700662 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700663 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 return false;
665 }
666
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700667 out_id_map->clear();
668 size_t line_no = 0;
669 for (StringPiece line : util::Tokenize(content, '\n')) {
670 line_no++;
671 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 if (line.empty()) {
673 continue;
674 }
675
676 auto iter = std::find(line.begin(), line.end(), '=');
677 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700678 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679 return false;
680 }
681
682 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700683 StringPiece res_name_str =
684 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
685 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700686 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
687 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688 return false;
689 }
690
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700691 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
692 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700693 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
696 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700697 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
698 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 return false;
700 }
701
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 }
704 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700705}
706
Adam Lesinskic6284372017-12-04 13:46:23 -0800707static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
708 using namespace android;
709
710 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
711 // we're looking for the first attribute resource in the system package.
712 const ResTable& table = assets.getResources(true);
713 Res_value val;
714 ssize_t idx = table.getResource(0x01010000, &val, true);
715 if (idx != NO_ERROR) {
716 // Try as a bag.
717 const ResTable::bag_entry* entry;
718 ssize_t cnt = table.lockBag(0x01010000, &entry);
719 if (cnt >= 0) {
720 idx = entry->stringBlock;
721 }
722 table.unlockBag(entry);
723 }
724
725 if (idx < 0) {
726 return 0;
727 }
728 return table.getTableCookie(idx);
729}
730
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700731class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700732 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700733 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 : options_(options),
735 context_(context),
736 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700737 file_collection_(util::make_unique<io::FileCollection>()) {
738 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700739
Adam Lesinskic6284372017-12-04 13:46:23 -0800740 void ExtractCompileSdkVersions(android::AssetManager* assets) {
741 using namespace android;
742
743 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
744 if (cookie == 0) {
745 // No Framework assets loaded. Not a failure.
746 return;
747 }
748
749 std::unique_ptr<Asset> manifest(
750 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
751 if (manifest == nullptr) {
752 // No errors.
753 return;
754 }
755
756 std::string error;
757 std::unique_ptr<xml::XmlResource> manifest_xml =
758 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
759 if (manifest_xml == nullptr) {
760 // No errors.
761 return;
762 }
763
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700764 if (!options_.manifest_fixer_options.compile_sdk_version) {
765 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
766 if (attr != nullptr) {
767 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
768 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
769 switch (prim->value.dataType) {
770 case Res_value::TYPE_INT_DEC:
771 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
772 break;
773 case Res_value::TYPE_INT_HEX:
774 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
775 break;
776 default:
777 break;
778 }
779 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
780 compile_sdk_version = *str->value;
781 } else {
782 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800783 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800784 }
785 }
786
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700787 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
788 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
789 if (attr != nullptr) {
790 Maybe<std::string>& compile_sdk_version_codename =
791 options_.manifest_fixer_options.compile_sdk_version_codename;
792 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
793 compile_sdk_version_codename = *str->value;
794 } else {
795 compile_sdk_version_codename = attr->value;
796 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800797 }
798 }
799 }
800
Adam Lesinski8780eb62017-10-31 17:44:39 -0700801 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800802 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700803 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700804 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700805 for (const std::string& path : options_.include_paths) {
806 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700807 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700808 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700809
Adam Lesinski8780eb62017-10-31 17:44:39 -0700810 std::string error;
811 auto zip_collection = io::ZipFileCollection::Create(path, &error);
812 if (zip_collection == nullptr) {
813 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
814 return false;
815 }
816
817 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
818 // Load this as a static library include.
819 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
820 Source(path), std::move(zip_collection), context_->GetDiagnostics());
821 if (static_apk == nullptr) {
822 return false;
823 }
824
Adam Lesinskib522f042017-04-21 16:57:59 -0700825 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800826 // Can't include static libraries when not building a static library (they have no IDs
827 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700828 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800829 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700830 return false;
831 }
832
Adam Lesinski8780eb62017-10-31 17:44:39 -0700833 ResourceTable* table = static_apk->GetResourceTable();
834
835 // If we are using --no-static-lib-packages, we need to rename the package of this table to
836 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700837 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800838 // Since package names can differ, and multiple packages can exist in a ResourceTable,
839 // we place the requirement that all static libraries are built with the package
840 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700841 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700842 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800843 } else {
844 context_->GetDiagnostics()->Error(DiagMessage(path)
845 << "no package with ID 0x7f found in static library");
846 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700847 }
848 }
849
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700850 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700851 util::make_unique<ResourceTableSymbolSource>(table));
852 static_library_includes_.push_back(std::move(static_apk));
853 } else {
854 if (!asset_source->AddAssetPath(path)) {
855 context_->GetDiagnostics()->Error(DiagMessage()
856 << "failed to load include path " << path);
857 return false;
858 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700859 }
860 }
861
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800862 // Capture the shared libraries so that the final resource table can be properly flattened
863 // with support for shared libraries.
864 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700865 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800866 // Capture the included base feature package.
867 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800868 } else if (entry.first == kFrameworkPackageId) {
869 // Try to embed which version of the framework we're compiling against.
870 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
871 // when linking our synthesized 'android:compileSdkVersion' attribute.
872 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
873 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
874 if (symbol != nullptr && symbol->is_public) {
875 // The symbol is present and public, extract the android:versionName and
876 // android:versionCode from the framework AndroidManifest.xml.
877 ExtractCompileSdkVersions(asset_source->GetAssetManager());
878 }
Todd Kennedy32512992018-04-25 16:45:59 -0700879 } else if (asset_source->IsPackageDynamic(entry.first)) {
880 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800881 }
882 }
883
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700884 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700885 return true;
886 }
887
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800888 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700889 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800890 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
891 if (manifest_el == nullptr) {
892 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800894
895 AppInfo app_info;
896
897 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
898 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
899 return {};
900 }
901
902 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
903 if (!package_attr) {
904 diag->Error(DiagMessage(xml_res->file.source)
905 << "<manifest> must have a 'package' attribute");
906 return {};
907 }
908 app_info.package = package_attr->value;
909
910 if (xml::Attribute* version_code_attr =
911 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
912 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
913 if (!maybe_code) {
914 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
915 << "invalid android:versionCode '" << version_code_attr->value << "'");
916 return {};
917 }
918 app_info.version_code = maybe_code.value();
919 }
920
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700921 if (xml::Attribute* version_code_major_attr =
922 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
923 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
924 if (!maybe_code) {
925 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
926 << "invalid android:versionCodeMajor '"
927 << version_code_major_attr->value << "'");
928 return {};
929 }
930 app_info.version_code_major = maybe_code.value();
931 }
932
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800933 if (xml::Attribute* revision_code_attr =
934 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
935 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
936 if (!maybe_code) {
937 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
938 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
939 return {};
940 }
941 app_info.revision_code = maybe_code.value();
942 }
943
944 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
945 if (!split_name_attr->value.empty()) {
946 app_info.split_name = split_name_attr->value;
947 }
948 }
949
950 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
951 if (xml::Attribute* min_sdk =
952 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700953 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800954 }
955 }
956 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700957 }
958
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700959 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
960 // Postcondition: ResourceTable has only one package left. All others are
961 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700962 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700963 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700964 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
965 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700966 };
967
968 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700969 for (const auto& package : final_table_.packages) {
970 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700971 // We have a package that is not related to the one we're building!
972 for (const auto& type : package->types) {
973 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700974 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700975
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700976 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700977 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700978 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700979 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
980 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
981 << "generated id '" << res_name
982 << "' for external package '" << package->name
983 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700984 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700985 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
986 << "defined resource '" << res_name
987 << "' for external package '" << package->name
988 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700989 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700991 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700992 }
993 }
994 }
995 }
996
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700997 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
998 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001000 return !error;
1001 }
1002
1003 /**
1004 * Returns true if no IDs have been set, false otherwise.
1005 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001006 bool VerifyNoIdsSet() {
1007 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001008 for (const auto& type : package->types) {
1009 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001010 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1011 << StringPrintf("%02x", type->id.value())
1012 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001014 }
1015
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 for (const auto& entry : type->entries) {
1017 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001018 ResourceNameRef res_name(package->name, type->type, entry->name);
1019 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001020 DiagMessage() << "entry " << res_name << " has ID "
1021 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 return false;
1023 }
1024 }
1025 }
1026 }
1027 return true;
1028 }
1029
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001030 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1031 if (options_.output_to_directory) {
1032 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001034 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001035 }
1036 }
1037
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001038 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1039 switch (format) {
1040 case OutputFormat::kApk: {
1041 BigBuffer buffer(1024);
1042 TableFlattener flattener(options_.table_flattener_options, &buffer);
1043 if (!flattener.Consume(context_, table)) {
1044 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1045 return false;
1046 }
1047
1048 io::BigBufferInputStream input_stream(&buffer);
1049 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1050 ArchiveEntry::kAlign, writer);
1051 } break;
1052
1053 case OutputFormat::kProto: {
1054 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001055 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001056 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1057 ArchiveEntry::kCompress, writer);
1058 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001059 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001060 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061 }
1062
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001063 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001064 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001065 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001066 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001067 return true;
1068 }
1069
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001070 std::string out_path;
1071 std::unique_ptr<io::FileOutputStream> fout;
1072 if (options_.generate_java_class_path) {
1073 out_path = options_.generate_java_class_path.value();
1074 file::AppendPath(&out_path, file::PackageToPath(out_package));
1075 if (!file::mkdirs(out_path)) {
1076 context_->GetDiagnostics()->Error(DiagMessage()
1077 << "failed to create directory '" << out_path << "'");
1078 return false;
1079 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001080
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001081 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001082
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001083 fout = util::make_unique<io::FileOutputStream>(out_path);
1084 if (fout->HadError()) {
1085 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1086 << "': " << fout->GetError());
1087 return false;
1088 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001089 }
1090
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001091 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001092 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001093 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1094 if (fout_text->HadError()) {
1095 context_->GetDiagnostics()->Error(DiagMessage()
1096 << "failed writing to '" << out_text_symbols_path.value()
1097 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001098 return false;
1099 }
1100 }
1101
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001102 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001103 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001104 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001105 return false;
1106 }
1107
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001108 return true;
1109 }
1110
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001111 bool GenerateJavaClasses() {
1112 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1113 std::vector<std::string> packages_to_callback;
1114
1115 JavaClassGeneratorOptions template_options;
1116 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1117 template_options.javadoc_annotations = options_.javadoc_annotations;
1118
1119 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1120 template_options.use_final = false;
1121 }
1122
1123 if (context_->GetPackageType() == PackageType::kSharedLib) {
1124 template_options.use_final = false;
1125 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1126 }
1127
1128 const StringPiece actual_package = context_->GetCompilationPackage();
1129 StringPiece output_package = context_->GetCompilationPackage();
1130 if (options_.custom_java_package) {
1131 // Override the output java package to the custom one.
1132 output_package = options_.custom_java_package.value();
1133 }
1134
1135 // Generate the private symbols if required.
1136 if (options_.private_symbols) {
1137 packages_to_callback.push_back(options_.private_symbols.value());
1138
1139 // If we defined a private symbols package, we only emit Public symbols
1140 // to the original package, and private and public symbols to the private package.
1141 JavaClassGeneratorOptions options = template_options;
1142 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1143 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1144 options)) {
1145 return false;
1146 }
1147 }
1148
1149 // Generate copies of the original package R class but with different package names.
1150 // This is to support non-namespaced builds.
1151 for (const std::string& extra_package : options_.extra_java_packages) {
1152 packages_to_callback.push_back(extra_package);
1153
1154 JavaClassGeneratorOptions options = template_options;
1155 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1156 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1157 return false;
1158 }
1159 }
1160
1161 // Generate R classes for each package that was merged (static library).
1162 // Use the actual package's resources only.
1163 for (const std::string& package : table_merger_->merged_packages()) {
1164 packages_to_callback.push_back(package);
1165
1166 JavaClassGeneratorOptions options = template_options;
1167 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1168 if (!WriteJavaFile(&final_table_, package, package, options)) {
1169 return false;
1170 }
1171 }
1172
1173 // Generate the main public R class.
1174 JavaClassGeneratorOptions options = template_options;
1175
1176 // Only generate public symbols if we have a private package.
1177 if (options_.private_symbols) {
1178 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1179 }
1180
1181 if (options.rewrite_callback_options) {
1182 options.rewrite_callback_options.value().packages_to_callback =
1183 std::move(packages_to_callback);
1184 }
1185
1186 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1187 options_.generate_text_symbols_path)) {
1188 return false;
1189 }
1190
1191 return true;
1192 }
1193
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001194 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1195 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 return true;
1197 }
1198
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001199 std::unique_ptr<ClassDefinition> manifest_class =
1200 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001201
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001202 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001203 // Something bad happened, but we already logged it, so exit.
1204 return false;
1205 }
1206
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001207 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001208 // Empty Manifest class, no need to generate it.
1209 return true;
1210 }
1211
1212 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001213 for (const std::string& annotation : options_.javadoc_annotations) {
1214 std::string proper_annotation = "@";
1215 proper_annotation += annotation;
1216 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001217 }
1218
Adam Lesinski0d81f702017-06-27 15:51:09 -07001219 const std::string package_utf8 =
1220 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001222 std::string out_path = options_.generate_java_class_path.value();
1223 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001224
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001225 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001226 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1227 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 return false;
1229 }
1230
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001231 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001233 io::FileOutputStream fout(out_path);
1234 if (fout.HadError()) {
1235 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1236 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 return false;
1238 }
1239
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001240 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1241 fout.Flush();
1242
1243 if (fout.HadError()) {
1244 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1245 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246 return false;
1247 }
1248 return true;
1249 }
1250
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001251 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001252 if (!out) {
1253 return true;
1254 }
1255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001257 io::FileOutputStream fout(out_path);
1258 if (fout.HadError()) {
1259 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1260 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 return false;
1262 }
1263
Ryan Mitchell7e5236d2018-09-25 15:20:59 -07001264 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001265 fout.Flush();
1266
1267 if (fout.HadError()) {
1268 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1269 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001270 return false;
1271 }
1272 return true;
1273 }
1274
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001275 bool MergeStaticLibrary(const std::string& input, bool override) {
1276 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001277 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278 }
1279
Adam Lesinski8780eb62017-10-31 17:44:39 -07001280 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1281 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001282 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001283 return false;
1284 }
1285
Adam Lesinski8780eb62017-10-31 17:44:39 -07001286 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001287 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001289 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001290 return false;
1291 }
1292
1293 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001294 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001295 // Merge all resources as if they were in the compilation package. This is the old behavior
1296 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001298 // Add the package to the set of --extra-packages so we emit an R.java for each library
1299 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001300 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001301 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 }
1303
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001304 // Clear the package name, so as to make the resources look like they are coming from the
1305 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001306 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001307 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308
1309 } else {
1310 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001311 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001312 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001313 }
1314
1315 if (!result) {
1316 return false;
1317 }
1318
1319 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001320 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 return true;
1322 }
1323
Adam Lesinski2427dce2017-11-30 15:10:28 -08001324 bool MergeExportedSymbols(const Source& source,
1325 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001326 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001327 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001328 ResourceName res_name = exported_symbol.name;
1329 if (res_name.package.empty()) {
1330 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001331 }
1332
Adam Lesinski00451162017-10-03 07:44:08 -07001333 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001334 if (mangled_name) {
1335 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001336 }
1337
1338 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001339 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001340 bool result =
1341 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1342 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343 if (!result) {
1344 return false;
1345 }
1346 }
1347 return true;
1348 }
1349
Adam Lesinski2427dce2017-11-30 15:10:28 -08001350 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1351 if (context_->IsVerbose()) {
1352 context_->GetDiagnostics()->Note(DiagMessage()
1353 << "merging '" << compiled_file.name
1354 << "' from compiled file " << compiled_file.source);
1355 }
1356
1357 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1358 return false;
1359 }
1360 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1361 }
1362
Adam Lesinski00451162017-10-03 07:44:08 -07001363 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1364 // If override is true, conflicting resources are allowed to override each other, in order of last
1365 // seen.
1366 // An io::IFileCollection is created from the ZIP file and added to the set of
1367 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001368 bool MergeArchive(const std::string& input, bool override) {
1369 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001370 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001371 }
1372
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001373 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001375 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001377 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378 return false;
1379 }
1380
1381 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001382 for (auto iter = collection->Iterator(); iter->HasNext();) {
1383 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001384 error = true;
1385 }
1386 }
1387
1388 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001390 return !error;
1391 }
1392
Adam Lesinski00451162017-10-03 07:44:08 -07001393 // Takes a path to load and merge into the master ResourceTable. If override is true,
1394 // conflicting resources are allowed to override each other, in order of last seen.
1395 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1396 // as ZIP archive and the files within are merged individually.
1397 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001398 bool MergePath(const std::string& path, bool override) {
1399 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1400 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1401 return MergeArchive(path, override);
1402 } else if (util::EndsWith(path, ".apk")) {
1403 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001404 }
1405
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001406 io::IFile* file = file_collection_->InsertFile(path);
1407 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 }
1409
Adam Lesinski00451162017-10-03 07:44:08 -07001410 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1411 // If override is true, conflicting resources are allowed to override each other, in order of last
1412 // seen.
1413 // All other file types are ignored. This is because these files could be coming from a zip,
1414 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 bool MergeFile(io::IFile* file, bool override) {
1416 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417
Adam Lesinski00451162017-10-03 07:44:08 -07001418 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001419 // Since AAPT compiles these file types and appends .flat to them, seeing
1420 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001421 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1422 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1423 << " file passed as argument. Must be "
1424 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001425 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001426 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1427 if (context_->IsVerbose()) {
1428 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1429 return true;
1430 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001431 }
1432
Adam Lesinski00451162017-10-03 07:44:08 -07001433 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1434 if (input_stream == nullptr) {
1435 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1436 return false;
1437 }
1438
1439 if (input_stream->HadError()) {
1440 context_->GetDiagnostics()->Error(DiagMessage(src)
1441 << "failed to open file: " << input_stream->GetError());
1442 return false;
1443 }
1444
1445 ContainerReaderEntry* entry;
1446 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001447
1448 if (reader.HadError()) {
1449 context_->GetDiagnostics()->Error(DiagMessage(src)
1450 << "failed to read file: " << reader.GetError());
1451 return false;
1452 }
1453
Adam Lesinski00451162017-10-03 07:44:08 -07001454 while ((entry = reader.Next()) != nullptr) {
1455 if (entry->Type() == ContainerEntryType::kResTable) {
1456 pb::ResourceTable pb_table;
1457 if (!entry->GetResTable(&pb_table)) {
1458 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1459 << entry->GetError());
1460 return false;
1461 }
1462
1463 ResourceTable table;
1464 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001465 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001466 context_->GetDiagnostics()->Error(DiagMessage(src)
1467 << "failed to deserialize resource table: " << error);
1468 return false;
1469 }
1470
1471 if (!table_merger_->Merge(src, &table, override)) {
1472 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1473 return false;
1474 }
1475 } else if (entry->Type() == ContainerEntryType::kResFile) {
1476 pb::internal::CompiledFile pb_compiled_file;
1477 off64_t offset;
1478 size_t len;
1479 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1480 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1481 << entry->GetError());
1482 return false;
1483 }
1484
1485 ResourceFile resource_file;
1486 std::string error;
1487 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1488 context_->GetDiagnostics()->Error(DiagMessage(src)
1489 << "failed to read compiled header: " << error);
1490 return false;
1491 }
1492
1493 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1494 return false;
1495 }
1496 }
1497 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001498 return true;
1499 }
1500
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001501 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1502 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1503 for (const std::string& assets_dir : options_.assets_dirs) {
1504 Maybe<std::vector<std::string>> files =
1505 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1506 if (!files) {
1507 return false;
1508 }
1509
1510 for (const std::string& file : files.value()) {
1511 std::string full_key = "assets/" + file;
1512 std::string full_path = assets_dir;
1513 file::AppendPath(&full_path, file);
1514
1515 auto iter = merged_assets.find(full_key);
1516 if (iter == merged_assets.end()) {
1517 merged_assets.emplace(std::move(full_key),
1518 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1519 } else if (context_->IsVerbose()) {
1520 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1521 << "asset file overrides '" << full_path << "'");
1522 }
1523 }
1524 }
1525
1526 for (auto& entry : merged_assets) {
1527 uint32_t compression_flags = ArchiveEntry::kCompress;
1528 std::string extension = file::GetExtension(entry.first).to_string();
1529 if (options_.extensions_to_not_compress.count(extension) > 0) {
1530 compression_flags = 0u;
1531 }
1532
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001533 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1534 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001535 return false;
1536 }
1537 }
1538 return true;
1539 }
1540
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001541 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1542 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001543 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1544 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001545 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001546 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1547 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001548 if (!result) {
1549 return false;
1550 }
1551
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001552 ResourceFileFlattenerOptions file_flattener_options;
1553 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001554 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1555 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001556 file_flattener_options.no_auto_version = options_.no_auto_version;
1557 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001558 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001559 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1560 file_flattener_options.update_proguard_spec =
1561 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001562 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001563
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001564 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001565
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001566 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001567 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568 return false;
1569 }
1570
Adam Lesinski490595a2017-11-07 17:08:07 -08001571 // Hack to fix b/68820737.
1572 // We need to modify the ResourceTable's package name, but that should NOT affect
1573 // anything else being generated, which includes the Java classes.
1574 // If required, the package name is modifed before flattening, and then modified back
1575 // to its original name.
1576 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001577 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1578 // or higher] as invalid. In order to work around this limitation, we allow the use
1579 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1580 // definition of what a valid "split" package ID is to account for this.
1581 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1582 context_->GetPackageId() != kAppPackageId &&
1583 context_->GetPackageId() != kFrameworkPackageId)
1584 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1585 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001586 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1587 // The base APK is included, and this is a feature split. If the base package is
1588 // the same as this package, then we are building an old style Android Instant Apps feature
1589 // split and must apply this workaround to avoid requiring namespaces support.
1590 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1591 if (package_to_rewrite != nullptr) {
1592 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1593
1594 std::string new_package_name =
1595 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1596 app_info_.split_name.value_or_default("feature").c_str());
1597
1598 if (context_->IsVerbose()) {
1599 context_->GetDiagnostics()->Note(
1600 DiagMessage() << "rewriting resource package name for feature split to '"
1601 << new_package_name << "'");
1602 }
1603 package_to_rewrite->name = new_package_name;
1604 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001605 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001606
1607 bool success = FlattenTable(table, options_.output_format, writer);
1608
1609 if (package_to_rewrite != nullptr) {
1610 // Change the name back.
1611 package_to_rewrite->name = context_->GetCompilationPackage();
1612 if (package_to_rewrite->id) {
1613 table->included_packages_.erase(package_to_rewrite->id.value());
1614 }
1615 }
1616
1617 if (!success) {
1618 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1619 }
1620 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001621 }
1622
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001623 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001624 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001625 std::unique_ptr<xml::XmlResource> manifest_xml =
1626 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1627 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001628 return 1;
1629 }
1630
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001631 // First extract the Package name without modifying it (via --rename-manifest-package).
1632 if (Maybe<AppInfo> maybe_app_info =
1633 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001634 const AppInfo& app_info = maybe_app_info.value();
1635 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001636 }
1637
Adam Lesinskic6284372017-12-04 13:46:23 -08001638 // Now that the compilation package is set, load the dependencies. This will also extract
1639 // the Android framework's versionCode and versionName, if they exist.
1640 if (!LoadSymbolsFromIncludePaths()) {
1641 return 1;
1642 }
1643
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001644 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1645 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001646 return 1;
1647 }
1648
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001649 Maybe<AppInfo> maybe_app_info =
1650 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001651 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001652 return 1;
1653 }
1654
Adam Lesinski490595a2017-11-07 17:08:07 -08001655 app_info_ = maybe_app_info.value();
1656 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001658 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001659
1660 // Override the package ID when it is "android".
1661 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001662 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001663
1664 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001665 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001666 context_->GetDiagnostics()->Error(
1667 DiagMessage() << "package 'android' can only be built as a regular app");
1668 return 1;
1669 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001670 }
1671
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001672 TableMergerOptions table_merger_options;
1673 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001674 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001675 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001676
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 if (context_->IsVerbose()) {
1678 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001679 << StringPrintf("linking package '%s' using package ID %02x",
1680 context_->GetCompilationPackage().data(),
1681 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001682 }
1683
Adam Lesinski2427dce2017-11-30 15:10:28 -08001684 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1685 // in res/**/*.
1686 {
1687 XmlIdCollector collector;
1688 if (!collector.Consume(context_, manifest_xml.get())) {
1689 return false;
1690 }
1691
1692 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1693 return false;
1694 }
1695 }
1696
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001697 for (const std::string& input : input_files) {
1698 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001699 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001700 return 1;
1701 }
1702 }
1703
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001704 for (const std::string& input : options_.overlay_files) {
1705 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001706 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707 return 1;
1708 }
1709 }
1710
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001711 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 return 1;
1713 }
1714
Adam Lesinskib522f042017-04-21 16:57:59 -07001715 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001717 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001718 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 return 1;
1720 }
1721
1722 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 IdAssigner id_assigner(&options_.stable_id_map);
1724 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001725 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001726 return 1;
1727 }
1728
1729 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001730 if (options_.resource_id_map_path) {
1731 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 for (auto& type : package->types) {
1733 for (auto& entry : type->entries) {
1734 ResourceName name(package->name, type->type, entry->name);
1735 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001736 options_.stable_id_map[std::move(name)] =
1737 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 }
1739 }
1740 }
1741
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001742 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001743 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001744 return 1;
1745 }
1746 }
1747 } else {
1748 // Static libs are merged with other apps, and ID collisions are bad, so
1749 // verify that
1750 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001751 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001752 return 1;
1753 }
1754 }
1755
1756 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001757 context_->SetNameManglerPolicy(
1758 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001759
1760 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001761 context_->GetExternalSymbols()->PrependSource(
1762 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001764 // Workaround for pre-O runtime that would treat negative resource IDs
1765 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1766 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1767 // are just identifiers.
1768 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1769 if (context_->IsVerbose()) {
1770 context_->GetDiagnostics()->Note(DiagMessage()
1771 << "enabling pre-O feature split ID rewriting");
1772 }
1773 context_->GetExternalSymbols()->SetDelegate(
1774 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1775 }
1776
Adam Lesinski34a16872018-02-23 16:18:10 -08001777 // Before we process anything, remove the resources whose default values don't exist.
1778 // We want to force any references to these to fail the build.
1779 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1780 context_->GetDiagnostics()->Error(DiagMessage()
1781 << "failed removing resources with no defaults");
1782 return 1;
1783 }
1784
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001786 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001787 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001788 return 1;
1789 }
1790
Adam Lesinskib522f042017-04-21 16:57:59 -07001791 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001792 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001793 context_->GetDiagnostics()->Warn(DiagMessage()
1794 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 }
1796 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001797 ProductFilter product_filter(options_.products);
1798 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001799 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 return 1;
1801 }
1802 }
1803
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001804 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001805 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001807 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808 return 1;
1809 }
1810 }
1811
Adam Lesinskib522f042017-04-21 16:57:59 -07001812 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001813 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001814 context_->GetDiagnostics()->Note(DiagMessage()
1815 << "collapsing resource versions for minimum SDK "
1816 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 }
1818
1819 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 return 1;
1822 }
1823 }
1824
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001825 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001828 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 return 1;
1830 }
1831 }
1832
Adam Koskidc21dea2017-07-21 10:55:27 -07001833 proguard::KeepSet proguard_keep_set =
1834 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001835 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836
Adam Lesinskib522f042017-04-21 16:57:59 -07001837 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001838 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001839 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001840 context_->GetDiagnostics()->Warn(DiagMessage()
1841 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001842 }
1843 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001844 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1845 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001846 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001847 options_.split_constraints =
1848 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001850 if (origConstraintSize != options_.split_constraints.size()) {
1851 context_->GetDiagnostics()->Warn(DiagMessage()
1852 << "requested to split resources prior to min sdk of "
1853 << context_->GetMinSdkVersion());
1854 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001855 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001856 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001857 return 1;
1858 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860
1861 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001863 auto split_constraints_iter = options_.split_constraints.begin();
1864 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001865 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001866 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1867 << "generating split with configurations '"
1868 << util::Joiner(split_constraints_iter->configs, ", ")
1869 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001870 }
1871
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001872 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001873 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001874 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001875 return 1;
1876 }
1877
1878 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001880 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001881
1882 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001883 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001884 context_->GetDiagnostics()->Error(DiagMessage()
1885 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886 return 1;
1887 }
1888
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001889 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1890 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001891 return 1;
1892 }
1893
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001894 ++path_iter;
1895 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 }
1897 }
1898
1899 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001900 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001902 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903 return 1;
1904 }
1905
1906 bool error = false;
1907 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001908 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001909 // (aka, which package the AndroidManifest.xml is coming from).
1910 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001912
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001913 XmlReferenceLinker manifest_linker;
1914 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1915 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001916 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001917 error = true;
1918 }
1919
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001921 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001922 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001923 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001924 }
1925
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001926 if (options_.generate_java_class_path) {
1927 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001928 error = true;
1929 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001930 }
1931
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 // PackageParser will fail if URIs are removed from
1934 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1936 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 error = true;
1938 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001939 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 } else {
1941 error = true;
1942 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001943 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001944
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001946 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947 return 1;
1948 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001949
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001950 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1951 return 1;
1952 }
1953
1954 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001955 return 1;
1956 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001957
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001958 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001959 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001960 return 1;
1961 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001962 }
1963
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001964 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965 return 1;
1966 }
1967
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1969 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001970 return 1;
1971 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 return 0;
1973 }
1974
1975 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001976 LinkOptions options_;
1977 LinkContext* context_;
1978 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001979
Adam Lesinski490595a2017-11-07 17:08:07 -08001980 AppInfo app_info_;
1981
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001983
1984 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986
Adam Lesinski8780eb62017-10-31 17:44:39 -07001987 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001988 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990
Adam Lesinski8780eb62017-10-31 17:44:39 -07001991 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1992 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1993
1994 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1995 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001996
1997 // The set of shared libraries being used, mapping their assigned package ID to package name.
1998 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001999
2000 // The package name of the base application, if it is included.
2001 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002002};
2003
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002004int LinkCommand::Action(const std::vector<std::string>& args) {
2005 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002007 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002008 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002009 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 const std::string path = arg.substr(1, arg.size() - 1);
2012 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2014 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002015 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 }
2017 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002018 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002019 }
2020 }
2021
2022 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002023 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025 const std::string path = arg.substr(1, arg.size() - 1);
2026 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002027 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 return 1;
2030 }
2031 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002032 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002033 }
2034 }
2035
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002036 if (verbose_) {
2037 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002038 }
2039
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002040 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002041 context.GetDiagnostics()->Error(
2042 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002043 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002044 return 1;
2045 }
2046
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002047 // The default build type.
2048 context.SetPackageType(PackageType::kApp);
2049 context.SetPackageId(kAppPackageId);
2050
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002051 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002052 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002053 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002054 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002055 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002056 options_.output_format = OutputFormat::kProto;
2057 } else if (proto_format_) {
2058 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002059 }
2060
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002061 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002062 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002063 context.GetDiagnostics()->Error(
2064 DiagMessage() << "can't specify --package-id when not building a regular app");
2065 return 1;
2066 }
2067
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002068 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002069 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002070 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002071 << "' is not a valid integer");
2072 return 1;
2073 }
2074
2075 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002076 if (package_id_int > std::numeric_limits<uint8_t>::max()
2077 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002078 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002079 context.GetDiagnostics()->Error(
2080 DiagMessage() << StringPrintf(
2081 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2082 return 1;
2083 }
2084 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2085 }
2086
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002088 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002089 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002091 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092 }
2093 }
2094
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002095 if (product_list_) {
2096 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002097 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002098 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099 }
2100 }
2101 }
2102
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002103 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002104 if (!configs_.empty()) {
2105 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002106 if (filter == nullptr) {
2107 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002108 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002109 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002110 }
2111
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002112 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002114 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002115 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002116 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002117 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002118 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002119 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002120
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002121 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002122 for (const std::string& split_arg : split_args_) {
2123 options_.split_paths.push_back({});
2124 options_.split_constraints.push_back({});
2125 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2126 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002127 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002128 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002129 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002130
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002131 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2132 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2133 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002134 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002135 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002136 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002137
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002138 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002139 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002141 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2142 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2143 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002144
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002146 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002147 options_.no_auto_version = true;
2148 options_.no_version_vectors = true;
2149 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002151
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002152 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002154}
2155
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156} // namespace aapt