blob: c94b8473ea87c04c328aa0531eaba2dc87f96c97 [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"
Adam Lesinskid5083f62017-01-16 15:07:21 -080030#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070031
Adam Lesinski1ab598f2015-08-14 14:26:04 -070032#include "AppInfo.h"
33#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070034#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080035#include "Locale.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;
73using ::android::StringPiece;
74using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070075
Adam Lesinski1ab598f2015-08-14 14:26:04 -070076namespace aapt {
77
Adam Lesinski64587af2016-02-18 18:33:06 -080078class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070079 public:
Chris Warrington820d72a2017-04-27 15:27:01 +010080 LinkContext(IDiagnostics* diagnostics)
81 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070082 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070083
Adam Lesinskib522f042017-04-21 16:57:59 -070084 PackageType GetPackageType() override {
85 return package_type_;
86 }
87
88 void SetPackageType(PackageType type) {
89 package_type_ = type;
90 }
91
Adam Lesinskid0f492d2017-04-03 18:12:45 -070092 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010093 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070094 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070095
Adam Lesinskid0f492d2017-04-03 18:12:45 -070096 NameMangler* GetNameMangler() override {
97 return &name_mangler_;
98 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070099
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700100 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
101 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700102 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800103
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 const std::string& GetCompilationPackage() override {
105 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700106 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700107
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700108 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800109 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700110 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800111
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700112 uint8_t GetPackageId() override {
113 return package_id_;
114 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700115
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700116 void SetPackageId(uint8_t id) {
117 package_id_ = id;
118 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800119
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700120 SymbolTable* GetExternalSymbols() override {
121 return &symbols_;
122 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800123
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700124 bool IsVerbose() override {
125 return verbose_;
126 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800127
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700128 void SetVerbose(bool val) {
129 verbose_ = val;
130 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800131
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700132 int GetMinSdkVersion() override {
133 return min_sdk_version_;
134 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700135
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 void SetMinSdkVersion(int minSdk) {
137 min_sdk_version_ = minSdk;
138 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700139
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700140 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700141 DISALLOW_COPY_AND_ASSIGN(LinkContext);
142
Adam Lesinskib522f042017-04-21 16:57:59 -0700143 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100144 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700145 NameMangler name_mangler_;
146 std::string compilation_package_;
147 uint8_t package_id_ = 0x0;
148 SymbolTable symbols_;
149 bool verbose_ = false;
150 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700151};
152
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700153// A custom delegate that generates compatible pre-O IDs for use with feature splits.
154// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
155// is interpreted as a negative number. Some verification was wrongly assuming negative values
156// were invalid.
157//
158// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
159// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
160// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800161//
162// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700163class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
164 public:
165 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
166 }
167
168 virtual ~FeatureSplitSymbolTableDelegate() = default;
169
170 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
171 const ResourceName& name,
172 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
173 std::unique_ptr<SymbolTable::Symbol> symbol =
174 DefaultSymbolTableDelegate::FindByName(name, sources);
175 if (symbol == nullptr) {
176 return {};
177 }
178
179 // Check to see if this is an 'id' with the target package.
180 if (name.type == ResourceType::kId && symbol->id) {
181 ResourceId* id = &symbol->id.value();
182 if (id->package_id() > kAppPackageId) {
183 // Rewrite the resource ID to be compatible pre-O.
184 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
185
186 // Check that this doesn't overlap another resource.
187 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
188 // The ID overlaps, so log a message (since this is a weird failure) and fail.
189 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
190 << " for pre-O feature split support");
191 return {};
192 }
193
194 if (context_->IsVerbose()) {
195 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
196 << ") -> (" << rewritten_id << ")");
197 }
198
199 *id = rewritten_id;
200 }
201 }
202 return symbol;
203 }
204
205 private:
206 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
207
208 IAaptContext* context_;
209};
210
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700211static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
212 const StringPiece& path, bool keep_raw_values, bool utf16,
213 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700214 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700215 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
216 << (keep_raw_values ? "true" : "false")
217 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700218 }
219
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700220 switch (format) {
221 case OutputFormat::kApk: {
222 BigBuffer buffer(1024);
223 XmlFlattenerOptions options = {};
224 options.keep_raw_values = keep_raw_values;
225 options.use_utf16 = utf16;
226 XmlFlattener flattener(&buffer, options);
227 if (!flattener.Consume(context, &xml_res)) {
228 return false;
229 }
230
231 io::BigBufferInputStream input_stream(&buffer);
232 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
233 ArchiveEntry::kCompress, writer);
234 } break;
235
236 case OutputFormat::kProto: {
237 pb::XmlNode pb_node;
238 SerializeXmlResourceToPb(xml_res, &pb_node);
239 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
240 writer);
241 } break;
242 }
243 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800244}
245
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700246// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700247static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700248 FileInputStream fin(path);
249 if (fin.HadError()) {
250 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700251 return {};
252 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700253 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800254}
255
Adam Lesinski355f2852016-02-13 20:26:45 -0800256struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700257 bool no_auto_version = false;
258 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900259 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700260 bool no_xml_namespaces = false;
261 bool keep_raw_values = false;
262 bool do_not_compress_anything = false;
263 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700264 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700265 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800266};
267
Adam Lesinskic744ae82017-05-17 19:28:38 -0700268// A sampling of public framework resource IDs.
269struct R {
270 struct attr {
271 enum : uint32_t {
272 paddingLeft = 0x010100d6u,
273 paddingRight = 0x010100d8u,
274 paddingHorizontal = 0x0101053du,
275
276 paddingTop = 0x010100d7u,
277 paddingBottom = 0x010100d9u,
278 paddingVertical = 0x0101053eu,
279
280 layout_marginLeft = 0x010100f7u,
281 layout_marginRight = 0x010100f9u,
282 layout_marginHorizontal = 0x0101053bu,
283
284 layout_marginTop = 0x010100f8u,
285 layout_marginBottom = 0x010100fau,
286 layout_marginVertical = 0x0101053cu,
287 };
288 };
289};
290
Adam Lesinski355f2852016-02-13 20:26:45 -0800291class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700292 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700293 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700294 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800295
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700296 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800297
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700298 private:
299 struct FileOperation {
300 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700301
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700302 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700303 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700304
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700305 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700306 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700307
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700308 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700309 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700310
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700311 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700312 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700313 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800314
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700315 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800316
Adam Lesinskic744ae82017-05-17 19:28:38 -0700317 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
318 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800319
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700320 ResourceFileFlattenerOptions options_;
321 IAaptContext* context_;
322 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700323 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800324};
325
Adam Lesinskic744ae82017-05-17 19:28:38 -0700326ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
327 IAaptContext* context, proguard::KeepSet* keep_set)
328 : options_(options), context_(context), keep_set_(keep_set) {
329 SymbolTable* symm = context_->GetExternalSymbols();
330
331 // Build up the rules for degrading newer attributes to older ones.
332 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
333 // generated from the attribute definitions themselves (b/62028956).
334 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
335 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800336 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
337 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700338 };
339 rules_[R::attr::paddingHorizontal] =
340 util::make_unique<DegradeToManyRule>(std::move(replacements));
341 }
342
343 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
344 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800345 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
346 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700347 };
348 rules_[R::attr::paddingVertical] =
349 util::make_unique<DegradeToManyRule>(std::move(replacements));
350 }
351
352 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
353 std::vector<ReplacementAttr> replacements{
354 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800355 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700356 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800357 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700358 };
359 rules_[R::attr::layout_marginHorizontal] =
360 util::make_unique<DegradeToManyRule>(std::move(replacements));
361 }
362
363 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
364 std::vector<ReplacementAttr> replacements{
365 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800366 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700367 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800368 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700369 };
370 rules_[R::attr::layout_marginVertical] =
371 util::make_unique<DegradeToManyRule>(std::move(replacements));
372 }
373}
374
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700375uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
376 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700377 return 0;
378 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800379
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700380 for (const std::string& extension : options_.extensions_to_not_compress) {
381 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700382 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800383 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700384 }
385 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800386}
387
Adam Lesinskibb94f322017-07-12 07:41:55 -0700388static bool IsTransitionElement(const std::string& name) {
389 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
390 name == "changeImageTransform" || name == "changeTransform" ||
391 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
392 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
393 name == "transitionManager";
394}
395
396static bool IsVectorElement(const std::string& name) {
397 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000398 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700399}
400
Adam Lesinskic744ae82017-05-17 19:28:38 -0700401template <typename T>
402std::vector<T> make_singleton_vec(T&& val) {
403 std::vector<T> vec;
404 vec.emplace_back(std::forward<T>(val));
405 return vec;
406}
407
408std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
409 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700410 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700411 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700412
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700413 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700414 context_->GetDiagnostics()->Note(DiagMessage()
415 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700416 }
417
Adam Lesinski00451162017-10-03 07:44:08 -0700418 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
419 // that existing projects have out-of-date references which pass compilation.
420 xml::StripAndroidStudioAttributes(doc->root.get());
421
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700422 XmlReferenceLinker xml_linker;
423 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700424 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700425 }
426
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700427 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700428 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700429 }
430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431 if (options_.no_xml_namespaces) {
432 XmlNamespaceRemover namespace_remover;
433 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700434 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800435 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700436 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800437
Adam Lesinskibb94f322017-07-12 07:41:55 -0700438 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700439 return make_singleton_vec(std::move(file_op->xml_to_flatten));
440 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700441
Adam Lesinskibb94f322017-07-12 07:41:55 -0700442 if (options_.no_version_vectors || options_.no_version_transitions) {
443 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700444 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700445 if (el && el->namespace_uri.empty()) {
446 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
447 (options_.no_version_transitions && IsTransitionElement(el->name))) {
448 return make_singleton_vec(std::move(file_op->xml_to_flatten));
449 }
450 }
451 }
452
Adam Lesinskic744ae82017-05-17 19:28:38 -0700453 const ConfigDescription& config = file_op->config;
454 ResourceEntry* entry = file_op->entry;
455
456 XmlCompatVersioner xml_compat_versioner(&rules_);
457 const util::Range<ApiVersion> api_range{config.sdkVersion,
458 FindNextApiVersionForConfig(entry, config)};
459 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800460}
461
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800462ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
463 switch (format) {
464 case OutputFormat::kApk:
465 return ResourceFile::Type::kBinaryXml;
466 case OutputFormat::kProto:
467 return ResourceFile::Type::kProtoXml;
468 }
469 LOG_ALWAYS_FATAL("unreachable");
470 return ResourceFile::Type::kUnknown;
471}
472
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700473bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700474 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700475 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800476
Adam Koskidc21dea2017-07-21 10:55:27 -0700477 proguard::CollectResourceReferences(context_, table, keep_set_);
478
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700479 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700480 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
481
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700482 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700484 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700485 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800486
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 // Populate the queue with all files in the ResourceTable.
488 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700489 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700490 // WARNING! Do not insert or remove any resources while executing in this scope. It will
491 // corrupt the iteration order.
492
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700493 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700494 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700495 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700496 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700497
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700498 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700499 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700500 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700501 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700502 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700503 }
504
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700505 FileOperation file_op;
506 file_op.entry = entry.get();
507 file_op.dst_path = *file_ref->path;
508 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700510
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700511 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700512 (file_ref->type == ResourceFile::Type::kBinaryXml ||
513 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700514 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700515 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700516 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700517 << "failed to open file");
518 return false;
519 }
520
Adam Lesinski00451162017-10-03 07:44:08 -0700521 if (file_ref->type == ResourceFile::Type::kProtoXml) {
522 pb::XmlNode pb_xml_node;
523 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
524 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700525 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700526 return false;
527 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700528
Adam Lesinski00451162017-10-03 07:44:08 -0700529 std::string error;
530 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
531 if (file_op.xml_to_flatten == nullptr) {
532 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700533 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700534 return false;
535 }
536 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700537 std::string error_str;
538 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700539 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700540 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
541 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700542 return false;
543 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 }
545
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800546 // Update the type that this file will be written as.
547 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
548
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700549 file_op.xml_to_flatten->file.config = config_value->config;
550 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700551 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700553
554 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
555 // else we end up copying the string in the std::make_pair() method,
556 // then creating a StringPiece from the copy, which would cause us
557 // to end up referencing garbage in the map.
558 const StringPiece entry_name(entry->name);
559 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
560 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 }
562 }
563
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700564 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700565 for (auto& map_entry : config_sorted_files) {
566 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700567 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700568
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700569 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700570 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
571 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700572 if (versioned_docs.empty()) {
573 error = true;
574 continue;
575 }
576
Adam Lesinskic744ae82017-05-17 19:28:38 -0700577 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
578 std::string dst_path = file_op.dst_path;
579 if (doc->file.config != file_op.config) {
580 // Only add the new versioned configurations.
581 if (context_->IsVerbose()) {
582 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
583 << "auto-versioning resource from config '"
584 << config << "' -> '" << doc->file.config << "'");
585 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700586
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800587 const ResourceFile& file = doc->file;
588 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
589
590 std::unique_ptr<FileReference> file_ref =
591 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
592 file_ref->SetSource(doc->file.source);
593 // Update the output format of this XML file.
594 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
595 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
596 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700597 return false;
598 }
599 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700600
601 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
602 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 }
604 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700605 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
606 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700607 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700609 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700610 }
611 return !error;
612}
613
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700614static bool WriteStableIdMapToPath(IDiagnostics* diag,
615 const std::unordered_map<ResourceName, ResourceId>& id_map,
616 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800617 io::FileOutputStream fout(id_map_path);
618 if (fout.HadError()) {
619 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620 return false;
621 }
622
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800623 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700624 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625 const ResourceName& name = entry.first;
626 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800627 printer.Print(name.to_string());
628 printer.Print(" = ");
629 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800631 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800633 if (fout.HadError()) {
634 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700635 return false;
636 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700637 return true;
638}
639
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700640static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
641 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700643 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700644 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700645 return false;
646 }
647
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700648 out_id_map->clear();
649 size_t line_no = 0;
650 for (StringPiece line : util::Tokenize(content, '\n')) {
651 line_no++;
652 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 if (line.empty()) {
654 continue;
655 }
656
657 auto iter = std::find(line.begin(), line.end(), '=');
658 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700659 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700660 return false;
661 }
662
663 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700664 StringPiece res_name_str =
665 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
666 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700667 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
668 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700669 return false;
670 }
671
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700672 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
673 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700674 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700676 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
677 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700678 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
679 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700680 return false;
681 }
682
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700683 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 }
685 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700686}
687
Adam Lesinskic6284372017-12-04 13:46:23 -0800688static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
689 using namespace android;
690
691 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
692 // we're looking for the first attribute resource in the system package.
693 const ResTable& table = assets.getResources(true);
694 Res_value val;
695 ssize_t idx = table.getResource(0x01010000, &val, true);
696 if (idx != NO_ERROR) {
697 // Try as a bag.
698 const ResTable::bag_entry* entry;
699 ssize_t cnt = table.lockBag(0x01010000, &entry);
700 if (cnt >= 0) {
701 idx = entry->stringBlock;
702 }
703 table.unlockBag(entry);
704 }
705
706 if (idx < 0) {
707 return 0;
708 }
709 return table.getTableCookie(idx);
710}
711
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700712class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700714 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 : options_(options),
716 context_(context),
717 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700718 file_collection_(util::make_unique<io::FileCollection>()) {
719 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700720
Adam Lesinskic6284372017-12-04 13:46:23 -0800721 void ExtractCompileSdkVersions(android::AssetManager* assets) {
722 using namespace android;
723
724 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
725 if (cookie == 0) {
726 // No Framework assets loaded. Not a failure.
727 return;
728 }
729
730 std::unique_ptr<Asset> manifest(
731 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
732 if (manifest == nullptr) {
733 // No errors.
734 return;
735 }
736
737 std::string error;
738 std::unique_ptr<xml::XmlResource> manifest_xml =
739 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
740 if (manifest_xml == nullptr) {
741 // No errors.
742 return;
743 }
744
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700745 if (!options_.manifest_fixer_options.compile_sdk_version) {
746 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
747 if (attr != nullptr) {
748 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
749 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
750 switch (prim->value.dataType) {
751 case Res_value::TYPE_INT_DEC:
752 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
753 break;
754 case Res_value::TYPE_INT_HEX:
755 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
756 break;
757 default:
758 break;
759 }
760 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
761 compile_sdk_version = *str->value;
762 } else {
763 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800764 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800765 }
766 }
767
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700768 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
769 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
770 if (attr != nullptr) {
771 Maybe<std::string>& compile_sdk_version_codename =
772 options_.manifest_fixer_options.compile_sdk_version_codename;
773 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
774 compile_sdk_version_codename = *str->value;
775 } else {
776 compile_sdk_version_codename = attr->value;
777 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800778 }
779 }
780 }
781
Adam Lesinski8780eb62017-10-31 17:44:39 -0700782 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800783 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700784 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700785 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700786 for (const std::string& path : options_.include_paths) {
787 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700788 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700789 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700790
Adam Lesinski8780eb62017-10-31 17:44:39 -0700791 std::string error;
792 auto zip_collection = io::ZipFileCollection::Create(path, &error);
793 if (zip_collection == nullptr) {
794 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
795 return false;
796 }
797
798 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
799 // Load this as a static library include.
800 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
801 Source(path), std::move(zip_collection), context_->GetDiagnostics());
802 if (static_apk == nullptr) {
803 return false;
804 }
805
Adam Lesinskib522f042017-04-21 16:57:59 -0700806 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800807 // Can't include static libraries when not building a static library (they have no IDs
808 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700809 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800810 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700811 return false;
812 }
813
Adam Lesinski8780eb62017-10-31 17:44:39 -0700814 ResourceTable* table = static_apk->GetResourceTable();
815
816 // If we are using --no-static-lib-packages, we need to rename the package of this table to
817 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700818 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800819 // Since package names can differ, and multiple packages can exist in a ResourceTable,
820 // we place the requirement that all static libraries are built with the package
821 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700822 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700823 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800824 } else {
825 context_->GetDiagnostics()->Error(DiagMessage(path)
826 << "no package with ID 0x7f found in static library");
827 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700828 }
829 }
830
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700831 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700832 util::make_unique<ResourceTableSymbolSource>(table));
833 static_library_includes_.push_back(std::move(static_apk));
834 } else {
835 if (!asset_source->AddAssetPath(path)) {
836 context_->GetDiagnostics()->Error(DiagMessage()
837 << "failed to load include path " << path);
838 return false;
839 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700840 }
841 }
842
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800843 // Capture the shared libraries so that the final resource table can be properly flattened
844 // with support for shared libraries.
845 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700846 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800847 // Capture the included base feature package.
848 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800849 } else if (entry.first == kFrameworkPackageId) {
850 // Try to embed which version of the framework we're compiling against.
851 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
852 // when linking our synthesized 'android:compileSdkVersion' attribute.
853 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
854 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
855 if (symbol != nullptr && symbol->is_public) {
856 // The symbol is present and public, extract the android:versionName and
857 // android:versionCode from the framework AndroidManifest.xml.
858 ExtractCompileSdkVersions(asset_source->GetAssetManager());
859 }
Todd Kennedy32512992018-04-25 16:45:59 -0700860 } else if (asset_source->IsPackageDynamic(entry.first)) {
861 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800862 }
863 }
864
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700865 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700866 return true;
867 }
868
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800869 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700870 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800871 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
872 if (manifest_el == nullptr) {
873 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700874 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800875
876 AppInfo app_info;
877
878 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
879 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
880 return {};
881 }
882
883 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
884 if (!package_attr) {
885 diag->Error(DiagMessage(xml_res->file.source)
886 << "<manifest> must have a 'package' attribute");
887 return {};
888 }
889 app_info.package = package_attr->value;
890
891 if (xml::Attribute* version_code_attr =
892 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
893 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
894 if (!maybe_code) {
895 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
896 << "invalid android:versionCode '" << version_code_attr->value << "'");
897 return {};
898 }
899 app_info.version_code = maybe_code.value();
900 }
901
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700902 if (xml::Attribute* version_code_major_attr =
903 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
904 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
905 if (!maybe_code) {
906 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
907 << "invalid android:versionCodeMajor '"
908 << version_code_major_attr->value << "'");
909 return {};
910 }
911 app_info.version_code_major = maybe_code.value();
912 }
913
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800914 if (xml::Attribute* revision_code_attr =
915 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
916 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
917 if (!maybe_code) {
918 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
919 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
920 return {};
921 }
922 app_info.revision_code = maybe_code.value();
923 }
924
925 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
926 if (!split_name_attr->value.empty()) {
927 app_info.split_name = split_name_attr->value;
928 }
929 }
930
931 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
932 if (xml::Attribute* min_sdk =
933 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700934 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800935 }
936 }
937 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700938 }
939
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700940 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
941 // Postcondition: ResourceTable has only one package left. All others are
942 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700943 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700944 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700945 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
946 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700947 };
948
949 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700950 for (const auto& package : final_table_.packages) {
951 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700952 // We have a package that is not related to the one we're building!
953 for (const auto& type : package->types) {
954 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700955 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700956
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700957 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700958 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700959 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700960 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
961 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
962 << "generated id '" << res_name
963 << "' for external package '" << package->name
964 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700965 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700966 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
967 << "defined resource '" << res_name
968 << "' for external package '" << package->name
969 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700970 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700971 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700972 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700973 }
974 }
975 }
976 }
977
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700978 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
979 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700980 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700981 return !error;
982 }
983
984 /**
985 * Returns true if no IDs have been set, false otherwise.
986 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700987 bool VerifyNoIdsSet() {
988 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700989 for (const auto& type : package->types) {
990 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800991 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
992 << StringPrintf("%02x", type->id.value())
993 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700994 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700995 }
996
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700997 for (const auto& entry : type->entries) {
998 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 ResourceNameRef res_name(package->name, type->type, entry->name);
1000 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001001 DiagMessage() << "entry " << res_name << " has ID "
1002 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001003 return false;
1004 }
1005 }
1006 }
1007 }
1008 return true;
1009 }
1010
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1012 if (options_.output_to_directory) {
1013 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001014 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001015 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 }
1017 }
1018
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001019 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1020 switch (format) {
1021 case OutputFormat::kApk: {
1022 BigBuffer buffer(1024);
1023 TableFlattener flattener(options_.table_flattener_options, &buffer);
1024 if (!flattener.Consume(context_, table)) {
1025 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1026 return false;
1027 }
1028
1029 io::BigBufferInputStream input_stream(&buffer);
1030 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1031 ArchiveEntry::kAlign, writer);
1032 } break;
1033
1034 case OutputFormat::kProto: {
1035 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001036 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001037 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1038 ArchiveEntry::kCompress, writer);
1039 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001040 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001041 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001042 }
1043
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001044 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001045 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001046 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001047 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001048 return true;
1049 }
1050
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001051 std::string out_path;
1052 std::unique_ptr<io::FileOutputStream> fout;
1053 if (options_.generate_java_class_path) {
1054 out_path = options_.generate_java_class_path.value();
1055 file::AppendPath(&out_path, file::PackageToPath(out_package));
1056 if (!file::mkdirs(out_path)) {
1057 context_->GetDiagnostics()->Error(DiagMessage()
1058 << "failed to create directory '" << out_path << "'");
1059 return false;
1060 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001062 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001064 fout = util::make_unique<io::FileOutputStream>(out_path);
1065 if (fout->HadError()) {
1066 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1067 << "': " << fout->GetError());
1068 return false;
1069 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001070 }
1071
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001072 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001073 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001074 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1075 if (fout_text->HadError()) {
1076 context_->GetDiagnostics()->Error(DiagMessage()
1077 << "failed writing to '" << out_text_symbols_path.value()
1078 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001079 return false;
1080 }
1081 }
1082
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001083 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001084 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001085 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086 return false;
1087 }
1088
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001089 return true;
1090 }
1091
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001092 bool GenerateJavaClasses() {
1093 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1094 std::vector<std::string> packages_to_callback;
1095
1096 JavaClassGeneratorOptions template_options;
1097 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1098 template_options.javadoc_annotations = options_.javadoc_annotations;
1099
1100 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1101 template_options.use_final = false;
1102 }
1103
1104 if (context_->GetPackageType() == PackageType::kSharedLib) {
1105 template_options.use_final = false;
1106 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1107 }
1108
1109 const StringPiece actual_package = context_->GetCompilationPackage();
1110 StringPiece output_package = context_->GetCompilationPackage();
1111 if (options_.custom_java_package) {
1112 // Override the output java package to the custom one.
1113 output_package = options_.custom_java_package.value();
1114 }
1115
1116 // Generate the private symbols if required.
1117 if (options_.private_symbols) {
1118 packages_to_callback.push_back(options_.private_symbols.value());
1119
1120 // If we defined a private symbols package, we only emit Public symbols
1121 // to the original package, and private and public symbols to the private package.
1122 JavaClassGeneratorOptions options = template_options;
1123 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1124 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1125 options)) {
1126 return false;
1127 }
1128 }
1129
1130 // Generate copies of the original package R class but with different package names.
1131 // This is to support non-namespaced builds.
1132 for (const std::string& extra_package : options_.extra_java_packages) {
1133 packages_to_callback.push_back(extra_package);
1134
1135 JavaClassGeneratorOptions options = template_options;
1136 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1137 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1138 return false;
1139 }
1140 }
1141
1142 // Generate R classes for each package that was merged (static library).
1143 // Use the actual package's resources only.
1144 for (const std::string& package : table_merger_->merged_packages()) {
1145 packages_to_callback.push_back(package);
1146
1147 JavaClassGeneratorOptions options = template_options;
1148 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1149 if (!WriteJavaFile(&final_table_, package, package, options)) {
1150 return false;
1151 }
1152 }
1153
1154 // Generate the main public R class.
1155 JavaClassGeneratorOptions options = template_options;
1156
1157 // Only generate public symbols if we have a private package.
1158 if (options_.private_symbols) {
1159 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1160 }
1161
1162 if (options.rewrite_callback_options) {
1163 options.rewrite_callback_options.value().packages_to_callback =
1164 std::move(packages_to_callback);
1165 }
1166
1167 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1168 options_.generate_text_symbols_path)) {
1169 return false;
1170 }
1171
1172 return true;
1173 }
1174
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001175 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1176 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001177 return true;
1178 }
1179
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001180 std::unique_ptr<ClassDefinition> manifest_class =
1181 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001182
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001183 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184 // Something bad happened, but we already logged it, so exit.
1185 return false;
1186 }
1187
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001188 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189 // Empty Manifest class, no need to generate it.
1190 return true;
1191 }
1192
1193 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001194 for (const std::string& annotation : options_.javadoc_annotations) {
1195 std::string proper_annotation = "@";
1196 proper_annotation += annotation;
1197 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 }
1199
Adam Lesinski0d81f702017-06-27 15:51:09 -07001200 const std::string package_utf8 =
1201 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001203 std::string out_path = options_.generate_java_class_path.value();
1204 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001206 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001207 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1208 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001209 return false;
1210 }
1211
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001212 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001213
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001214 io::FileOutputStream fout(out_path);
1215 if (fout.HadError()) {
1216 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1217 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 return false;
1219 }
1220
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001221 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1222 fout.Flush();
1223
1224 if (fout.HadError()) {
1225 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1226 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001227 return false;
1228 }
1229 return true;
1230 }
1231
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001232 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233 if (!out) {
1234 return true;
1235 }
1236
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001237 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001238 io::FileOutputStream fout(out_path);
1239 if (fout.HadError()) {
1240 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1241 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 return false;
1243 }
1244
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001245 proguard::WriteKeepSet(keep_set, &fout);
1246 fout.Flush();
1247
1248 if (fout.HadError()) {
1249 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1250 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251 return false;
1252 }
1253 return true;
1254 }
1255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 bool MergeStaticLibrary(const std::string& input, bool override) {
1257 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001258 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 }
1260
Adam Lesinski8780eb62017-10-31 17:44:39 -07001261 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1262 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001263 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 return false;
1265 }
1266
Adam Lesinski8780eb62017-10-31 17:44:39 -07001267 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001268 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001269 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001270 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001271 return false;
1272 }
1273
1274 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001275 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001276 // Merge all resources as if they were in the compilation package. This is the old behavior
1277 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001279 // Add the package to the set of --extra-packages so we emit an R.java for each library
1280 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001282 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001283 }
1284
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001285 // Clear the package name, so as to make the resources look like they are coming from the
1286 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001287 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001288 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001289
1290 } else {
1291 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001292 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001293 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 }
1295
1296 if (!result) {
1297 return false;
1298 }
1299
1300 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001301 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 return true;
1303 }
1304
Adam Lesinski2427dce2017-11-30 15:10:28 -08001305 bool MergeExportedSymbols(const Source& source,
1306 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001308 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001309 ResourceName res_name = exported_symbol.name;
1310 if (res_name.package.empty()) {
1311 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312 }
1313
Adam Lesinski00451162017-10-03 07:44:08 -07001314 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001315 if (mangled_name) {
1316 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 }
1318
1319 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001320 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001321 bool result =
1322 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1323 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324 if (!result) {
1325 return false;
1326 }
1327 }
1328 return true;
1329 }
1330
Adam Lesinski2427dce2017-11-30 15:10:28 -08001331 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1332 if (context_->IsVerbose()) {
1333 context_->GetDiagnostics()->Note(DiagMessage()
1334 << "merging '" << compiled_file.name
1335 << "' from compiled file " << compiled_file.source);
1336 }
1337
1338 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1339 return false;
1340 }
1341 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1342 }
1343
Adam Lesinski00451162017-10-03 07:44:08 -07001344 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1345 // If override is true, conflicting resources are allowed to override each other, in order of last
1346 // seen.
1347 // An io::IFileCollection is created from the ZIP file and added to the set of
1348 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001349 bool MergeArchive(const std::string& input, bool override) {
1350 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001351 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001352 }
1353
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001355 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001356 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001357 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001358 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001359 return false;
1360 }
1361
1362 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001363 for (auto iter = collection->Iterator(); iter->HasNext();) {
1364 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001365 error = true;
1366 }
1367 }
1368
1369 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001370 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001371 return !error;
1372 }
1373
Adam Lesinski00451162017-10-03 07:44:08 -07001374 // Takes a path to load and merge into the master ResourceTable. If override is true,
1375 // conflicting resources are allowed to override each other, in order of last seen.
1376 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1377 // as ZIP archive and the files within are merged individually.
1378 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 bool MergePath(const std::string& path, bool override) {
1380 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1381 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1382 return MergeArchive(path, override);
1383 } else if (util::EndsWith(path, ".apk")) {
1384 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001385 }
1386
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001387 io::IFile* file = file_collection_->InsertFile(path);
1388 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001389 }
1390
Adam Lesinski00451162017-10-03 07:44:08 -07001391 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1392 // If override is true, conflicting resources are allowed to override each other, in order of last
1393 // seen.
1394 // All other file types are ignored. This is because these files could be coming from a zip,
1395 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001396 bool MergeFile(io::IFile* file, bool override) {
1397 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398
Adam Lesinski00451162017-10-03 07:44:08 -07001399 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001400 // Since AAPT compiles these file types and appends .flat to them, seeing
1401 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001402 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1403 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1404 << " file passed as argument. Must be "
1405 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001406 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001407 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1408 if (context_->IsVerbose()) {
1409 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1410 return true;
1411 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001412 }
1413
Adam Lesinski00451162017-10-03 07:44:08 -07001414 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1415 if (input_stream == nullptr) {
1416 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1417 return false;
1418 }
1419
1420 if (input_stream->HadError()) {
1421 context_->GetDiagnostics()->Error(DiagMessage(src)
1422 << "failed to open file: " << input_stream->GetError());
1423 return false;
1424 }
1425
1426 ContainerReaderEntry* entry;
1427 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001428
1429 if (reader.HadError()) {
1430 context_->GetDiagnostics()->Error(DiagMessage(src)
1431 << "failed to read file: " << reader.GetError());
1432 return false;
1433 }
1434
Adam Lesinski00451162017-10-03 07:44:08 -07001435 while ((entry = reader.Next()) != nullptr) {
1436 if (entry->Type() == ContainerEntryType::kResTable) {
1437 pb::ResourceTable pb_table;
1438 if (!entry->GetResTable(&pb_table)) {
1439 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1440 << entry->GetError());
1441 return false;
1442 }
1443
1444 ResourceTable table;
1445 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001446 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001447 context_->GetDiagnostics()->Error(DiagMessage(src)
1448 << "failed to deserialize resource table: " << error);
1449 return false;
1450 }
1451
1452 if (!table_merger_->Merge(src, &table, override)) {
1453 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1454 return false;
1455 }
1456 } else if (entry->Type() == ContainerEntryType::kResFile) {
1457 pb::internal::CompiledFile pb_compiled_file;
1458 off64_t offset;
1459 size_t len;
1460 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1461 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1462 << entry->GetError());
1463 return false;
1464 }
1465
1466 ResourceFile resource_file;
1467 std::string error;
1468 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1469 context_->GetDiagnostics()->Error(DiagMessage(src)
1470 << "failed to read compiled header: " << error);
1471 return false;
1472 }
1473
1474 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1475 return false;
1476 }
1477 }
1478 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001479 return true;
1480 }
1481
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001482 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1483 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1484 for (const std::string& assets_dir : options_.assets_dirs) {
1485 Maybe<std::vector<std::string>> files =
1486 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1487 if (!files) {
1488 return false;
1489 }
1490
1491 for (const std::string& file : files.value()) {
1492 std::string full_key = "assets/" + file;
1493 std::string full_path = assets_dir;
1494 file::AppendPath(&full_path, file);
1495
1496 auto iter = merged_assets.find(full_key);
1497 if (iter == merged_assets.end()) {
1498 merged_assets.emplace(std::move(full_key),
1499 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1500 } else if (context_->IsVerbose()) {
1501 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1502 << "asset file overrides '" << full_path << "'");
1503 }
1504 }
1505 }
1506
1507 for (auto& entry : merged_assets) {
1508 uint32_t compression_flags = ArchiveEntry::kCompress;
1509 std::string extension = file::GetExtension(entry.first).to_string();
1510 if (options_.extensions_to_not_compress.count(extension) > 0) {
1511 compression_flags = 0u;
1512 }
1513
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001514 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1515 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001516 return false;
1517 }
1518 }
1519 return true;
1520 }
1521
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001522 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1523 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001524 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1525 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001526 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001527 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1528 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001529 if (!result) {
1530 return false;
1531 }
1532
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001533 ResourceFileFlattenerOptions file_flattener_options;
1534 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001535 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1536 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001537 file_flattener_options.no_auto_version = options_.no_auto_version;
1538 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001539 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001540 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1541 file_flattener_options.update_proguard_spec =
1542 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001543 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001544
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001545 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001546
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001547 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001548 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001549 return false;
1550 }
1551
Adam Lesinski490595a2017-11-07 17:08:07 -08001552 // Hack to fix b/68820737.
1553 // We need to modify the ResourceTable's package name, but that should NOT affect
1554 // anything else being generated, which includes the Java classes.
1555 // If required, the package name is modifed before flattening, and then modified back
1556 // to its original name.
1557 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001558 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1559 // or higher] as invalid. In order to work around this limitation, we allow the use
1560 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1561 // definition of what a valid "split" package ID is to account for this.
1562 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1563 context_->GetPackageId() != kAppPackageId &&
1564 context_->GetPackageId() != kFrameworkPackageId)
1565 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1566 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001567 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1568 // The base APK is included, and this is a feature split. If the base package is
1569 // the same as this package, then we are building an old style Android Instant Apps feature
1570 // split and must apply this workaround to avoid requiring namespaces support.
1571 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1572 if (package_to_rewrite != nullptr) {
1573 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1574
1575 std::string new_package_name =
1576 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1577 app_info_.split_name.value_or_default("feature").c_str());
1578
1579 if (context_->IsVerbose()) {
1580 context_->GetDiagnostics()->Note(
1581 DiagMessage() << "rewriting resource package name for feature split to '"
1582 << new_package_name << "'");
1583 }
1584 package_to_rewrite->name = new_package_name;
1585 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001586 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001587
1588 bool success = FlattenTable(table, options_.output_format, writer);
1589
1590 if (package_to_rewrite != nullptr) {
1591 // Change the name back.
1592 package_to_rewrite->name = context_->GetCompilationPackage();
1593 if (package_to_rewrite->id) {
1594 table->included_packages_.erase(package_to_rewrite->id.value());
1595 }
1596 }
1597
1598 if (!success) {
1599 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1600 }
1601 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001602 }
1603
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001604 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001605 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001606 std::unique_ptr<xml::XmlResource> manifest_xml =
1607 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1608 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001609 return 1;
1610 }
1611
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001612 // First extract the Package name without modifying it (via --rename-manifest-package).
1613 if (Maybe<AppInfo> maybe_app_info =
1614 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001615 const AppInfo& app_info = maybe_app_info.value();
1616 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001617 }
1618
Adam Lesinskic6284372017-12-04 13:46:23 -08001619 // Now that the compilation package is set, load the dependencies. This will also extract
1620 // the Android framework's versionCode and versionName, if they exist.
1621 if (!LoadSymbolsFromIncludePaths()) {
1622 return 1;
1623 }
1624
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001625 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1626 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001627 return 1;
1628 }
1629
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001630 Maybe<AppInfo> maybe_app_info =
1631 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001632 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001633 return 1;
1634 }
1635
Adam Lesinski490595a2017-11-07 17:08:07 -08001636 app_info_ = maybe_app_info.value();
1637 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001639 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001640
1641 // Override the package ID when it is "android".
1642 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001643 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001644
1645 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001646 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001647 context_->GetDiagnostics()->Error(
1648 DiagMessage() << "package 'android' can only be built as a regular app");
1649 return 1;
1650 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001651 }
1652
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001653 TableMergerOptions table_merger_options;
1654 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001655 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001656 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001658 if (context_->IsVerbose()) {
1659 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001660 << StringPrintf("linking package '%s' using package ID %02x",
1661 context_->GetCompilationPackage().data(),
1662 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663 }
1664
Adam Lesinski2427dce2017-11-30 15:10:28 -08001665 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1666 // in res/**/*.
1667 {
1668 XmlIdCollector collector;
1669 if (!collector.Consume(context_, manifest_xml.get())) {
1670 return false;
1671 }
1672
1673 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1674 return false;
1675 }
1676 }
1677
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 for (const std::string& input : input_files) {
1679 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001680 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681 return 1;
1682 }
1683 }
1684
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001685 for (const std::string& input : options_.overlay_files) {
1686 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001687 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688 return 1;
1689 }
1690 }
1691
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001692 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 return 1;
1694 }
1695
Adam Lesinskib522f042017-04-21 16:57:59 -07001696 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001698 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001699 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001700 return 1;
1701 }
1702
1703 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001704 IdAssigner id_assigner(&options_.stable_id_map);
1705 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001706 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707 return 1;
1708 }
1709
1710 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001711 if (options_.resource_id_map_path) {
1712 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 for (auto& type : package->types) {
1714 for (auto& entry : type->entries) {
1715 ResourceName name(package->name, type->type, entry->name);
1716 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001717 options_.stable_id_map[std::move(name)] =
1718 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 }
1720 }
1721 }
1722
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001723 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001725 return 1;
1726 }
1727 }
1728 } else {
1729 // Static libs are merged with other apps, and ID collisions are bad, so
1730 // verify that
1731 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001732 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001733 return 1;
1734 }
1735 }
1736
1737 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001738 context_->SetNameManglerPolicy(
1739 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001740
1741 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 context_->GetExternalSymbols()->PrependSource(
1743 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001744
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001745 // Workaround for pre-O runtime that would treat negative resource IDs
1746 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1747 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1748 // are just identifiers.
1749 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1750 if (context_->IsVerbose()) {
1751 context_->GetDiagnostics()->Note(DiagMessage()
1752 << "enabling pre-O feature split ID rewriting");
1753 }
1754 context_->GetExternalSymbols()->SetDelegate(
1755 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1756 }
1757
Adam Lesinski34a16872018-02-23 16:18:10 -08001758 // Before we process anything, remove the resources whose default values don't exist.
1759 // We want to force any references to these to fail the build.
1760 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1761 context_->GetDiagnostics()->Error(DiagMessage()
1762 << "failed removing resources with no defaults");
1763 return 1;
1764 }
1765
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001766 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001767 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001768 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769 return 1;
1770 }
1771
Adam Lesinskib522f042017-04-21 16:57:59 -07001772 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001773 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001774 context_->GetDiagnostics()->Warn(DiagMessage()
1775 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001776 }
1777 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001778 ProductFilter product_filter(options_.products);
1779 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001780 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001781 return 1;
1782 }
1783 }
1784
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001785 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001786 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001787 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001788 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001789 return 1;
1790 }
1791 }
1792
Adam Lesinskib522f042017-04-21 16:57:59 -07001793 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001794 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001795 context_->GetDiagnostics()->Note(DiagMessage()
1796 << "collapsing resource versions for minimum SDK "
1797 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798 }
1799
1800 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001801 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 return 1;
1803 }
1804 }
1805
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001807 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001808 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001809 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001810 return 1;
1811 }
1812 }
1813
Adam Koskidc21dea2017-07-21 10:55:27 -07001814 proguard::KeepSet proguard_keep_set =
1815 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817
Adam Lesinskib522f042017-04-21 16:57:59 -07001818 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001819 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001820 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001821 context_->GetDiagnostics()->Warn(DiagMessage()
1822 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001823 }
1824 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001825 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1826 // equal to the minSdk.
1827 options_.split_constraints =
1828 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001830 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001831 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001832 return 1;
1833 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001834 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001835
1836 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001837 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001838 auto split_constraints_iter = options_.split_constraints.begin();
1839 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001841 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1842 << "generating split with configurations '"
1843 << util::Joiner(split_constraints_iter->configs, ", ")
1844 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845 }
1846
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001847 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001848 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001849 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 return 1;
1851 }
1852
1853 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001854 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001855 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856
1857 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001858 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001859 context_->GetDiagnostics()->Error(DiagMessage()
1860 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001861 return 1;
1862 }
1863
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001864 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1865 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001866 return 1;
1867 }
1868
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 ++path_iter;
1870 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001871 }
1872 }
1873
1874 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001875 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001877 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001878 return 1;
1879 }
1880
1881 bool error = false;
1882 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001883 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001884 // (aka, which package the AndroidManifest.xml is coming from).
1885 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001886 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001887
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001888 XmlReferenceLinker manifest_linker;
1889 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1890 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001891 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001892 error = true;
1893 }
1894
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001896 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001897 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001899 }
1900
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 if (options_.generate_java_class_path) {
1902 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903 error = true;
1904 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001905 }
1906
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001908 // PackageParser will fail if URIs are removed from
1909 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1911 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001912 error = true;
1913 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001914 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001915 } else {
1916 error = true;
1917 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001918 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001919
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001920 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001921 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922 return 1;
1923 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001924
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001925 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1926 return 1;
1927 }
1928
1929 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001930 return 1;
1931 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001932
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001933 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001934 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001935 return 1;
1936 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 }
1938
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001939 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 return 1;
1941 }
1942
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1944 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 return 1;
1946 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947 return 0;
1948 }
1949
1950 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 LinkOptions options_;
1952 LinkContext* context_;
1953 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001954
Adam Lesinski490595a2017-11-07 17:08:07 -08001955 AppInfo app_info_;
1956
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001958
1959 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001961
Adam Lesinski8780eb62017-10-31 17:44:39 -07001962 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001963 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001964 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965
Adam Lesinski8780eb62017-10-31 17:44:39 -07001966 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1967 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1968
1969 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
1970 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001971
1972 // The set of shared libraries being used, mapping their assigned package ID to package name.
1973 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08001974
1975 // The package name of the base application, if it is included.
1976 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001977};
1978
Ryan Mitchell833a1a62018-07-10 13:51:36 -07001979int LinkCommand::Action(const std::vector<std::string>& args) {
1980 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001981
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001982 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001983 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07001984 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986 const std::string path = arg.substr(1, arg.size() - 1);
1987 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1989 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001990 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001991 }
1992 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001993 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 }
1995 }
1996
1997 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07001998 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 const std::string path = arg.substr(1, arg.size() - 1);
2001 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002002 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002003 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004 return 1;
2005 }
2006 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002007 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002008 }
2009 }
2010
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002011 if (verbose_) {
2012 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002013 }
2014
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002015 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002016 context.GetDiagnostics()->Error(
2017 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002018 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002019 return 1;
2020 }
2021
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002022 // The default build type.
2023 context.SetPackageType(PackageType::kApp);
2024 context.SetPackageId(kAppPackageId);
2025
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002026 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002027 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002028 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002029 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002030 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002031 options_.output_format = OutputFormat::kProto;
2032 } else if (proto_format_) {
2033 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002034 }
2035
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002036 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002037 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002038 context.GetDiagnostics()->Error(
2039 DiagMessage() << "can't specify --package-id when not building a regular app");
2040 return 1;
2041 }
2042
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002043 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002044 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002045 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002046 << "' is not a valid integer");
2047 return 1;
2048 }
2049
2050 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002051 if (package_id_int > std::numeric_limits<uint8_t>::max()
2052 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002053 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002054 context.GetDiagnostics()->Error(
2055 DiagMessage() << StringPrintf(
2056 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2057 return 1;
2058 }
2059 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2060 }
2061
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002062 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002063 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002065 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002066 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002067 }
2068 }
2069
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002070 if (product_list_) {
2071 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002072 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002073 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002074 }
2075 }
2076 }
2077
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002078 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002079 if (!configs_.empty()) {
2080 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002081 if (filter == nullptr) {
2082 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002083 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002084 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002085 }
2086
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002087 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002088 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002089 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002090 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002091 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002092 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002093 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002094 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002095
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002096 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002097 for (const std::string& split_arg : split_args_) {
2098 options_.split_paths.push_back({});
2099 options_.split_constraints.push_back({});
2100 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2101 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002103 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002105
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002106 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2107 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2108 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002109 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002110 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002112
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002113 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002114 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002115 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002116 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2117 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2118 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002120 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002121 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002122 options_.no_auto_version = true;
2123 options_.no_version_vectors = true;
2124 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002125 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002126
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002127 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002128 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002129}
2130
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002131} // namespace aapt